@jennifersoft/jennifer5-instrumentation 5.6.5-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,3636 @@
1
+ // src/instrumentations/register-ritm.ts
2
+ import { Hook } from "require-in-the-middle";
3
+
4
+ // src/instrumentations/http-server.ts
5
+ import {
6
+ info,
7
+ warn as warn3,
8
+ configUsingRemoteAddressForWmonid as configUsingRemoteAddressForWmonid2,
9
+ createTransactionCtx,
10
+ releaseTransactionCtx
11
+ } from "@jennifersoft/jennifer5-agent";
12
+
13
+ // src/core/shimmer.ts
14
+ var skipMethods = /* @__PURE__ */ new Set(["caller", "arguments", "name", "length"]);
15
+ var skipMethodSize = skipMethods.size;
16
+ var nonConfigurableModuleExports = /* @__PURE__ */ new WeakMap();
17
+ function copyProperties(original, wrapped) {
18
+ if (original.constructor !== wrapped.constructor) {
19
+ const proto = Object.getPrototypeOf(original);
20
+ Object.setPrototypeOf(wrapped, proto);
21
+ }
22
+ const ownKeys = Reflect.ownKeys(original);
23
+ if (original.length !== wrapped.length) {
24
+ Object.defineProperty(wrapped, "length", { value: original.length, configurable: true });
25
+ }
26
+ if (original.name !== wrapped.name) {
27
+ Object.defineProperty(wrapped, "name", { value: original.name, configurable: true });
28
+ }
29
+ if (ownKeys.length !== 2) {
30
+ for (const key of ownKeys) {
31
+ if (skipMethods.has(key)) continue;
32
+ const descriptor = Object.getOwnPropertyDescriptor(original, key);
33
+ if (descriptor.writable && descriptor.enumerable && descriptor.configurable) {
34
+ wrapped[key] = original[key];
35
+ } else if (descriptor.writable || descriptor.configurable || !Object.hasOwn(wrapped, key)) {
36
+ Object.defineProperty(wrapped, key, descriptor);
37
+ }
38
+ }
39
+ }
40
+ }
41
+ function copyObjectProperties(original, wrapped, skipKey) {
42
+ const ownKeys = Reflect.ownKeys(original);
43
+ for (const key of ownKeys) {
44
+ if (key === skipKey) continue;
45
+ const descriptor = Object.getOwnPropertyDescriptor(original, key);
46
+ if (descriptor.writable && descriptor.enumerable && descriptor.configurable) {
47
+ wrapped[key] = original[key];
48
+ } else if (descriptor.writable || descriptor.configurable || !Object.hasOwn(wrapped, key)) {
49
+ Object.defineProperty(wrapped, key, descriptor);
50
+ }
51
+ }
52
+ }
53
+ function wrap(target, name, wrapper, options) {
54
+ if (typeof wrapper !== "function") {
55
+ throw new TypeError(wrapper ? "Target is not a function" : "No function provided");
56
+ }
57
+ if (target == null) {
58
+ return;
59
+ }
60
+ const descriptor = Object.getOwnPropertyDescriptor(target, name) ?? {
61
+ value: target[name],
62
+ writable: true,
63
+ configurable: true,
64
+ enumerable: false
65
+ };
66
+ if (descriptor.set && (!descriptor.get || options?.replaceGetter)) {
67
+ throw new Error(
68
+ options?.replaceGetter ? "Replacing a getter/setter pair is not supported. Implement if required." : "Replacing setters is not supported. Implement if required."
69
+ );
70
+ }
71
+ const original = descriptor.value ?? (options?.replaceGetter ? target[name] : descriptor.get);
72
+ assertMethod(target, name, original);
73
+ const wrapped = wrapper(original);
74
+ copyProperties(original, wrapped);
75
+ if (descriptor.writable) {
76
+ if (descriptor.configurable && descriptor.enumerable) {
77
+ target[name] = wrapped;
78
+ return target;
79
+ }
80
+ descriptor.value = wrapped;
81
+ } else {
82
+ if (descriptor.get) {
83
+ descriptor.get = options?.replaceGetter ? () => wrapped : wrapped;
84
+ } else {
85
+ descriptor.value = wrapped;
86
+ }
87
+ if (descriptor.configurable === false) {
88
+ let moduleExports = nonConfigurableModuleExports.get(target);
89
+ if (!moduleExports) {
90
+ if (typeof target === "function") {
91
+ const original2 = target;
92
+ moduleExports = function(...args) {
93
+ return original2.apply(original2, args);
94
+ };
95
+ skipMethods.add(name);
96
+ copyProperties(target, moduleExports);
97
+ if (skipMethods.size === skipMethodSize + 1) {
98
+ skipMethods.delete(name);
99
+ }
100
+ } else {
101
+ moduleExports = Object.create(target);
102
+ copyObjectProperties(target, moduleExports, name);
103
+ }
104
+ nonConfigurableModuleExports.set(target, moduleExports);
105
+ }
106
+ target = moduleExports;
107
+ }
108
+ }
109
+ Object.defineProperty(target, name, descriptor);
110
+ return target;
111
+ }
112
+ function assertMethod(target, name, method) {
113
+ if (typeof method !== "function") {
114
+ let message = "No target object provided";
115
+ if (target) {
116
+ if (typeof target !== "object" && typeof target !== "function") {
117
+ message = "Invalid target";
118
+ } else {
119
+ const nameStr = String(name);
120
+ message = method ? `Original method ${nameStr} is not a function` : `No original method ${nameStr}`;
121
+ }
122
+ }
123
+ throw new TypeError(message);
124
+ }
125
+ }
126
+
127
+ // src/core/context-manager.ts
128
+ import { AsyncLocalStorage } from "async_hooks";
129
+ import { generateTxid, configEnable } from "@jennifersoft/jennifer5-agent";
130
+ var TransactionContextManager = class {
131
+ constructor() {
132
+ this._asyncLocalStorage = new AsyncLocalStorage();
133
+ }
134
+ /**
135
+ * Create a new transaction context
136
+ */
137
+ start() {
138
+ const ctx = {
139
+ id: generateTxid(),
140
+ enable: configEnable()
141
+ };
142
+ return ctx;
143
+ }
144
+ /**
145
+ * Run a callback within a transaction context scope
146
+ * All async operations within this scope will automatically have access to the context
147
+ */
148
+ run(ctx, callback) {
149
+ return this._asyncLocalStorage.run(ctx, callback);
150
+ }
151
+ /**
152
+ * Get the current transaction context (if any)
153
+ * This works automatically across async boundaries thanks to AsyncLocalStorage
154
+ */
155
+ getCurrentContext() {
156
+ return this._asyncLocalStorage.getStore();
157
+ }
158
+ };
159
+ var contextManager = new TransactionContextManager();
160
+
161
+ // src/feat/wmonid.ts
162
+ import {
163
+ i64ToBase64,
164
+ base64ToI64,
165
+ configEnableHttpOnlyForWmonidCookie,
166
+ configEnableSecureForWmonidCookie,
167
+ warn
168
+ } from "@jennifersoft/jennifer5-agent";
169
+
170
+ // src/dep/cookie.ts
171
+ var cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/;
172
+ var cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/;
173
+ var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
174
+ var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/;
175
+ var __toString = Object.prototype.toString;
176
+ var NullObject = /* @__PURE__ */ (() => {
177
+ const C = function() {
178
+ };
179
+ C.prototype = /* @__PURE__ */ Object.create(null);
180
+ return C;
181
+ })();
182
+ function parseCookie(str, options) {
183
+ const obj = new NullObject();
184
+ const len = str.length;
185
+ if (len < 2) return obj;
186
+ const dec = options?.decode || decode;
187
+ let index = 0;
188
+ do {
189
+ const eqIdx = eqIndex(str, index, len);
190
+ if (eqIdx === -1) break;
191
+ const endIdx = endIndex(str, index, len);
192
+ if (eqIdx > endIdx) {
193
+ index = str.lastIndexOf(";", eqIdx - 1) + 1;
194
+ continue;
195
+ }
196
+ const key = valueSlice(str, index, eqIdx);
197
+ if (obj[key] === void 0) {
198
+ obj[key] = dec(valueSlice(str, eqIdx + 1, endIdx));
199
+ }
200
+ index = endIdx + 1;
201
+ } while (index < len);
202
+ return obj;
203
+ }
204
+ function stringifySetCookie(_name, _val, _opts) {
205
+ const cookie = typeof _name === "object" ? _name : { ..._opts, name: _name, value: String(_val) };
206
+ const options = typeof _val === "object" ? _val : _opts;
207
+ const enc = options?.encode || encodeURIComponent;
208
+ if (!cookieNameRegExp.test(cookie.name)) {
209
+ throw new TypeError(`argument name is invalid: ${cookie.name}`);
210
+ }
211
+ const value = cookie.value ? enc(cookie.value) : "";
212
+ if (!cookieValueRegExp.test(value)) {
213
+ throw new TypeError(`argument val is invalid: ${cookie.value}`);
214
+ }
215
+ let str = cookie.name + "=" + value;
216
+ if (cookie.maxAge !== void 0) {
217
+ if (!Number.isInteger(cookie.maxAge)) {
218
+ throw new TypeError(`option maxAge is invalid: ${cookie.maxAge}`);
219
+ }
220
+ str += "; Max-Age=" + cookie.maxAge;
221
+ }
222
+ if (cookie.domain) {
223
+ if (!domainValueRegExp.test(cookie.domain)) {
224
+ throw new TypeError(`option domain is invalid: ${cookie.domain}`);
225
+ }
226
+ str += "; Domain=" + cookie.domain;
227
+ }
228
+ if (cookie.path) {
229
+ if (!pathValueRegExp.test(cookie.path)) {
230
+ throw new TypeError(`option path is invalid: ${cookie.path}`);
231
+ }
232
+ str += "; Path=" + cookie.path;
233
+ }
234
+ if (cookie.expires) {
235
+ if (!isDate(cookie.expires) || !Number.isFinite(cookie.expires.valueOf())) {
236
+ throw new TypeError(`option expires is invalid: ${cookie.expires}`);
237
+ }
238
+ str += "; Expires=" + cookie.expires.toUTCString();
239
+ }
240
+ if (cookie.httpOnly) {
241
+ str += "; HttpOnly";
242
+ }
243
+ if (cookie.secure) {
244
+ str += "; Secure";
245
+ }
246
+ if (cookie.partitioned) {
247
+ str += "; Partitioned";
248
+ }
249
+ if (cookie.priority) {
250
+ const priority = typeof cookie.priority === "string" ? cookie.priority.toLowerCase() : void 0;
251
+ switch (priority) {
252
+ case "low":
253
+ str += "; Priority=Low";
254
+ break;
255
+ case "medium":
256
+ str += "; Priority=Medium";
257
+ break;
258
+ case "high":
259
+ str += "; Priority=High";
260
+ break;
261
+ default:
262
+ throw new TypeError(`option priority is invalid: ${cookie.priority}`);
263
+ }
264
+ }
265
+ if (cookie.sameSite) {
266
+ const sameSite = typeof cookie.sameSite === "string" ? cookie.sameSite.toLowerCase() : cookie.sameSite;
267
+ switch (sameSite) {
268
+ case true:
269
+ case "strict":
270
+ str += "; SameSite=Strict";
271
+ break;
272
+ case "lax":
273
+ str += "; SameSite=Lax";
274
+ break;
275
+ case "none":
276
+ str += "; SameSite=None";
277
+ break;
278
+ default:
279
+ throw new TypeError(`option sameSite is invalid: ${cookie.sameSite}`);
280
+ }
281
+ }
282
+ return str;
283
+ }
284
+ function endIndex(str, min, len) {
285
+ const index = str.indexOf(";", min);
286
+ return index === -1 ? len : index;
287
+ }
288
+ function eqIndex(str, min, max) {
289
+ const index = str.indexOf("=", min);
290
+ return index < max ? index : -1;
291
+ }
292
+ function valueSlice(str, min, max) {
293
+ let start = min;
294
+ let end = max;
295
+ do {
296
+ const code = str.charCodeAt(start);
297
+ if (code !== 32 && code !== 9) break;
298
+ } while (++start < end);
299
+ while (end > start) {
300
+ const code = str.charCodeAt(end - 1);
301
+ if (code !== 32 && code !== 9) break;
302
+ end--;
303
+ }
304
+ return str.slice(start, end);
305
+ }
306
+ function decode(str) {
307
+ if (str.indexOf("%") === -1) return str;
308
+ try {
309
+ return decodeURIComponent(str);
310
+ } catch (e) {
311
+ return str;
312
+ }
313
+ }
314
+ function isDate(val) {
315
+ return __toString.call(val) === "[object Date]";
316
+ }
317
+
318
+ // src/feat/wmonid.ts
319
+ var WMONID_COOKIE_NAME = "WMONID";
320
+ var SECONDS_PER_YEAR = 365 * 24 * 60 * 60;
321
+ function getCookie(req, name) {
322
+ const cookieHeader = req.headers?.cookie;
323
+ if (!cookieHeader) {
324
+ return void 0;
325
+ }
326
+ const cookieString = Array.isArray(cookieHeader) ? cookieHeader.join("; ") : cookieHeader;
327
+ const cookies = parseCookie(cookieString);
328
+ return cookies[name];
329
+ }
330
+ function setCookie(res, cookie) {
331
+ const cookieString = stringifySetCookie(cookie);
332
+ const existingSetCookie = res.getHeader("Set-Cookie");
333
+ if (existingSetCookie === void 0) {
334
+ res.setHeader("Set-Cookie", cookieString);
335
+ } else if (Array.isArray(existingSetCookie)) {
336
+ res.setHeader("Set-Cookie", [...existingSetCookie, cookieString]);
337
+ } else {
338
+ res.setHeader("Set-Cookie", [String(existingSetCookie), cookieString]);
339
+ }
340
+ }
341
+ function setNewWmonidCookie(res, txid) {
342
+ const cookieValue = i64ToBase64(txid);
343
+ setCookie(res, {
344
+ name: WMONID_COOKIE_NAME,
345
+ value: cookieValue,
346
+ maxAge: SECONDS_PER_YEAR,
347
+ path: "/",
348
+ secure: configEnableSecureForWmonidCookie(),
349
+ httpOnly: configEnableHttpOnlyForWmonidCookie()
350
+ });
351
+ }
352
+ function getWmonidInCookie(req, res, txid) {
353
+ try {
354
+ const wmonidCookie = getCookie(req, WMONID_COOKIE_NAME);
355
+ if (wmonidCookie) {
356
+ return base64ToI64(wmonidCookie);
357
+ }
358
+ } catch (e) {
359
+ warn(`Failed to get WMONID cookie: ${e}`);
360
+ }
361
+ try {
362
+ setNewWmonidCookie(res, txid);
363
+ } catch (e) {
364
+ warn(`Failed to set WMONID cookie: ${e}`);
365
+ }
366
+ return 0;
367
+ }
368
+
369
+ // src/feat/topology.ts
370
+ import {
371
+ isAgentId,
372
+ domainId,
373
+ agentId,
374
+ generateTxid as generateTxid2,
375
+ configEnableHttpTopologyMode,
376
+ configTopologyHttpHeaderKey,
377
+ warn as warn2
378
+ } from "@jennifersoft/jennifer5-agent";
379
+ var X_DOMAIN_ID = "x-domainid";
380
+ var X_AGENT_ID = "x-agentid";
381
+ function getTopologyInfo(msg) {
382
+ if (!configEnableHttpTopologyMode()) {
383
+ return void 0;
384
+ }
385
+ try {
386
+ const topologyHeaderKey = configTopologyHttpHeaderKey();
387
+ const remoteCallKey = parseNumber(getHeader(msg, topologyHeaderKey));
388
+ const sid = parseNumber(getHeader(msg, X_DOMAIN_ID));
389
+ const oid = parseNumber(getHeader(msg, X_AGENT_ID));
390
+ if ([remoteCallKey, sid, oid].some((v) => v === void 0)) {
391
+ return void 0;
392
+ }
393
+ if (!isAgentId(oid)) {
394
+ return void 0;
395
+ }
396
+ return { remoteCallKey, domainId: sid, oid };
397
+ } catch {
398
+ return void 0;
399
+ }
400
+ }
401
+ function setTopologyResponseHeaders(incoming, res) {
402
+ if (!configEnableHttpTopologyMode()) {
403
+ return;
404
+ }
405
+ try {
406
+ if (!incoming) return;
407
+ if (res.headersSent || res.writableEnded) {
408
+ return;
409
+ }
410
+ const currentDomainId = domainId();
411
+ const currentAgentId = agentId();
412
+ if (!currentDomainId || !currentAgentId) {
413
+ return;
414
+ }
415
+ const topologyHeaderKey = configTopologyHttpHeaderKey();
416
+ res.setHeader(topologyHeaderKey, incoming.remoteCallKey);
417
+ res.setHeader(X_DOMAIN_ID, String(currentDomainId));
418
+ res.setHeader(X_AGENT_ID, String(currentAgentId));
419
+ } catch (error) {
420
+ warn2(`Failed to set topology response headers: ${error}`);
421
+ }
422
+ }
423
+ function setTopologyRequestHeaders(req) {
424
+ if (!configEnableHttpTopologyMode()) {
425
+ return void 0;
426
+ }
427
+ try {
428
+ const remoteCallKey = generateTxid2();
429
+ const currentDomainId = domainId();
430
+ const currentAgentId = agentId();
431
+ if (!currentDomainId || !currentAgentId) {
432
+ return void 0;
433
+ }
434
+ const topologyHeaderKey = configTopologyHttpHeaderKey();
435
+ if (!req.getHeader(topologyHeaderKey)) {
436
+ req.setHeader(topologyHeaderKey, String(remoteCallKey));
437
+ req.setHeader(X_DOMAIN_ID, String(currentDomainId));
438
+ req.setHeader(X_AGENT_ID, String(currentAgentId));
439
+ }
440
+ return {
441
+ remoteCallKey,
442
+ domainId: currentDomainId,
443
+ oid: currentAgentId
444
+ };
445
+ } catch (error) {
446
+ warn2(`Failed to set topology request headers: ${error}`);
447
+ return void 0;
448
+ }
449
+ }
450
+ function setTopologyFetchHeaders(headers) {
451
+ if (!configEnableHttpTopologyMode()) {
452
+ return void 0;
453
+ }
454
+ try {
455
+ const remoteCallKey = generateTxid2();
456
+ const currentDomainId = domainId();
457
+ const currentAgentId = agentId();
458
+ if (!currentDomainId || !currentAgentId) {
459
+ return void 0;
460
+ }
461
+ const topologyHeaderKey = configTopologyHttpHeaderKey();
462
+ if (!headers.get(topologyHeaderKey)) {
463
+ headers.set(topologyHeaderKey, String(remoteCallKey));
464
+ headers.set(X_DOMAIN_ID, String(currentDomainId));
465
+ headers.set(X_AGENT_ID, String(currentAgentId));
466
+ }
467
+ return {
468
+ remoteCallKey,
469
+ domainId: currentDomainId,
470
+ oid: currentAgentId
471
+ };
472
+ } catch (error) {
473
+ warn2(`Failed to set topology fetch headers: ${error}`);
474
+ return void 0;
475
+ }
476
+ }
477
+ function getTopologyInfoFromFetch(response) {
478
+ if (!configEnableHttpTopologyMode()) {
479
+ return void 0;
480
+ }
481
+ try {
482
+ const topologyHeaderKey = configTopologyHttpHeaderKey();
483
+ const remoteCallKey = parseNumber(response.headers.get(topologyHeaderKey) || void 0);
484
+ const targetDomainId = parseNumber(response.headers.get(X_DOMAIN_ID) || void 0);
485
+ const targetAgentId = parseNumber(response.headers.get(X_AGENT_ID) || void 0);
486
+ if ([remoteCallKey, targetDomainId, targetAgentId].some((v) => v === void 0)) {
487
+ return void 0;
488
+ }
489
+ if (!isAgentId(targetAgentId)) {
490
+ return void 0;
491
+ }
492
+ return {
493
+ remoteCallKey,
494
+ domainId: targetDomainId,
495
+ oid: targetAgentId
496
+ };
497
+ } catch {
498
+ return void 0;
499
+ }
500
+ }
501
+ function getHeader(req, name) {
502
+ const value = req.headers?.[name.toLowerCase()];
503
+ if (!value) {
504
+ return void 0;
505
+ }
506
+ return Array.isArray(value) ? value[0] : value;
507
+ }
508
+ function parseNumber(value) {
509
+ if (!value) {
510
+ return void 0;
511
+ }
512
+ const parsed = Number(value);
513
+ return Number.isNaN(parsed) ? void 0 : parsed;
514
+ }
515
+
516
+ // src/instrumentations/http-server.ts
517
+ var JENNIFER_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.http.wrapped");
518
+ function collectResponseHeaders(res) {
519
+ if (!res?.getHeaders) return void 0;
520
+ return Object.entries(res.getHeaders()).map(([key, value]) => {
521
+ const valueStr = Array.isArray(value) ? value.join(", ") : String(value);
522
+ return `${key}:${valueStr}`;
523
+ });
524
+ }
525
+ function patchHttpServer(httpModule, moduleName) {
526
+ try {
527
+ if (instrumentServerEmit(httpModule)) {
528
+ info(`${moduleName} server instrumentation registered`);
529
+ }
530
+ } catch (error) {
531
+ warn3(`Failed to register ${moduleName} server instrumentation: ${error}`);
532
+ }
533
+ }
534
+ function instrumentServerEmit(httpModule) {
535
+ const ServerPrototype = httpModule.Server.prototype;
536
+ if (ServerPrototype.emit?.[JENNIFER_WRAPPED]) {
537
+ return false;
538
+ }
539
+ wrap(ServerPrototype, "emit", (originalEmit) => {
540
+ const wrapper = function(eventName, ...args) {
541
+ if (eventName === "request") {
542
+ return handleRequestEvent(this, originalEmit, eventName, args);
543
+ }
544
+ if (eventName === "upgrade") {
545
+ return handleUpgradeEvent(this, originalEmit, eventName, args);
546
+ }
547
+ return originalEmit.apply(this, [eventName, ...args]);
548
+ };
549
+ wrapper[JENNIFER_WRAPPED] = true;
550
+ return wrapper;
551
+ });
552
+ return true;
553
+ }
554
+ function createHttpHeaders(req) {
555
+ return req?.headers ? Object.entries(req.headers).map(([key, value]) => `${key}:${value}`) : void 0;
556
+ }
557
+ function handleRequestEvent(server, originalEmit, eventName, args) {
558
+ const [req, res] = args;
559
+ const ctx = contextManager.start();
560
+ if (ctx.enable) {
561
+ const wmonidInCookie = !configUsingRemoteAddressForWmonid2() ? getWmonidInCookie(req, res, ctx.id) : void 0;
562
+ const incomingRemotecallInfo = getTopologyInfo(req);
563
+ setTopologyResponseHeaders(incomingRemotecallInfo, res);
564
+ createTransactionCtx({
565
+ txId: ctx.id,
566
+ httpMethod: req?.method,
567
+ httpHeaders: createHttpHeaders(req),
568
+ httpUrl: req?.url,
569
+ clientIp: req?.socket?.remoteAddress,
570
+ wmonidInCookie,
571
+ incomingRemotecallInfo
572
+ });
573
+ return contextManager.run(ctx, () => {
574
+ let transactionEnded = false;
575
+ res.once("close", () => {
576
+ if (!transactionEnded) {
577
+ transactionEnded = true;
578
+ releaseTransactionCtx(ctx.id, {
579
+ httpStatusCode: res?.statusCode,
580
+ httpHeaders: collectResponseHeaders(res),
581
+ connectionAborted: true
582
+ });
583
+ }
584
+ });
585
+ wrap(res, "end", (originalEnd) => {
586
+ return function(...endArgs) {
587
+ if (!transactionEnded) {
588
+ transactionEnded = true;
589
+ releaseTransactionCtx(ctx.id, {
590
+ httpStatusCode: res?.statusCode,
591
+ httpHeaders: collectResponseHeaders(res)
592
+ });
593
+ }
594
+ return originalEnd.apply(this, endArgs);
595
+ };
596
+ });
597
+ return originalEmit.call(server, eventName, req, res);
598
+ });
599
+ } else {
600
+ return originalEmit.call(server, eventName, req, res);
601
+ }
602
+ }
603
+ function handleUpgradeEvent(server, originalEmit, eventName, args) {
604
+ const [req] = args;
605
+ const ctx = contextManager.start();
606
+ if (ctx.enable) {
607
+ createTransactionCtx({
608
+ txId: ctx.id,
609
+ method: "http.upgrade",
610
+ httpMethod: req?.method,
611
+ httpHeaders: createHttpHeaders(req),
612
+ httpUrl: req?.url,
613
+ clientIp: req?.socket?.remoteAddress
614
+ });
615
+ } else {
616
+ return originalEmit.apply(server, [eventName, ...args]);
617
+ }
618
+ return contextManager.run(ctx, () => {
619
+ try {
620
+ return originalEmit.apply(server, [eventName, ...args]);
621
+ } finally {
622
+ releaseTransactionCtx(ctx.id, {});
623
+ }
624
+ });
625
+ }
626
+
627
+ // src/instrumentations/apollo.ts
628
+ import {
629
+ changeTransactionServiceName,
630
+ configServiceNamingByGraphqlOperation,
631
+ info as info2,
632
+ sendError,
633
+ warn as warn4
634
+ } from "@jennifersoft/jennifer5-agent";
635
+ var JENNIFER_APOLLO_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.apollo.execute_http_graphql_request.wrapped");
636
+ function extractGraphQLErrorsMessage(response) {
637
+ const body = response?.body;
638
+ if (!body || typeof body !== "object") {
639
+ return null;
640
+ }
641
+ let errors = [];
642
+ if (Array.isArray(body.errors)) {
643
+ errors = body.errors;
644
+ } else if (body.singleResult && Array.isArray(body.singleResult.errors)) {
645
+ errors = body.singleResult.errors;
646
+ } else if (typeof body.string === "string") {
647
+ try {
648
+ const parsed = JSON.parse(body.string);
649
+ if (Array.isArray(parsed?.errors)) {
650
+ errors = parsed.errors;
651
+ }
652
+ } catch {
653
+ }
654
+ }
655
+ if (!errors.length) {
656
+ return null;
657
+ }
658
+ const messages = errors.map((error) => typeof error?.message === "string" ? error.message : "Unknown GraphQL error").filter((message) => message.length > 0);
659
+ if (!messages.length) {
660
+ return "GraphQL: Unknown GraphQL error";
661
+ }
662
+ return messages.map((message) => `GraphQL: ${message}`).join(" | ");
663
+ }
664
+ function detectOperationType(query) {
665
+ const normalized = query?.trim().toLowerCase();
666
+ if (!normalized) {
667
+ return "unknown";
668
+ }
669
+ if (normalized.startsWith("mutation")) {
670
+ return "mutation";
671
+ }
672
+ if (normalized.startsWith("query") || normalized.startsWith("{")) {
673
+ return "query";
674
+ }
675
+ return "unknown";
676
+ }
677
+ function buildServiceName(requestContext) {
678
+ const body = requestContext?.httpGraphQLRequest?.body;
679
+ if (!body || typeof body !== "object") {
680
+ return null;
681
+ }
682
+ if (body.kind && body.kind !== "single") {
683
+ return "GraphQL - unknown anonymous";
684
+ }
685
+ const operationType = detectOperationType(body.query);
686
+ const operationName = body.operationName?.trim() || "anonymous";
687
+ return `GraphQL - ${operationType} ${operationName}`;
688
+ }
689
+ function patchApolloServerModule(apolloModule, moduleName) {
690
+ try {
691
+ const ApolloServer = apolloModule?.ApolloServer;
692
+ const proto = ApolloServer?.prototype;
693
+ if (!proto || typeof proto.executeHTTPGraphQLRequest !== "function") {
694
+ return;
695
+ }
696
+ if (proto.executeHTTPGraphQLRequest[JENNIFER_APOLLO_WRAPPED]) {
697
+ return;
698
+ }
699
+ wrap(proto, "executeHTTPGraphQLRequest", (original) => {
700
+ const wrapper = async function(...args) {
701
+ const ctx = contextManager.getCurrentContext();
702
+ if (ctx?.enable && configServiceNamingByGraphqlOperation()) {
703
+ const serviceName = buildServiceName(args[0]);
704
+ if (serviceName) {
705
+ changeTransactionServiceName(ctx.id, serviceName);
706
+ }
707
+ }
708
+ const response = await original.apply(this, args);
709
+ if (ctx?.enable) {
710
+ const errorsMessage = extractGraphQLErrorsMessage(response);
711
+ if (errorsMessage) {
712
+ sendError(ctx.id, errorsMessage);
713
+ }
714
+ }
715
+ return response;
716
+ };
717
+ wrapper[JENNIFER_APOLLO_WRAPPED] = true;
718
+ return wrapper;
719
+ });
720
+ info2(`${moduleName}.ApolloServer instrumentation registered`);
721
+ } catch (error) {
722
+ warn4(`Failed to register ${moduleName} Apollo instrumentation: ${error}`);
723
+ }
724
+ }
725
+
726
+ // src/instrumentations/http-client.ts
727
+ import { format as urlFormat } from "url";
728
+ import {
729
+ info as info3,
730
+ warn as warn5,
731
+ configEnableHttpClientProfile,
732
+ createHttpProfileCtx,
733
+ releaseHttpProfileCtx
734
+ } from "@jennifersoft/jennifer5-agent";
735
+ var JENNIFER_WRAPPED2 = /* @__PURE__ */ Symbol.for("jennifer.http.wrapped");
736
+ function patchHttpClient(httpModule, moduleName) {
737
+ try {
738
+ if (instrumentClientRequest(httpModule)) {
739
+ info3(`${moduleName} client instrumentation registered`);
740
+ }
741
+ } catch (error) {
742
+ warn5(`Failed to register ${moduleName} client instrumentation: ${error}`);
743
+ }
744
+ }
745
+ function instrumentClientRequest(httpModule) {
746
+ if (httpModule.request?.[JENNIFER_WRAPPED2]) {
747
+ return false;
748
+ }
749
+ wrap(httpModule, "request", (originalRequest) => {
750
+ const wrapper = function(...args) {
751
+ const req = originalRequest.apply(this, args);
752
+ const ctx = contextManager.getCurrentContext();
753
+ if (!ctx || !ctx.enable || !configEnableHttpClientProfile()) {
754
+ return req;
755
+ }
756
+ const { uri, options } = normalizeArgs(httpModule, args[0], args[1]);
757
+ const method = options.method || req.method || "GET";
758
+ setTopologyRequestHeaders(req);
759
+ const headers = {};
760
+ const rawHeaders = req.getHeaders();
761
+ for (const [key, value] of Object.entries(rawHeaders)) {
762
+ if (typeof value === "string") {
763
+ headers[key] = value;
764
+ } else if (Array.isArray(value)) {
765
+ headers[key] = value.join(", ");
766
+ } else if (value !== void 0) {
767
+ headers[key] = String(value);
768
+ }
769
+ }
770
+ const startCtx = createHttpProfileCtx(method, uri, headers, ctx.id);
771
+ let released = false;
772
+ const release = (endCtx) => {
773
+ if (!released) {
774
+ released = true;
775
+ releaseHttpProfileCtx(startCtx, endCtx);
776
+ }
777
+ };
778
+ const originalEmit = req.emit;
779
+ req.emit = function(eventName, ...emitArgs) {
780
+ switch (eventName) {
781
+ case "response": {
782
+ const res = emitArgs[0];
783
+ res.once("end", () => {
784
+ release({
785
+ statusCode: res.statusCode,
786
+ remoteCallInfo: getTopologyInfo(res)
787
+ });
788
+ });
789
+ break;
790
+ }
791
+ case "error":
792
+ case "timeout": {
793
+ const error = emitArgs[0];
794
+ release({
795
+ error: {
796
+ message: error?.message,
797
+ stack: error?.stack
798
+ }
799
+ });
800
+ break;
801
+ }
802
+ case "abort":
803
+ case "close":
804
+ break;
805
+ }
806
+ return originalEmit.apply(this, [eventName, ...emitArgs]);
807
+ };
808
+ return req;
809
+ };
810
+ wrapper[JENNIFER_WRAPPED2] = true;
811
+ return wrapper;
812
+ });
813
+ wrap(httpModule, "get", (originalGet) => {
814
+ return function(...args) {
815
+ const req = httpModule.request.apply(this, args);
816
+ req.end();
817
+ return req;
818
+ };
819
+ });
820
+ return true;
821
+ }
822
+ function normalizeOptions(httpModule, inputURL) {
823
+ if (typeof inputURL === "string") {
824
+ try {
825
+ return urlToOptions(httpModule, new URL(inputURL));
826
+ } catch {
827
+ return { path: inputURL };
828
+ }
829
+ }
830
+ if (inputURL instanceof URL) {
831
+ return urlToOptions(httpModule, inputURL);
832
+ }
833
+ if (inputURL) {
834
+ const result = { ...inputURL };
835
+ if (!result.protocol) {
836
+ result.protocol = httpModule.globalAgent?.protocol || "http:";
837
+ }
838
+ if (!result.pathname && result.path) {
839
+ const pathParts = result.path.split("?");
840
+ result.pathname = pathParts[0];
841
+ if (pathParts[1] && !result.search) {
842
+ result.search = `?${pathParts[1]}`;
843
+ }
844
+ }
845
+ return result;
846
+ }
847
+ return inputURL;
848
+ }
849
+ function urlToOptions(httpModule, urlObj) {
850
+ const agent = httpModule.globalAgent;
851
+ const options = {
852
+ protocol: urlObj.protocol || agent?.protocol,
853
+ hostname: urlObj.hostname.startsWith("[") ? urlObj.hostname.slice(1, -1) : urlObj.hostname || "localhost",
854
+ hash: urlObj.hash,
855
+ search: urlObj.search,
856
+ pathname: urlObj.pathname,
857
+ path: `${urlObj.pathname || ""}${urlObj.search || ""}`,
858
+ href: urlObj.href
859
+ };
860
+ if (urlObj.port !== "") {
861
+ options.port = Number(urlObj.port);
862
+ }
863
+ if (urlObj.username || urlObj.password) {
864
+ options.auth = `${urlObj.username}:${urlObj.password}`;
865
+ }
866
+ return options;
867
+ }
868
+ function combineOptions(inputURL, inputOptions) {
869
+ return inputOptions !== null && typeof inputOptions === "object" ? Object.assign(inputURL || {}, inputOptions) : inputURL;
870
+ }
871
+ function normalizeArgs(httpModule, inputURL, inputOptions) {
872
+ const normalizedURL = normalizeOptions(httpModule, inputURL);
873
+ const options = combineOptions(normalizedURL, inputOptions);
874
+ const uri = urlFormat(options);
875
+ return { uri, options };
876
+ }
877
+
878
+ // src/instrumentations/fs.ts
879
+ import {
880
+ info as info4,
881
+ FsActionType,
882
+ createFsProfileCtx,
883
+ releaseFsProfileCtx,
884
+ configEnableFileProfile
885
+ } from "@jennifersoft/jennifer5-agent";
886
+ var JENNIFER_WRAPPED3 = /* @__PURE__ */ Symbol.for("jennifer.fs.wrapped");
887
+ function patchFsSync(fs, _moduleName) {
888
+ const methods = [
889
+ ["readFileSync", FsActionType.SyncRead],
890
+ ["writeFileSync", FsActionType.SyncWrite]
891
+ ];
892
+ let patchedCount = 0;
893
+ for (const [method, event] of methods) {
894
+ if (fs[method]?.[JENNIFER_WRAPPED3]) {
895
+ continue;
896
+ }
897
+ wrap(fs, method, (original) => {
898
+ const wrapper = function(...args) {
899
+ const ctx = contextManager.getCurrentContext();
900
+ if (!ctx || !ctx.enable || !configEnableFileProfile()) {
901
+ return original.apply(this, args);
902
+ }
903
+ const filePathArg = args[0];
904
+ const filePath = filePathArg ? String(filePathArg) : "undefined";
905
+ const profileCtx = createFsProfileCtx(event, filePath, ctx.id);
906
+ try {
907
+ const result = original.apply(this, args);
908
+ releaseFsProfileCtx(profileCtx, {
909
+ fileSize: result?.length
910
+ });
911
+ return result;
912
+ } catch (error) {
913
+ releaseFsProfileCtx(profileCtx, {
914
+ error: {
915
+ message: error.toString()
916
+ }
917
+ });
918
+ throw error;
919
+ }
920
+ };
921
+ wrapper[JENNIFER_WRAPPED3] = true;
922
+ return wrapper;
923
+ });
924
+ patchedCount++;
925
+ }
926
+ if (patchedCount > 0) {
927
+ info4(`fs sync: ${patchedCount} methods instrumented`);
928
+ }
929
+ return patchedCount > 0;
930
+ }
931
+ function patchFsAsync(fs, _moduleName) {
932
+ const asyncMethods = [
933
+ ["readFile", FsActionType.AsyncRead],
934
+ ["writeFile", FsActionType.AsyncWrite]
935
+ ];
936
+ let patchedCount = 0;
937
+ for (const [method, event] of asyncMethods) {
938
+ if (fs[method]?.[JENNIFER_WRAPPED3]) {
939
+ continue;
940
+ }
941
+ wrap(fs, method, (original) => {
942
+ const wrapper = function(...args) {
943
+ const callbackIndex = args.findIndex((arg) => typeof arg === "function");
944
+ if (callbackIndex === -1) {
945
+ return original.apply(this, args);
946
+ }
947
+ const ctx = contextManager.getCurrentContext();
948
+ if (!ctx || !ctx.enable || !configEnableFileProfile()) {
949
+ return original.apply(this, args);
950
+ }
951
+ const filePathArg = args[0];
952
+ const filePath = filePathArg ? String(filePathArg) : "undefined";
953
+ const perfCtx = createFsProfileCtx(event, filePath, ctx.id);
954
+ const originalCallback = args[callbackIndex];
955
+ args[callbackIndex] = function(err, data) {
956
+ releaseFsProfileCtx(perfCtx, {
957
+ error: err ? { message: err.message, stack: err.stack } : void 0,
958
+ fileSize: data?.length
959
+ });
960
+ return contextManager.run(ctx, () => originalCallback.call(this, err, data));
961
+ };
962
+ return original.apply(this, args);
963
+ };
964
+ wrapper[JENNIFER_WRAPPED3] = true;
965
+ return wrapper;
966
+ });
967
+ patchedCount++;
968
+ }
969
+ if (patchedCount > 0) {
970
+ info4(`fs async: ${patchedCount} methods instrumented`);
971
+ }
972
+ return patchedCount > 0;
973
+ }
974
+ function patchFsPromise(fs, _moduleName) {
975
+ const fsPromises = fs.promises;
976
+ if (!fsPromises) {
977
+ return false;
978
+ }
979
+ const promiseMethods = [
980
+ ["readFile", FsActionType.PromiseRead],
981
+ ["writeFile", FsActionType.PromiseWrite]
982
+ ];
983
+ let patchedCount = 0;
984
+ for (const [method, event] of promiseMethods) {
985
+ if (fsPromises[method]?.[JENNIFER_WRAPPED3]) {
986
+ continue;
987
+ }
988
+ wrap(fsPromises, method, (original) => {
989
+ const wrapper = function(...args) {
990
+ const ctx = contextManager.getCurrentContext();
991
+ if (!ctx || !ctx.enable || !configEnableFileProfile()) {
992
+ return original.apply(this, args);
993
+ }
994
+ const filePathArg = args[0];
995
+ const filePath = filePathArg ? String(filePathArg) : "undefined";
996
+ const perfCtx = createFsProfileCtx(event, filePath, ctx.id);
997
+ try {
998
+ const result = original.apply(this, args);
999
+ if (result && typeof result.then === "function") {
1000
+ return result.then(
1001
+ (res) => {
1002
+ releaseFsProfileCtx(perfCtx, {
1003
+ fileSize: res?.length
1004
+ });
1005
+ return res;
1006
+ },
1007
+ (err) => {
1008
+ releaseFsProfileCtx(perfCtx, {
1009
+ error: {
1010
+ message: err.message,
1011
+ stack: err.stack
1012
+ }
1013
+ });
1014
+ throw err;
1015
+ }
1016
+ );
1017
+ } else {
1018
+ releaseFsProfileCtx(perfCtx, {});
1019
+ return result;
1020
+ }
1021
+ } catch (error) {
1022
+ releaseFsProfileCtx(perfCtx, {
1023
+ error: { message: error.message, stack: error.stack }
1024
+ });
1025
+ throw error;
1026
+ }
1027
+ };
1028
+ wrapper[JENNIFER_WRAPPED3] = true;
1029
+ return wrapper;
1030
+ });
1031
+ patchedCount++;
1032
+ }
1033
+ if (patchedCount > 0) {
1034
+ info4(`fs.promises: ${patchedCount} methods instrumented`);
1035
+ }
1036
+ return patchedCount > 0;
1037
+ }
1038
+
1039
+ // src/instrumentations/fetch.ts
1040
+ import {
1041
+ info as info5,
1042
+ warn as warn6,
1043
+ createHttpProfileCtx as createHttpProfileCtx2,
1044
+ releaseHttpProfileCtx as releaseHttpProfileCtx2,
1045
+ configEnableHttpClientProfile as configEnableHttpClientProfile2
1046
+ } from "@jennifersoft/jennifer5-agent";
1047
+ var JENNIFER_WRAPPED4 = /* @__PURE__ */ Symbol.for("jennifer.fetch.wrapped");
1048
+ function handleRequestObject(originalFetch, request, init, txId) {
1049
+ const normalizedRequest = init ? new Request(request, init) : request;
1050
+ const url = normalizedRequest.url;
1051
+ const method = normalizedRequest.method;
1052
+ const fetchHeaders = new Headers(normalizedRequest.headers);
1053
+ setTopologyFetchHeaders(fetchHeaders);
1054
+ const headers = {};
1055
+ fetchHeaders.forEach((value, key) => {
1056
+ headers[key] = value;
1057
+ });
1058
+ const wrappedRequest = new Request(normalizedRequest, { headers: fetchHeaders });
1059
+ const startCtx = createHttpProfileCtx2(method, url, headers, txId);
1060
+ const result = originalFetch(wrappedRequest);
1061
+ return { result, startCtx };
1062
+ }
1063
+ function handleUrlString(originalFetch, input, init, txId) {
1064
+ const url = typeof input === "string" ? input : input.href;
1065
+ const method = init?.method || "GET";
1066
+ const fetchHeaders = new Headers(init?.headers);
1067
+ setTopologyFetchHeaders(fetchHeaders);
1068
+ const headers = {};
1069
+ fetchHeaders.forEach((value, key) => {
1070
+ headers[key] = value;
1071
+ });
1072
+ const modifiedInit = {
1073
+ ...init,
1074
+ headers: fetchHeaders
1075
+ };
1076
+ const startCtx = createHttpProfileCtx2(method, url, headers, txId);
1077
+ const result = originalFetch(input, modifiedInit);
1078
+ return { result, startCtx };
1079
+ }
1080
+ function createFetchWrapper(originalFetch) {
1081
+ return function(...args) {
1082
+ const ctx = contextManager.getCurrentContext();
1083
+ if (!ctx || !ctx.enable || !configEnableHttpClientProfile2()) {
1084
+ return originalFetch(...args);
1085
+ }
1086
+ const [input, init] = args;
1087
+ const { result, startCtx } = input instanceof Request ? handleRequestObject(originalFetch, input, init, ctx.id) : handleUrlString(originalFetch, input, init, ctx.id);
1088
+ return result.then(
1089
+ (response) => {
1090
+ const contentLength = response.headers.get("content-length");
1091
+ const responseSize = contentLength ? parseInt(contentLength, 10) : void 0;
1092
+ const remoteCallInfo = getTopologyInfoFromFetch(response);
1093
+ releaseHttpProfileCtx2(startCtx, {
1094
+ statusCode: response.status,
1095
+ responseSize,
1096
+ remoteCallInfo
1097
+ });
1098
+ return response;
1099
+ },
1100
+ (error) => {
1101
+ releaseHttpProfileCtx2(startCtx, {
1102
+ error: {
1103
+ message: error.message,
1104
+ stack: error.stack
1105
+ }
1106
+ });
1107
+ throw error;
1108
+ }
1109
+ );
1110
+ };
1111
+ }
1112
+ function patchGlobalFetch() {
1113
+ try {
1114
+ if (typeof global.fetch !== "function") {
1115
+ return;
1116
+ }
1117
+ if (global.fetch[JENNIFER_WRAPPED4]) {
1118
+ return;
1119
+ }
1120
+ wrap(global, "fetch", (originalFetch) => {
1121
+ const wrapper = createFetchWrapper(originalFetch);
1122
+ wrapper[JENNIFER_WRAPPED4] = true;
1123
+ return wrapper;
1124
+ });
1125
+ info5("global.fetch instrumentation registered");
1126
+ } catch (error) {
1127
+ warn6("Failed to register global.fetch instrumentation:" + error);
1128
+ }
1129
+ }
1130
+
1131
+ // src/instrumentations/n8n-workflow.ts
1132
+ import {
1133
+ info as info6,
1134
+ warn as warn7,
1135
+ createTransactionCtx as createTransactionCtx2,
1136
+ releaseTransactionCtx as releaseTransactionCtx2
1137
+ } from "@jennifersoft/jennifer5-agent";
1138
+ var JENNIFER_WRAPPED5 = /* @__PURE__ */ Symbol.for("jennifer.n8n.workflow.wrapped");
1139
+ var executionTxMap = /* @__PURE__ */ new Map();
1140
+ function registerWorkflowExecutionTx(executionId, txId) {
1141
+ executionTxMap.set(executionId, txId);
1142
+ }
1143
+ function takeWorkflowExecutionTx(executionId) {
1144
+ const txId = executionTxMap.get(executionId);
1145
+ if (txId !== void 0) {
1146
+ executionTxMap.delete(executionId);
1147
+ }
1148
+ return txId;
1149
+ }
1150
+ function patchN8nWorkflowRunner(workflowRunnerModule, moduleName) {
1151
+ try {
1152
+ if (!workflowRunnerModule?.WorkflowRunner) {
1153
+ return;
1154
+ }
1155
+ instrumentWorkflowRunner(workflowRunnerModule.WorkflowRunner);
1156
+ info6(`${moduleName} WorkflowRunner instrumentation registered`);
1157
+ } catch (error) {
1158
+ warn7(`Failed to register ${moduleName} WorkflowRunner instrumentation: ${error}`);
1159
+ }
1160
+ }
1161
+ function instrumentWorkflowRunner(WorkflowRunnerClass) {
1162
+ const prototype = WorkflowRunnerClass.prototype;
1163
+ if (prototype?.run?.[JENNIFER_WRAPPED5]) {
1164
+ return;
1165
+ }
1166
+ wrap(prototype, "run", (originalRun) => {
1167
+ const wrapper = function(...args) {
1168
+ const [data] = args;
1169
+ const workflowData = data?.workflowData;
1170
+ const workflowId = workflowData?.id;
1171
+ const workflowName = workflowData?.name;
1172
+ const executionMode = data?.executionMode;
1173
+ const userId = data?.userId;
1174
+ const ctx = contextManager.start();
1175
+ if (ctx.enable) {
1176
+ const serviceName = workflowName || workflowId || "unknown-workflow";
1177
+ createTransactionCtx2({
1178
+ txId: ctx.id,
1179
+ method: "n8n.workflow.run",
1180
+ httpMethod: "EXECUTE",
1181
+ httpUrl: `${serviceName}`,
1182
+ httpHeaders: [
1183
+ `execution-mode:${executionMode || "unknown"}`,
1184
+ `workflow-id:${workflowId || "unknown"}`,
1185
+ ...userId ? [`user-id:${userId}`] : []
1186
+ ]
1187
+ });
1188
+ }
1189
+ const result = contextManager.run(ctx, () => {
1190
+ return originalRun.apply(this, args);
1191
+ });
1192
+ if (result && typeof result.then === "function") {
1193
+ return result.then(
1194
+ (executionId) => {
1195
+ if (ctx.enable && typeof executionId === "string") {
1196
+ registerWorkflowExecutionTx(executionId, ctx.id);
1197
+ }
1198
+ return executionId;
1199
+ },
1200
+ (error) => {
1201
+ if (ctx.enable) {
1202
+ releaseTransactionCtx2(ctx.id, {
1203
+ httpStatusCode: 500
1204
+ // Error
1205
+ });
1206
+ }
1207
+ throw error;
1208
+ }
1209
+ );
1210
+ }
1211
+ if (ctx.enable) {
1212
+ releaseTransactionCtx2(ctx.id, {
1213
+ httpStatusCode: 200
1214
+ // Success
1215
+ });
1216
+ }
1217
+ return result;
1218
+ };
1219
+ wrapper[JENNIFER_WRAPPED5] = true;
1220
+ return wrapper;
1221
+ });
1222
+ }
1223
+
1224
+ // src/instrumentations/n8n-active-executions.ts
1225
+ import { warn as warn8, releaseTransactionCtx as releaseTransactionCtx3 } from "@jennifersoft/jennifer5-agent";
1226
+ var JENNIFER_WRAPPED6 = /* @__PURE__ */ Symbol.for("jennifer.n8n.active-executions.wrapped");
1227
+ function patchN8nActiveExecutions(activeExecutionsModule, moduleName) {
1228
+ try {
1229
+ if (!activeExecutionsModule?.ActiveExecutions) {
1230
+ return;
1231
+ }
1232
+ instrumentActiveExecutions(activeExecutionsModule.ActiveExecutions);
1233
+ } catch (error) {
1234
+ warn8(`Failed to register ${moduleName} ActiveExecutions instrumentation: ${error}`);
1235
+ }
1236
+ }
1237
+ function instrumentActiveExecutions(ActiveExecutionsClass) {
1238
+ const prototype = ActiveExecutionsClass.prototype;
1239
+ if (prototype?.finalizeExecution?.[JENNIFER_WRAPPED6]) {
1240
+ return;
1241
+ }
1242
+ wrap(prototype, "finalizeExecution", (originalFinalize) => {
1243
+ const wrapper = function(executionId, fullRunData) {
1244
+ const txId = typeof executionId === "string" ? takeWorkflowExecutionTx(executionId) : void 0;
1245
+ try {
1246
+ return originalFinalize.apply(this, arguments);
1247
+ } finally {
1248
+ if (txId !== void 0) {
1249
+ const isError = fullRunData?.status === "error";
1250
+ releaseTransactionCtx3(txId, { httpStatusCode: isError ? 500 : 200 });
1251
+ }
1252
+ }
1253
+ };
1254
+ wrapper[JENNIFER_WRAPPED6] = true;
1255
+ return wrapper;
1256
+ });
1257
+ }
1258
+
1259
+ // src/instrumentations/mariadb.ts
1260
+ import {
1261
+ configEnableMariadbProfile,
1262
+ createDbConnectionProfileCtx,
1263
+ createSqlProfileCtx,
1264
+ SqlExecuteMethod,
1265
+ info as info7,
1266
+ warn as warn9
1267
+ } from "@jennifersoft/jennifer5-agent";
1268
+
1269
+ // src/instrumentations/db-utils.ts
1270
+ import {
1271
+ releaseDbConnectionProfileCtx,
1272
+ releaseSqlProfileCtx,
1273
+ SqlParamType
1274
+ } from "@jennifersoft/jennifer5-agent";
1275
+ function normalizeOptionalParams(value) {
1276
+ if (value === void 0 || typeof value === "function") {
1277
+ return void 0;
1278
+ }
1279
+ return value;
1280
+ }
1281
+ function buildSqlEndCtx(startCtx, error) {
1282
+ return {
1283
+ error: error ? {
1284
+ message: error?.message,
1285
+ stack: error?.stack
1286
+ } : void 0,
1287
+ id: startCtx?.id ?? 0,
1288
+ txId: startCtx?.txId ?? 0
1289
+ };
1290
+ }
1291
+ function releaseSqlProfile(startCtx, error) {
1292
+ releaseSqlProfileCtx(startCtx, buildSqlEndCtx(startCtx, error));
1293
+ }
1294
+ function buildDbConnectionEndCtx(startCtx, error) {
1295
+ return {
1296
+ error: error ? {
1297
+ message: error?.message,
1298
+ stack: error?.stack
1299
+ } : void 0,
1300
+ id: startCtx?.id ?? 0,
1301
+ txId: startCtx?.txId ?? 0
1302
+ };
1303
+ }
1304
+ function releaseDbConnectionProfile(startCtx, error) {
1305
+ releaseDbConnectionProfileCtx(startCtx, buildDbConnectionEndCtx(startCtx, error));
1306
+ }
1307
+ function toSqlParams(params, options) {
1308
+ if (params === void 0 || params === null) {
1309
+ return void 0;
1310
+ }
1311
+ if (Array.isArray(params)) {
1312
+ return params.map((value) => buildSqlParam(value, options));
1313
+ }
1314
+ if (typeof params === "object") {
1315
+ return Object.keys(params).map((key) => buildSqlParam(params[key], options));
1316
+ }
1317
+ return [buildSqlParam(params, options)];
1318
+ }
1319
+ function buildSqlParam(value, options) {
1320
+ const normalized = normalizeSqlParamValue(value, options);
1321
+ return {
1322
+ value: normalized.value,
1323
+ paramType: normalized.paramType
1324
+ };
1325
+ }
1326
+ function normalizeSqlParamValue(input, options) {
1327
+ const value = options?.unwrapValue ? options.unwrapValue(input) : input;
1328
+ const bigintAsNumeric = options?.bigintAsNumeric ?? true;
1329
+ if (value === null || value === void 0) {
1330
+ return { value: "null", paramType: SqlParamType.String };
1331
+ }
1332
+ if (typeof value === "number" && Number.isFinite(value)) {
1333
+ return { value: String(value), paramType: SqlParamType.Numeric };
1334
+ }
1335
+ if (typeof value === "bigint") {
1336
+ return {
1337
+ value: value.toString(),
1338
+ paramType: bigintAsNumeric ? SqlParamType.Numeric : SqlParamType.String
1339
+ };
1340
+ }
1341
+ if (typeof value === "boolean") {
1342
+ return { value: String(value), paramType: SqlParamType.String };
1343
+ }
1344
+ if (typeof value === "string") {
1345
+ return { value, paramType: SqlParamType.String };
1346
+ }
1347
+ if (value instanceof Date) {
1348
+ return { value: value.toISOString(), paramType: SqlParamType.String };
1349
+ }
1350
+ if (Buffer.isBuffer(value)) {
1351
+ return { value: `[Buffer len=${value.length}]`, paramType: SqlParamType.String };
1352
+ }
1353
+ if (typeof value === "function") {
1354
+ return { value: "[Function]", paramType: SqlParamType.String };
1355
+ }
1356
+ if (isStreamLike(value)) {
1357
+ return { value: "[Stream]", paramType: SqlParamType.String };
1358
+ }
1359
+ if (typeof value === "object") {
1360
+ try {
1361
+ return {
1362
+ value: JSON.stringify(value, jsonReplacer),
1363
+ paramType: SqlParamType.String
1364
+ };
1365
+ } catch {
1366
+ return {
1367
+ value: Object.prototype.toString.call(value),
1368
+ paramType: SqlParamType.String
1369
+ };
1370
+ }
1371
+ }
1372
+ return { value: String(value), paramType: SqlParamType.String };
1373
+ }
1374
+ function jsonReplacer(_key, input) {
1375
+ if (typeof input === "bigint") {
1376
+ return input.toString();
1377
+ }
1378
+ if (Buffer.isBuffer(input)) {
1379
+ return `[Buffer len=${input.length}]`;
1380
+ }
1381
+ if (typeof input === "function") {
1382
+ return "[Function]";
1383
+ }
1384
+ if (isStreamLike(input)) {
1385
+ return "[Stream]";
1386
+ }
1387
+ if (typeof input === "symbol") {
1388
+ return input.toString();
1389
+ }
1390
+ return input;
1391
+ }
1392
+ function isStreamLike(value) {
1393
+ return Boolean(
1394
+ value && typeof value === "object" && typeof value.pipe === "function" && typeof value.read === "function"
1395
+ );
1396
+ }
1397
+
1398
+ // src/instrumentations/mariadb.ts
1399
+ var JENNIFER_MARIADB_CREATE_CONNECTION_WRAPPED = /* @__PURE__ */ Symbol.for(
1400
+ "jennifer.mariadb.create.connection.wrapped"
1401
+ );
1402
+ var JENNIFER_MARIADB_QUERY_START_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.mariadb.query.start.wrapped");
1403
+ var JENNIFER_MARIADB_EXECUTE_START_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.mariadb.execute.start.wrapped");
1404
+ function patchMariadbModule(mariadbModule, moduleName) {
1405
+ try {
1406
+ if (instrumentCreateConnection(mariadbModule)) {
1407
+ info7(`${moduleName}.createConnection instrumented`);
1408
+ }
1409
+ } catch (error) {
1410
+ warn9(`Failed to register ${moduleName} instrumentation: ${error}`);
1411
+ }
1412
+ }
1413
+ function patchMariadbQueryCommandModule(queryCommandModule, moduleName) {
1414
+ try {
1415
+ if (instrumentCommandStart(
1416
+ queryCommandModule?.prototype,
1417
+ "start",
1418
+ SqlExecuteMethod.ExecuteQuery,
1419
+ JENNIFER_MARIADB_QUERY_START_WRAPPED
1420
+ )) {
1421
+ info7(`${moduleName}.prototype.start instrumented`);
1422
+ }
1423
+ } catch (error) {
1424
+ warn9(`Failed to register ${moduleName} instrumentation: ${error}`);
1425
+ }
1426
+ }
1427
+ function patchMariadbExecuteCommandModule(executeCommandModule, moduleName) {
1428
+ try {
1429
+ if (instrumentCommandStart(
1430
+ executeCommandModule?.prototype,
1431
+ "start",
1432
+ SqlExecuteMethod.Execute,
1433
+ JENNIFER_MARIADB_EXECUTE_START_WRAPPED
1434
+ )) {
1435
+ info7(`${moduleName}.prototype.start instrumented`);
1436
+ }
1437
+ } catch (error) {
1438
+ warn9(`Failed to register ${moduleName} instrumentation: ${error}`);
1439
+ }
1440
+ }
1441
+ function instrumentCommandStart(prototype, methodName, executeMethod, wrapMarker) {
1442
+ if (!prototype || typeof prototype[methodName] !== "function" || prototype[methodName]?.[wrapMarker]) {
1443
+ return false;
1444
+ }
1445
+ wrap(prototype, methodName, (originalMethod) => {
1446
+ const wrapper = function(...args) {
1447
+ const ctx = contextManager.getCurrentContext();
1448
+ if (!ctx || !ctx.enable || !configEnableMariadbProfile()) {
1449
+ return originalMethod.apply(this, args);
1450
+ }
1451
+ const sqlData = extractSqlAndParams(this);
1452
+ if (!sqlData?.sql) {
1453
+ return originalMethod.apply(this, args);
1454
+ }
1455
+ const startCtx = createSqlProfileCtx(
1456
+ sqlData.sql,
1457
+ executeMethod,
1458
+ extractBoundParameters(sqlData.params),
1459
+ ctx?.id
1460
+ );
1461
+ if (!startCtx) {
1462
+ return originalMethod.apply(this, args);
1463
+ }
1464
+ let isReleased = false;
1465
+ const releaseSuccess2 = () => {
1466
+ if (isReleased) {
1467
+ return;
1468
+ }
1469
+ isReleased = true;
1470
+ releaseSqlProfile(startCtx);
1471
+ };
1472
+ const releaseError = (error) => {
1473
+ if (isReleased) {
1474
+ return;
1475
+ }
1476
+ isReleased = true;
1477
+ releaseSqlProfile(startCtx, error);
1478
+ };
1479
+ const originalResolve = this?.resolve;
1480
+ if (typeof originalResolve === "function") {
1481
+ this.resolve = function(...resolveArgs) {
1482
+ releaseSuccess2();
1483
+ return originalResolve.apply(this, resolveArgs);
1484
+ };
1485
+ }
1486
+ const originalReject = this?.reject;
1487
+ if (typeof originalReject === "function") {
1488
+ this.reject = function(error, ...rejectArgs) {
1489
+ releaseError(error);
1490
+ return originalReject.call(this, error, ...rejectArgs);
1491
+ };
1492
+ }
1493
+ try {
1494
+ return originalMethod.apply(this, args);
1495
+ } catch (error) {
1496
+ releaseError(error);
1497
+ throw error;
1498
+ }
1499
+ };
1500
+ wrapper[wrapMarker] = true;
1501
+ return wrapper;
1502
+ });
1503
+ return true;
1504
+ }
1505
+ function instrumentCreateConnection(mariadbModule) {
1506
+ if (!mariadbModule || typeof mariadbModule.createConnection !== "function" || mariadbModule.createConnection?.[JENNIFER_MARIADB_CREATE_CONNECTION_WRAPPED]) {
1507
+ return false;
1508
+ }
1509
+ wrap(mariadbModule, "createConnection", (originalCreateConnection) => {
1510
+ const wrapper = function(...args) {
1511
+ const ctx = contextManager.getCurrentContext();
1512
+ if (!ctx || !ctx.enable || !configEnableMariadbProfile()) {
1513
+ return originalCreateConnection.apply(this, args);
1514
+ }
1515
+ const connectionInfo = extractConnectionInfo(args[0]);
1516
+ const startCtx = createDbConnectionProfileCtx(connectionInfo, void 0, ctx.id);
1517
+ try {
1518
+ const result = originalCreateConnection.apply(this, args);
1519
+ if (result && typeof result.then === "function") {
1520
+ return result.then(
1521
+ (connection) => {
1522
+ releaseDbConnectionProfile(startCtx);
1523
+ return connection;
1524
+ },
1525
+ (error) => {
1526
+ releaseDbConnectionProfile(startCtx, error);
1527
+ throw error;
1528
+ }
1529
+ );
1530
+ }
1531
+ releaseDbConnectionProfile(startCtx);
1532
+ return result;
1533
+ } catch (error) {
1534
+ releaseDbConnectionProfile(startCtx, error);
1535
+ throw error;
1536
+ }
1537
+ };
1538
+ wrapper[JENNIFER_MARIADB_CREATE_CONNECTION_WRAPPED] = true;
1539
+ return wrapper;
1540
+ });
1541
+ return true;
1542
+ }
1543
+ function extractSqlAndParams(command) {
1544
+ const sql = command?.sql;
1545
+ if (typeof sql !== "string") {
1546
+ return void 0;
1547
+ }
1548
+ return {
1549
+ sql,
1550
+ params: command?.initialValues
1551
+ };
1552
+ }
1553
+ function extractBoundParameters(params) {
1554
+ return toSqlParams(params);
1555
+ }
1556
+ function extractConnectionInfo(config) {
1557
+ if (!config) {
1558
+ return void 0;
1559
+ }
1560
+ if (typeof config === "string") {
1561
+ return parseMariadbConnectionString(config);
1562
+ }
1563
+ if (typeof config !== "object") {
1564
+ return void 0;
1565
+ }
1566
+ return {
1567
+ host: config.host || "localhost",
1568
+ port: config.port || 3306,
1569
+ user: config.user || "",
1570
+ database: config.database || ""
1571
+ };
1572
+ }
1573
+ function parseMariadbConnectionString(connectionString) {
1574
+ try {
1575
+ const parsed = new URL(connectionString);
1576
+ return {
1577
+ host: parsed.hostname || "localhost",
1578
+ port: parsed.port ? Number(parsed.port) : 3306,
1579
+ user: parsed.username || "",
1580
+ database: parsed.pathname ? parsed.pathname.replace(/^\/+/, "") : ""
1581
+ };
1582
+ } catch {
1583
+ return {
1584
+ host: "localhost",
1585
+ port: 3306,
1586
+ user: "",
1587
+ database: ""
1588
+ };
1589
+ }
1590
+ }
1591
+
1592
+ // src/instrumentations/mysql2.ts
1593
+ import {
1594
+ configEnableMysql2Profile,
1595
+ createDbConnectionProfileCtx as createDbConnectionProfileCtx2,
1596
+ createSqlProfileCtx as createSqlProfileCtx2,
1597
+ SqlExecuteMethod as SqlExecuteMethod2,
1598
+ info as info8,
1599
+ warn as warn10
1600
+ } from "@jennifersoft/jennifer5-agent";
1601
+ var JENNIFER_WRAPPED7 = /* @__PURE__ */ Symbol.for("jennifer.mysql2.wrapped");
1602
+ var JENNIFER_QUERY_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.mysql2.query.wrapped");
1603
+ var JENNIFER_EXECUTE_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.mysql2.execute.wrapped");
1604
+ function patchMysql2PromiseModule(mysql2Module, moduleName) {
1605
+ patchMysql2CreateConnection(mysql2Module, moduleName, "promise");
1606
+ patchMysql2ConnectionPrototype(mysql2Module, moduleName);
1607
+ }
1608
+ function patchMysql2Module(mysql2Module, moduleName) {
1609
+ patchMysql2CreateConnection(mysql2Module, moduleName, "callback");
1610
+ patchMysql2ConnectionPrototype(mysql2Module, moduleName);
1611
+ }
1612
+ function patchMysql2CreateConnection(mysql2Module, moduleName, mode) {
1613
+ try {
1614
+ if (instrumentCreateConnection2(mysql2Module, mode)) {
1615
+ info8(`${moduleName} instrumentation registered`);
1616
+ }
1617
+ } catch (error) {
1618
+ warn10(`Failed to register ${moduleName} instrumentation: ${error}`);
1619
+ }
1620
+ }
1621
+ function patchMysql2ConnectionPrototype(mysql2Module, moduleName) {
1622
+ try {
1623
+ const instrumentedTargets = [];
1624
+ if (instrumentConnectionPrototype(mysql2Module?.Connection)) {
1625
+ instrumentedTargets.push("Connection.prototype");
1626
+ }
1627
+ if (instrumentConnectionPrototype(mysql2Module?.PoolConnection)) {
1628
+ instrumentedTargets.push("PoolConnection.prototype");
1629
+ }
1630
+ if (instrumentConnectionPrototype(mysql2Module?.Pool)) {
1631
+ instrumentedTargets.push("Pool.prototype");
1632
+ }
1633
+ if (instrumentedTargets.length > 0) {
1634
+ info8(`${moduleName}.${instrumentedTargets.join(", ")} instrumented`);
1635
+ }
1636
+ } catch (error) {
1637
+ warn10(`Failed to instrument ${moduleName} prototypes: ${error}`);
1638
+ }
1639
+ }
1640
+ function instrumentCreateConnection2(mysql2Module, mode) {
1641
+ if (typeof mysql2Module?.createConnection !== "function") {
1642
+ return false;
1643
+ }
1644
+ if (mysql2Module.createConnection?.[JENNIFER_WRAPPED7]) {
1645
+ return false;
1646
+ }
1647
+ wrap(mysql2Module, "createConnection", (originalCreateConnection) => {
1648
+ const wrapper = function(...args) {
1649
+ const ctx = contextManager.getCurrentContext();
1650
+ if (!ctx || !ctx.enable || !configEnableMysql2Profile()) {
1651
+ return originalCreateConnection.apply(this, args);
1652
+ }
1653
+ const connectionInfo = extractConnectionInfo2(args[0]);
1654
+ const startCtx = createDbConnectionProfileCtx2(connectionInfo, void 0, ctx?.id);
1655
+ try {
1656
+ const result = originalCreateConnection.apply(this, args);
1657
+ if (mode === "callback") {
1658
+ instrumentConnectionPrototype(result);
1659
+ releaseDbConnectionProfile(startCtx);
1660
+ return result;
1661
+ }
1662
+ if (result && typeof result.then === "function") {
1663
+ return result.then(
1664
+ (connection) => {
1665
+ instrumentConnectionPrototype(connection?.connection ?? connection);
1666
+ releaseDbConnectionProfile(startCtx);
1667
+ return connection;
1668
+ },
1669
+ (error) => {
1670
+ releaseDbConnectionProfile(startCtx, error);
1671
+ throw error;
1672
+ }
1673
+ );
1674
+ }
1675
+ releaseDbConnectionProfile(startCtx);
1676
+ return result;
1677
+ } catch (error) {
1678
+ releaseDbConnectionProfile(startCtx, error);
1679
+ throw error;
1680
+ }
1681
+ };
1682
+ wrapper[JENNIFER_WRAPPED7] = true;
1683
+ return wrapper;
1684
+ });
1685
+ return true;
1686
+ }
1687
+ function instrumentConnectionPrototype(target) {
1688
+ const prototype = resolveConnectionPrototype(target);
1689
+ if (!prototype) {
1690
+ return false;
1691
+ }
1692
+ const queryInstrumented = instrumentSqlMethod(
1693
+ prototype,
1694
+ "query",
1695
+ SqlExecuteMethod2.ExecuteQuery,
1696
+ JENNIFER_QUERY_WRAPPED
1697
+ );
1698
+ const executeInstrumented = instrumentSqlMethod(
1699
+ prototype,
1700
+ "execute",
1701
+ SqlExecuteMethod2.Execute,
1702
+ JENNIFER_EXECUTE_WRAPPED
1703
+ );
1704
+ return queryInstrumented || executeInstrumented;
1705
+ }
1706
+ function resolveConnectionPrototype(target) {
1707
+ if (!target) {
1708
+ return void 0;
1709
+ }
1710
+ if (target.prototype) {
1711
+ return target.prototype;
1712
+ }
1713
+ return target.constructor?.prototype;
1714
+ }
1715
+ function instrumentSqlMethod(prototype, methodName, executeMethod, wrapMarker) {
1716
+ if (typeof prototype?.[methodName] !== "function" || prototype[methodName]?.[wrapMarker]) {
1717
+ return false;
1718
+ }
1719
+ wrap(prototype, methodName, (originalMethod) => {
1720
+ const wrapper = function(...args) {
1721
+ const ctx = contextManager.getCurrentContext();
1722
+ if (!ctx || !ctx.enable || !configEnableMysql2Profile()) {
1723
+ return originalMethod.apply(this, args);
1724
+ }
1725
+ const sqlData = extractSqlAndParams2(args);
1726
+ if (!sqlData?.sql) {
1727
+ return originalMethod.apply(this, args);
1728
+ }
1729
+ const startCtx = createSqlProfileCtx2(
1730
+ sqlData.sql,
1731
+ executeMethod,
1732
+ extractBoundParameters2(sqlData.params),
1733
+ ctx?.id
1734
+ );
1735
+ if (!startCtx) {
1736
+ return originalMethod.apply(this, args);
1737
+ }
1738
+ let isReleased = false;
1739
+ const releaseSuccess2 = () => {
1740
+ if (isReleased) return;
1741
+ isReleased = true;
1742
+ releaseSqlProfile(startCtx);
1743
+ };
1744
+ const releaseError = (error) => {
1745
+ if (isReleased) return;
1746
+ isReleased = true;
1747
+ releaseSqlProfile(startCtx, error);
1748
+ };
1749
+ const lastArgIndex = args.length - 1;
1750
+ const hasCallback = lastArgIndex >= 0 && typeof args[lastArgIndex] === "function";
1751
+ if (hasCallback) {
1752
+ const originalCallback = args[lastArgIndex];
1753
+ args[lastArgIndex] = function(...callbackArgs) {
1754
+ releaseError(callbackArgs[0]);
1755
+ return contextManager.run(ctx, () => originalCallback.apply(this, callbackArgs));
1756
+ };
1757
+ }
1758
+ try {
1759
+ const result = originalMethod.apply(this, args);
1760
+ if (hasCallback) {
1761
+ return result;
1762
+ }
1763
+ if (result && typeof result.once === "function") {
1764
+ result.once("error", (error) => releaseError(error));
1765
+ result.once("end", () => releaseSuccess2());
1766
+ return result;
1767
+ }
1768
+ if (result && typeof result.then === "function") {
1769
+ return result.then(
1770
+ (value) => {
1771
+ releaseSuccess2();
1772
+ return value;
1773
+ },
1774
+ (error) => {
1775
+ releaseError(error);
1776
+ throw error;
1777
+ }
1778
+ );
1779
+ }
1780
+ releaseSuccess2();
1781
+ return result;
1782
+ } catch (error) {
1783
+ releaseError(error);
1784
+ throw error;
1785
+ }
1786
+ };
1787
+ wrapper[wrapMarker] = true;
1788
+ return wrapper;
1789
+ });
1790
+ return true;
1791
+ }
1792
+ function extractConnectionInfo2(config) {
1793
+ if (!config) {
1794
+ return void 0;
1795
+ }
1796
+ const normalizedConfig = typeof config === "object" ? config : {};
1797
+ return {
1798
+ host: normalizedConfig.host || "localhost",
1799
+ port: normalizedConfig.port || 3306,
1800
+ user: normalizedConfig.user || "",
1801
+ database: normalizedConfig.database || ""
1802
+ };
1803
+ }
1804
+ function extractSqlAndParams2(args) {
1805
+ if (!args.length) {
1806
+ return void 0;
1807
+ }
1808
+ const firstArg = args[0];
1809
+ const secondArg = args[1];
1810
+ if (typeof firstArg === "string") {
1811
+ return {
1812
+ sql: firstArg,
1813
+ params: normalizeOptionalParams(secondArg)
1814
+ };
1815
+ }
1816
+ if (firstArg && typeof firstArg === "object" && typeof firstArg.sql === "string") {
1817
+ const params = firstArg.values !== void 0 ? firstArg.values : normalizeOptionalParams(secondArg);
1818
+ return {
1819
+ sql: firstArg.sql,
1820
+ params
1821
+ };
1822
+ }
1823
+ return void 0;
1824
+ }
1825
+ function extractBoundParameters2(params) {
1826
+ return toSqlParams(params);
1827
+ }
1828
+
1829
+ // src/instrumentations/ioredis.ts
1830
+ import {
1831
+ configEnableRedisProfile,
1832
+ createDbConnectionProfileCtx as createDbConnectionProfileCtx3,
1833
+ createMethodProfileCtx,
1834
+ info as info9,
1835
+ releaseMethodProfileCtx,
1836
+ warn as warn11
1837
+ } from "@jennifersoft/jennifer5-agent";
1838
+
1839
+ // src/instrumentations/redis-utils.ts
1840
+ import { configRedisCommandBlocklist } from "@jennifersoft/jennifer5-agent";
1841
+ function normalizeRedisCommandName(name) {
1842
+ if (typeof name === "string" && name) {
1843
+ return name.toUpperCase();
1844
+ }
1845
+ if (Buffer.isBuffer(name) && name.length > 0) {
1846
+ return name.toString("utf8").toUpperCase();
1847
+ }
1848
+ return void 0;
1849
+ }
1850
+ function isRedisCommandBlocked(commandName) {
1851
+ const blockedCommands = configRedisCommandBlocklist();
1852
+ if (!Array.isArray(blockedCommands) || blockedCommands.length === 0) {
1853
+ return false;
1854
+ }
1855
+ return blockedCommands.some((blockedCommand) => {
1856
+ if (typeof blockedCommand !== "string" || !blockedCommand) {
1857
+ return false;
1858
+ }
1859
+ return blockedCommand.toUpperCase() === commandName;
1860
+ });
1861
+ }
1862
+ function extractRedisMethodArguments(commandArgs, keyIndex) {
1863
+ if (!Array.isArray(commandArgs) || commandArgs.length <= keyIndex) {
1864
+ return [];
1865
+ }
1866
+ const key = stringifyRedisArgument(commandArgs[keyIndex]);
1867
+ return key ? [key] : [];
1868
+ }
1869
+ function stringifyRedisArgument(value) {
1870
+ if (value === void 0 || value === null) {
1871
+ return void 0;
1872
+ }
1873
+ if (Buffer.isBuffer(value)) {
1874
+ return `[Buffer len=${value.length}]`;
1875
+ }
1876
+ const normalized = String(value);
1877
+ const maxArgLen = 256;
1878
+ return normalized.length > maxArgLen ? `${normalized.slice(0, maxArgLen)}...` : normalized;
1879
+ }
1880
+
1881
+ // src/instrumentations/ioredis.ts
1882
+ var JENNIFER_IOREDIS_CONNECT_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.ioredis.connect.wrapped");
1883
+ var JENNIFER_IOREDIS_SEND_COMMAND_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.ioredis.sendCommand.wrapped");
1884
+ function patchIoredisModule(ioredisModule, moduleName) {
1885
+ try {
1886
+ const connectInstrumented = instrumentRedisConnect(ioredisModule);
1887
+ const commandInstrumented = instrumentRedisSendCommand(ioredisModule);
1888
+ if (connectInstrumented) {
1889
+ info9(`${moduleName}.prototype.connect instrumented`);
1890
+ }
1891
+ if (commandInstrumented) {
1892
+ info9(`${moduleName}.prototype.sendCommand instrumented`);
1893
+ }
1894
+ } catch (error) {
1895
+ warn11(`Failed to register ${moduleName} instrumentation: ${error}`);
1896
+ }
1897
+ }
1898
+ function instrumentRedisConnect(ioredisModule) {
1899
+ const Redis = resolveRedisConstructor(ioredisModule);
1900
+ const prototype = Redis?.prototype;
1901
+ if (!prototype || typeof prototype.connect !== "function" || prototype.connect?.[JENNIFER_IOREDIS_CONNECT_WRAPPED]) {
1902
+ return false;
1903
+ }
1904
+ wrap(prototype, "connect", (originalConnect) => {
1905
+ const wrapper = function(...args) {
1906
+ const ctx = contextManager.getCurrentContext();
1907
+ if (!ctx || !ctx.enable || !configEnableRedisProfile()) {
1908
+ return originalConnect.apply(this, args);
1909
+ }
1910
+ const connectionString = buildRedisConnectionString(this?.options);
1911
+ const startCtx = createDbConnectionProfileCtx3(void 0, connectionString, ctx.id);
1912
+ try {
1913
+ const result = originalConnect.apply(this, args);
1914
+ if (result && typeof result.then === "function") {
1915
+ return result.then(
1916
+ (value) => {
1917
+ releaseDbConnectionProfile(startCtx);
1918
+ return value;
1919
+ },
1920
+ (error) => {
1921
+ releaseDbConnectionProfile(startCtx, error);
1922
+ throw error;
1923
+ }
1924
+ );
1925
+ }
1926
+ releaseDbConnectionProfile(startCtx);
1927
+ return result;
1928
+ } catch (error) {
1929
+ releaseDbConnectionProfile(startCtx, error);
1930
+ throw error;
1931
+ }
1932
+ };
1933
+ wrapper[JENNIFER_IOREDIS_CONNECT_WRAPPED] = true;
1934
+ return wrapper;
1935
+ });
1936
+ return true;
1937
+ }
1938
+ function instrumentRedisSendCommand(ioredisModule) {
1939
+ const Redis = resolveRedisConstructor(ioredisModule);
1940
+ const prototype = Redis?.prototype;
1941
+ if (!prototype || typeof prototype.sendCommand !== "function" || prototype.sendCommand?.[JENNIFER_IOREDIS_SEND_COMMAND_WRAPPED]) {
1942
+ return false;
1943
+ }
1944
+ wrap(prototype, "sendCommand", (originalSendCommand) => {
1945
+ const wrapper = function(...args) {
1946
+ const ctx = contextManager.getCurrentContext();
1947
+ const command = args[0];
1948
+ const commandName = normalizeRedisCommandName(command?.name);
1949
+ if (!ctx || !ctx.enable || !configEnableRedisProfile() || !commandName || isRedisCommandBlocked(commandName)) {
1950
+ return originalSendCommand.apply(this, args);
1951
+ }
1952
+ const methodArgs = extractRedisMethodArguments(command?.args, 0);
1953
+ const startCtx = createMethodProfileCtx(`Redis.${commandName}`, methodArgs, ctx.id);
1954
+ if (!startCtx) {
1955
+ return originalSendCommand.apply(this, args);
1956
+ }
1957
+ let isReleased = false;
1958
+ const releaseSuccess2 = () => {
1959
+ if (isReleased) {
1960
+ return;
1961
+ }
1962
+ isReleased = true;
1963
+ releaseMethodProfileCtx(startCtx, {
1964
+ id: startCtx?.id ?? 0,
1965
+ txId: startCtx?.txId ?? 0
1966
+ });
1967
+ };
1968
+ const releaseError = (error) => {
1969
+ if (isReleased) {
1970
+ return;
1971
+ }
1972
+ isReleased = true;
1973
+ releaseMethodProfileCtx(startCtx, {
1974
+ id: startCtx?.id ?? 0,
1975
+ txId: startCtx?.txId ?? 0,
1976
+ error: error ? {
1977
+ message: error?.message,
1978
+ stack: error?.stack
1979
+ } : void 0
1980
+ });
1981
+ };
1982
+ try {
1983
+ const result = originalSendCommand.apply(this, args);
1984
+ if (result && typeof result.then === "function") {
1985
+ return result.then(
1986
+ (value) => {
1987
+ releaseSuccess2();
1988
+ return value;
1989
+ },
1990
+ (error) => {
1991
+ releaseError(error);
1992
+ throw error;
1993
+ }
1994
+ );
1995
+ }
1996
+ releaseSuccess2();
1997
+ return result;
1998
+ } catch (error) {
1999
+ releaseError(error);
2000
+ throw error;
2001
+ }
2002
+ };
2003
+ wrapper[JENNIFER_IOREDIS_SEND_COMMAND_WRAPPED] = true;
2004
+ return wrapper;
2005
+ });
2006
+ return true;
2007
+ }
2008
+ function resolveRedisConstructor(ioredisModule) {
2009
+ if (typeof ioredisModule === "function") {
2010
+ return ioredisModule;
2011
+ }
2012
+ if (typeof ioredisModule?.default === "function") {
2013
+ return ioredisModule.default;
2014
+ }
2015
+ if (typeof ioredisModule?.Redis === "function") {
2016
+ return ioredisModule.Redis;
2017
+ }
2018
+ return void 0;
2019
+ }
2020
+ function buildRedisConnectionString(options) {
2021
+ const { host, port, db } = extractConnectionOptions(options);
2022
+ return `datasource : redis://${host}:${port}/${db}`;
2023
+ }
2024
+ function extractConnectionOptions(options) {
2025
+ if (!options || typeof options !== "object") {
2026
+ return { host: "localhost", port: 6379, db: "0" };
2027
+ }
2028
+ const rawDb = options.db;
2029
+ const db = rawDb === void 0 || rawDb === null || rawDb === "" ? "0" : String(rawDb);
2030
+ return {
2031
+ host: options.host || options.sentinels?.[0]?.host || "localhost",
2032
+ port: Number(options.port || options.sentinels?.[0]?.port || 6379),
2033
+ db
2034
+ };
2035
+ }
2036
+
2037
+ // src/instrumentations/oracledb.ts
2038
+ import {
2039
+ configEnableOracledbProfile,
2040
+ createDbConnectionProfileCtx as createDbConnectionProfileCtx4,
2041
+ createSqlProfileCtx as createSqlProfileCtx3,
2042
+ SqlExecuteMethod as SqlExecuteMethod3,
2043
+ info as info10,
2044
+ warn as warn12
2045
+ } from "@jennifersoft/jennifer5-agent";
2046
+ var JENNIFER_WRAPPED8 = /* @__PURE__ */ Symbol.for("jennifer.oracledb.wrapped");
2047
+ var JENNIFER_PROTO_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.oracledb.connection.prototype.wrapped");
2048
+ function patchOracleDbModule(oracledbModule, moduleName) {
2049
+ try {
2050
+ if (instrumentGetConnection(oracledbModule)) {
2051
+ info10(`${moduleName}.getConnection instrumented`);
2052
+ }
2053
+ if (instrumentConnectionPrototype2(oracledbModule)) {
2054
+ info10(`${moduleName}.Connection.prototype instrumented`);
2055
+ }
2056
+ } catch (error) {
2057
+ warn12(`Failed to register ${moduleName} instrumentation: ${error}`);
2058
+ }
2059
+ }
2060
+ function instrumentGetConnection(oracledbModule) {
2061
+ if (oracledbModule.getConnection?.[JENNIFER_WRAPPED8]) {
2062
+ return false;
2063
+ }
2064
+ wrap(oracledbModule, "getConnection", (originalGetConnection) => {
2065
+ const wrapper = function(...args) {
2066
+ const config = args[0];
2067
+ const ctx = contextManager.getCurrentContext();
2068
+ if (!ctx || !ctx.enable || !configEnableOracledbProfile()) {
2069
+ return originalGetConnection.apply(this, args);
2070
+ }
2071
+ const connectionInfo = extractConnectionInfo3(config);
2072
+ const startCtx = createDbConnectionProfileCtx4(connectionInfo, void 0, ctx?.id);
2073
+ const lastArgIndex = args.length - 1;
2074
+ const hasCallback = lastArgIndex >= 0 && typeof args[lastArgIndex] === "function";
2075
+ if (hasCallback) {
2076
+ const originalCallback = args[lastArgIndex];
2077
+ args[lastArgIndex] = function(error, connection) {
2078
+ releaseWithError(startCtx, error);
2079
+ return contextManager.run(ctx, () => originalCallback.call(this, error, connection));
2080
+ };
2081
+ }
2082
+ try {
2083
+ const connectionResult = originalGetConnection.apply(this, args);
2084
+ if (hasCallback) {
2085
+ return connectionResult;
2086
+ }
2087
+ if (connectionResult && typeof connectionResult.then === "function") {
2088
+ return handlePromise(connectionResult, startCtx);
2089
+ }
2090
+ releaseSuccess(startCtx);
2091
+ return connectionResult;
2092
+ } catch (error) {
2093
+ releaseWithError(startCtx, error);
2094
+ throw error;
2095
+ }
2096
+ };
2097
+ wrapper[JENNIFER_WRAPPED8] = true;
2098
+ return wrapper;
2099
+ });
2100
+ return true;
2101
+ }
2102
+ function handlePromise(connectionPromise, startCtx) {
2103
+ return connectionPromise.then(
2104
+ (connection) => {
2105
+ releaseSuccess(startCtx);
2106
+ return connection;
2107
+ },
2108
+ (error) => {
2109
+ releaseWithError(startCtx, error);
2110
+ throw error;
2111
+ }
2112
+ );
2113
+ }
2114
+ function releaseSuccess(startCtx) {
2115
+ releaseDbConnectionProfile(startCtx);
2116
+ }
2117
+ function releaseWithError(startCtx, error) {
2118
+ releaseDbConnectionProfile(startCtx, error);
2119
+ }
2120
+ function instrumentConnectionPrototype2(oracledbModule) {
2121
+ const connectionProto = oracledbModule?.Connection?.prototype;
2122
+ if (!connectionProto || connectionProto.execute?.[JENNIFER_PROTO_WRAPPED]) {
2123
+ return false;
2124
+ }
2125
+ wrap(connectionProto, "execute", (originalExecute) => {
2126
+ const wrapper = function(...args) {
2127
+ const ctx = contextManager.getCurrentContext();
2128
+ if (!ctx || !ctx.enable || !configEnableOracledbProfile()) {
2129
+ return originalExecute.apply(this, args);
2130
+ }
2131
+ const sql = typeof args[0] === "string" ? args[0] : void 0;
2132
+ if (!sql) {
2133
+ return originalExecute.apply(this, args);
2134
+ }
2135
+ const boundParameters = extractBoundParameters3(args[1]);
2136
+ const startCtx = createSqlProfileCtx3(sql, SqlExecuteMethod3.Execute, boundParameters, ctx?.id);
2137
+ if (!startCtx) {
2138
+ return originalExecute.apply(this, args);
2139
+ }
2140
+ const lastArgIndex = args.length - 1;
2141
+ const hasCallback = lastArgIndex >= 0 && typeof args[lastArgIndex] === "function";
2142
+ if (hasCallback) {
2143
+ const originalCallback = args[lastArgIndex];
2144
+ args[lastArgIndex] = function(error, result) {
2145
+ releaseSqlWithError(startCtx, error);
2146
+ return contextManager.run(ctx, () => originalCallback.call(this, error, result));
2147
+ };
2148
+ }
2149
+ try {
2150
+ const resultPromise = originalExecute.apply(this, args);
2151
+ if (hasCallback) {
2152
+ return resultPromise;
2153
+ }
2154
+ if (resultPromise && typeof resultPromise.then === "function") {
2155
+ return handleSqlPromise(resultPromise, startCtx);
2156
+ }
2157
+ releaseSqlSuccess(startCtx);
2158
+ return resultPromise;
2159
+ } catch (error) {
2160
+ releaseSqlWithError(startCtx, error);
2161
+ throw error;
2162
+ }
2163
+ };
2164
+ wrapper[JENNIFER_PROTO_WRAPPED] = true;
2165
+ return wrapper;
2166
+ });
2167
+ return true;
2168
+ }
2169
+ function handleSqlPromise(resultPromise, startCtx) {
2170
+ return resultPromise.then(
2171
+ (result) => {
2172
+ releaseSqlSuccess(startCtx);
2173
+ return result;
2174
+ },
2175
+ (error) => {
2176
+ releaseSqlWithError(startCtx, error);
2177
+ throw error;
2178
+ }
2179
+ );
2180
+ }
2181
+ function releaseSqlSuccess(startCtx) {
2182
+ releaseSqlProfile(startCtx);
2183
+ }
2184
+ function releaseSqlWithError(startCtx, error) {
2185
+ releaseSqlProfile(startCtx, error);
2186
+ }
2187
+ function extractBoundParameters3(binds) {
2188
+ if (!binds) {
2189
+ return void 0;
2190
+ }
2191
+ if (!Array.isArray(binds) && typeof binds !== "object") {
2192
+ return void 0;
2193
+ }
2194
+ return toSqlParams(binds, {
2195
+ unwrapValue: (value) => value && typeof value === "object" && "val" in value ? value.val : value
2196
+ });
2197
+ }
2198
+ function extractConnectionInfo3(config) {
2199
+ if (!config || typeof config === "function") {
2200
+ return getDefaultPoolInfo();
2201
+ }
2202
+ if (typeof config === "string") {
2203
+ if (isLikelyPoolAlias(config)) {
2204
+ return getPoolAliasInfo(config);
2205
+ }
2206
+ const parsed2 = parseOracleConnectString(config);
2207
+ return {
2208
+ host: parsed2.host,
2209
+ port: parsed2.port,
2210
+ user: "",
2211
+ database: parsed2.serviceName
2212
+ };
2213
+ }
2214
+ const connectString = typeof config.connectString === "string" ? config.connectString : "";
2215
+ const parsed = connectString ? parseOracleConnectString(connectString) : void 0;
2216
+ const poolAlias = typeof config.poolAlias === "string" ? config.poolAlias : "";
2217
+ if (!parsed && poolAlias) {
2218
+ return {
2219
+ ...getPoolAliasInfo(poolAlias),
2220
+ user: config.user || ""
2221
+ };
2222
+ }
2223
+ return {
2224
+ host: parsed?.host || "localhost",
2225
+ port: parsed?.port || 1521,
2226
+ user: config.user || "",
2227
+ database: parsed?.serviceName || ""
2228
+ };
2229
+ }
2230
+ function parseOracleConnectString(connectString) {
2231
+ if (!connectString) {
2232
+ return {
2233
+ host: "localhost",
2234
+ port: 1521,
2235
+ serviceName: ""
2236
+ };
2237
+ }
2238
+ const match = connectString.match(/^([^:/]+)(?::(\d+))?(?:\/([^\?]+))?/);
2239
+ if (match) {
2240
+ return {
2241
+ host: match[1] || "localhost",
2242
+ port: Number(match[2] || "1521"),
2243
+ serviceName: match[3] || ""
2244
+ };
2245
+ }
2246
+ return {
2247
+ host: connectString,
2248
+ port: 1521,
2249
+ serviceName: ""
2250
+ };
2251
+ }
2252
+ function isLikelyPoolAlias(value) {
2253
+ return !/[/:]/.test(value);
2254
+ }
2255
+ function getDefaultPoolInfo() {
2256
+ return getPoolAliasInfo("default");
2257
+ }
2258
+ function getPoolAliasInfo(alias) {
2259
+ return {
2260
+ host: `alias:${alias}`,
2261
+ port: 1521,
2262
+ user: "",
2263
+ database: ""
2264
+ };
2265
+ }
2266
+
2267
+ // src/instrumentations/pg.ts
2268
+ import {
2269
+ configEnablePgProfile,
2270
+ createSqlProfileCtx as createSqlProfileCtx4,
2271
+ SqlExecuteMethod as SqlExecuteMethod4,
2272
+ info as info11,
2273
+ warn as warn13
2274
+ } from "@jennifersoft/jennifer5-agent";
2275
+ var JENNIFER_PG_CLIENT_QUERY_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.pg.client.query.wrapped");
2276
+ function patchPgClientModule(clientModule, moduleName) {
2277
+ try {
2278
+ const clientPrototype = resolveClientPrototype(clientModule);
2279
+ if (!instrumentQueryMethod(clientPrototype, "query", JENNIFER_PG_CLIENT_QUERY_WRAPPED)) {
2280
+ return;
2281
+ }
2282
+ info11(`${moduleName}.Client.prototype.query instrumented`);
2283
+ } catch (error) {
2284
+ warn13(`Failed to register ${moduleName} instrumentation: ${error}`);
2285
+ }
2286
+ }
2287
+ function resolveClientPrototype(clientModule) {
2288
+ if (!clientModule) {
2289
+ return void 0;
2290
+ }
2291
+ if (clientModule?.Client?.prototype) {
2292
+ return clientModule.Client.prototype;
2293
+ }
2294
+ if (clientModule?.prototype) {
2295
+ return clientModule.prototype;
2296
+ }
2297
+ if (clientModule?.default?.prototype) {
2298
+ return clientModule.default.prototype;
2299
+ }
2300
+ if (clientModule?.default?.Client?.prototype) {
2301
+ return clientModule.default.Client.prototype;
2302
+ }
2303
+ return void 0;
2304
+ }
2305
+ function instrumentQueryMethod(prototype, methodName, wrapMarker) {
2306
+ if (!prototype || typeof prototype[methodName] !== "function" || prototype[methodName]?.[wrapMarker]) {
2307
+ return false;
2308
+ }
2309
+ wrap(prototype, methodName, (originalMethod) => {
2310
+ const wrapper = function(...args) {
2311
+ const ctx = contextManager.getCurrentContext();
2312
+ if (!ctx || !ctx.enable || !configEnablePgProfile()) {
2313
+ return originalMethod.apply(this, args);
2314
+ }
2315
+ const sqlData = extractSqlAndParams3(args);
2316
+ if (!sqlData?.sql) {
2317
+ return originalMethod.apply(this, args);
2318
+ }
2319
+ const startCtx = createSqlProfileCtx4(
2320
+ sqlData.sql,
2321
+ SqlExecuteMethod4.ExecuteQuery,
2322
+ extractBoundParameters4(sqlData.params),
2323
+ ctx?.id
2324
+ );
2325
+ if (!startCtx) {
2326
+ return originalMethod.apply(this, args);
2327
+ }
2328
+ let isReleased = false;
2329
+ const releaseSuccess2 = () => {
2330
+ if (isReleased) {
2331
+ return;
2332
+ }
2333
+ isReleased = true;
2334
+ releaseSqlProfile(startCtx);
2335
+ };
2336
+ const releaseError = (error) => {
2337
+ if (isReleased) {
2338
+ return;
2339
+ }
2340
+ isReleased = true;
2341
+ releaseSqlProfile(startCtx, error);
2342
+ };
2343
+ const lastArgIndex = args.length - 1;
2344
+ const hasCallback = lastArgIndex >= 0 && typeof args[lastArgIndex] === "function";
2345
+ if (hasCallback) {
2346
+ const originalCallback = args[lastArgIndex];
2347
+ args[lastArgIndex] = function(...callbackArgs) {
2348
+ const callbackError = callbackArgs[0];
2349
+ if (callbackError) {
2350
+ releaseError(callbackError);
2351
+ } else {
2352
+ releaseSuccess2();
2353
+ }
2354
+ return contextManager.run(ctx, () => originalCallback.apply(this, callbackArgs));
2355
+ };
2356
+ }
2357
+ try {
2358
+ const result = originalMethod.apply(this, args);
2359
+ if (hasCallback) {
2360
+ return result;
2361
+ }
2362
+ if (result && typeof result.then === "function") {
2363
+ return result.then(
2364
+ (value) => {
2365
+ releaseSuccess2();
2366
+ return value;
2367
+ },
2368
+ (error) => {
2369
+ releaseError(error);
2370
+ throw error;
2371
+ }
2372
+ );
2373
+ }
2374
+ if (result && typeof result.once === "function") {
2375
+ result.once("end", releaseSuccess2);
2376
+ result.once("error", releaseError);
2377
+ return result;
2378
+ }
2379
+ releaseSuccess2();
2380
+ return result;
2381
+ } catch (error) {
2382
+ releaseError(error);
2383
+ throw error;
2384
+ }
2385
+ };
2386
+ wrapper[wrapMarker] = true;
2387
+ return wrapper;
2388
+ });
2389
+ return true;
2390
+ }
2391
+ function extractSqlAndParams3(args) {
2392
+ if (!args.length) {
2393
+ return void 0;
2394
+ }
2395
+ const firstArg = args[0];
2396
+ const secondArg = args[1];
2397
+ if (firstArg && typeof firstArg === "object" && typeof firstArg.submit === "function") {
2398
+ return void 0;
2399
+ }
2400
+ if (typeof firstArg === "string") {
2401
+ return {
2402
+ sql: firstArg,
2403
+ params: normalizeOptionalParams(secondArg)
2404
+ };
2405
+ }
2406
+ if (firstArg && typeof firstArg === "object" && typeof firstArg.text === "string") {
2407
+ return {
2408
+ sql: firstArg.text,
2409
+ params: normalizeOptionalParams(firstArg.values)
2410
+ };
2411
+ }
2412
+ return void 0;
2413
+ }
2414
+ function extractBoundParameters4(params) {
2415
+ return toSqlParams(params);
2416
+ }
2417
+
2418
+ // src/instrumentations/prisma.ts
2419
+ import {
2420
+ configEnablePrismaProfile,
2421
+ createSqlProfileCtx as createSqlProfileCtx5,
2422
+ SqlExecuteMethod as SqlExecuteMethod5,
2423
+ SqlParamType as SqlParamType2,
2424
+ info as info12,
2425
+ warn as warn14
2426
+ } from "@jennifersoft/jennifer5-agent";
2427
+ var JENNIFER_WRAPPED9 = /* @__PURE__ */ Symbol.for("jennifer.prisma.wrapped");
2428
+ var JENNIFER_INSTANCE_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.prisma.instance.wrapped");
2429
+ function patchPrismaModule(prismaModule, moduleName) {
2430
+ try {
2431
+ if (instrumentPrismaClient(prismaModule)) {
2432
+ info12(`${moduleName}.PrismaClient instrumented`);
2433
+ }
2434
+ } catch (error) {
2435
+ warn14(`Failed to register ${moduleName} instrumentation: ${error}`);
2436
+ }
2437
+ }
2438
+ function instrumentPrismaClient(prismaModule) {
2439
+ if (!prismaModule?.PrismaClient || prismaModule.PrismaClient[JENNIFER_WRAPPED9]) {
2440
+ return false;
2441
+ }
2442
+ wrap(prismaModule, "PrismaClient", (originalConstructor) => {
2443
+ const wrapper = function(...args) {
2444
+ const instance = Reflect.construct(originalConstructor, args);
2445
+ const patchedInstance = patchPrismaInstance(instance);
2446
+ return patchedInstance ?? instance;
2447
+ };
2448
+ wrapper[JENNIFER_WRAPPED9] = true;
2449
+ return wrapper;
2450
+ });
2451
+ return true;
2452
+ }
2453
+ function patchPrismaInstance(prismaInstance) {
2454
+ if (!prismaInstance || prismaInstance[JENNIFER_INSTANCE_WRAPPED]) {
2455
+ return prismaInstance;
2456
+ }
2457
+ prismaInstance[JENNIFER_INSTANCE_WRAPPED] = true;
2458
+ hookUseMiddleware(prismaInstance);
2459
+ return hookQueryExtension(prismaInstance) ?? prismaInstance;
2460
+ }
2461
+ function safeStringify(args) {
2462
+ if (!args) return "";
2463
+ try {
2464
+ const stringified = JSON.stringify(args);
2465
+ return stringified.length > 1e3 ? `${stringified.substring(0, 1e3)}...` : stringified;
2466
+ } catch {
2467
+ return "[Unserializable Args]";
2468
+ }
2469
+ }
2470
+ function hookUseMiddleware(prismaInstance) {
2471
+ if (typeof prismaInstance.$use !== "function") {
2472
+ return;
2473
+ }
2474
+ prismaInstance.$use(async (params, next) => {
2475
+ const ctx = contextManager.getCurrentContext();
2476
+ if (!ctx || !ctx.enable || !configEnablePrismaProfile()) {
2477
+ return next(params);
2478
+ }
2479
+ const modelName = params?.model;
2480
+ const action = params?.operation || params?.action || "unknown";
2481
+ const argsStr = safeStringify(params?.args);
2482
+ const queryInfo = modelName ? `Prisma ${modelName}.${action}`.trim() : `Prisma.${action}`.trim();
2483
+ const startCtx = createSqlProfileCtx5(
2484
+ queryInfo,
2485
+ SqlExecuteMethod5.Execute,
2486
+ [
2487
+ {
2488
+ value: argsStr,
2489
+ paramType: SqlParamType2.String
2490
+ }
2491
+ ],
2492
+ ctx.id
2493
+ );
2494
+ if (!startCtx) {
2495
+ return next(params);
2496
+ }
2497
+ try {
2498
+ const result = await next(params);
2499
+ releaseSqlProfile(startCtx);
2500
+ return result;
2501
+ } catch (error) {
2502
+ releaseSqlProfile(startCtx, error);
2503
+ throw error;
2504
+ }
2505
+ });
2506
+ }
2507
+ function hookQueryExtension(prismaInstance) {
2508
+ if (typeof prismaInstance.$extends !== "function") {
2509
+ return prismaInstance;
2510
+ }
2511
+ const traceOperation = async (params) => {
2512
+ const ctx = contextManager.getCurrentContext();
2513
+ if (!ctx || !ctx.enable || !configEnablePrismaProfile()) {
2514
+ return params.query(params.args);
2515
+ }
2516
+ const modelName = params?.model;
2517
+ const action = params?.operation || params?.action || "unknown";
2518
+ const argsStr = safeStringify(params?.args);
2519
+ const queryInfo = modelName ? `Prisma ${modelName}.${action} ?`.trim() : `Prisma.${action} ?`.trim();
2520
+ const startCtx = createSqlProfileCtx5(
2521
+ queryInfo,
2522
+ SqlExecuteMethod5.Execute,
2523
+ [
2524
+ {
2525
+ value: argsStr,
2526
+ paramType: SqlParamType2.String
2527
+ }
2528
+ ],
2529
+ ctx.id
2530
+ );
2531
+ if (!startCtx) {
2532
+ return params.query(params.args);
2533
+ }
2534
+ try {
2535
+ const result = await params.query(params.args);
2536
+ releaseSqlProfile(startCtx);
2537
+ return result;
2538
+ } catch (error) {
2539
+ releaseSqlProfile(startCtx, error);
2540
+ throw error;
2541
+ }
2542
+ };
2543
+ const extended = prismaInstance.$extends({
2544
+ query: {
2545
+ $allModels: {
2546
+ $allOperations: async (params) => traceOperation(params)
2547
+ },
2548
+ // Raw queries
2549
+ $queryRaw: async (params) => traceOperation(params),
2550
+ $executeRaw: async (params) => traceOperation(params),
2551
+ $queryRawUnsafe: async (params) => traceOperation(params),
2552
+ $executeRawUnsafe: async (params) => traceOperation(params)
2553
+ }
2554
+ });
2555
+ extended[JENNIFER_INSTANCE_WRAPPED] = true;
2556
+ return extended;
2557
+ }
2558
+
2559
+ // src/instrumentations/redis.ts
2560
+ import {
2561
+ configEnableRedisProfile as configEnableRedisProfile2,
2562
+ createDbConnectionProfileCtx as createDbConnectionProfileCtx5,
2563
+ createMethodProfileCtx as createMethodProfileCtx2,
2564
+ info as info13,
2565
+ releaseMethodProfileCtx as releaseMethodProfileCtx2,
2566
+ warn as warn15
2567
+ } from "@jennifersoft/jennifer5-agent";
2568
+ var JENNIFER_REDIS_CONNECT_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.redis.connect.wrapped");
2569
+ var JENNIFER_REDIS_ADD_COMMAND_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.redis.addCommand.wrapped");
2570
+ var JENNIFER_REDIS_CREATE_CLIENT_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.redis.createClient.wrapped");
2571
+ function patchRedisModule(redisModule, moduleName) {
2572
+ try {
2573
+ const instrumented = instrumentRedisCreateClient(redisModule);
2574
+ if (instrumented) {
2575
+ info13(`${moduleName}.createClient instrumented`);
2576
+ }
2577
+ } catch (error) {
2578
+ warn15(`Failed to register ${moduleName} instrumentation: ${error}`);
2579
+ }
2580
+ }
2581
+ function patchRedisCommandsQueueModule(redisCommandsQueueModule, moduleName) {
2582
+ try {
2583
+ const instrumented = instrumentRedisAddCommand(redisCommandsQueueModule);
2584
+ if (instrumented) {
2585
+ info13(`${moduleName}.prototype.addCommand instrumented`);
2586
+ }
2587
+ } catch (error) {
2588
+ warn15(`Failed to register ${moduleName} instrumentation: ${error}`);
2589
+ }
2590
+ }
2591
+ function instrumentRedisCreateClient(redisModule) {
2592
+ if (!redisModule || typeof redisModule.createClient !== "function" || redisModule.createClient[JENNIFER_REDIS_CREATE_CLIENT_WRAPPED]) {
2593
+ return false;
2594
+ }
2595
+ wrap(redisModule, "createClient", (originalCreateClient) => {
2596
+ const wrapper = function(...args) {
2597
+ const client = originalCreateClient.apply(this, args);
2598
+ instrumentRedisConnect2(client);
2599
+ return client;
2600
+ };
2601
+ wrapper[JENNIFER_REDIS_CREATE_CLIENT_WRAPPED] = true;
2602
+ return wrapper;
2603
+ });
2604
+ return true;
2605
+ }
2606
+ function instrumentRedisConnect2(client) {
2607
+ const prototype = resolveRedisConnectPrototype(client);
2608
+ if (!prototype || prototype.connect[JENNIFER_REDIS_CONNECT_WRAPPED]) {
2609
+ return false;
2610
+ }
2611
+ wrap(prototype, "connect", (originalConnect) => {
2612
+ const wrapper = function(...args) {
2613
+ const ctx = contextManager.getCurrentContext();
2614
+ if (!ctx || !ctx.enable || !configEnableRedisProfile2()) {
2615
+ return originalConnect.apply(this, args);
2616
+ }
2617
+ const connectionString = buildRedisConnectionString2(this?.options);
2618
+ const startCtx = createDbConnectionProfileCtx5(void 0, connectionString, ctx.id);
2619
+ try {
2620
+ const result = originalConnect.apply(this, args);
2621
+ if (result && typeof result.then === "function") {
2622
+ return result.then(
2623
+ (value) => {
2624
+ releaseDbConnectionProfile(startCtx);
2625
+ return value;
2626
+ },
2627
+ (error) => {
2628
+ releaseDbConnectionProfile(startCtx, error);
2629
+ throw error;
2630
+ }
2631
+ );
2632
+ }
2633
+ releaseDbConnectionProfile(startCtx);
2634
+ return result;
2635
+ } catch (error) {
2636
+ releaseDbConnectionProfile(startCtx, error);
2637
+ throw error;
2638
+ }
2639
+ };
2640
+ wrapper[JENNIFER_REDIS_CONNECT_WRAPPED] = true;
2641
+ return wrapper;
2642
+ });
2643
+ return true;
2644
+ }
2645
+ function instrumentRedisAddCommand(redisCommandsQueueModule) {
2646
+ const RedisCommandsQueue = resolveRedisCommandsQueueConstructor(redisCommandsQueueModule);
2647
+ const prototype = RedisCommandsQueue?.prototype;
2648
+ if (!prototype || typeof prototype.addCommand !== "function" || prototype.addCommand[JENNIFER_REDIS_ADD_COMMAND_WRAPPED]) {
2649
+ return false;
2650
+ }
2651
+ wrap(prototype, "addCommand", (originalAddCommand) => {
2652
+ const wrapper = function(...args) {
2653
+ const ctx = contextManager.getCurrentContext();
2654
+ const commandArgs = args[0];
2655
+ const commandName = normalizeRedisCommandName(commandArgs?.[0]);
2656
+ if (!ctx || !ctx.enable || !configEnableRedisProfile2() || !commandName || isRedisCommandBlocked(commandName)) {
2657
+ return originalAddCommand.apply(this, args);
2658
+ }
2659
+ const methodArgs = extractRedisMethodArguments(commandArgs, 1);
2660
+ const startCtx = createMethodProfileCtx2(`Redis.${commandName}`, methodArgs, ctx.id);
2661
+ if (!startCtx) {
2662
+ return originalAddCommand.apply(this, args);
2663
+ }
2664
+ let isReleased = false;
2665
+ const releaseSuccess2 = () => {
2666
+ if (isReleased) {
2667
+ return;
2668
+ }
2669
+ isReleased = true;
2670
+ releaseMethodProfileCtx2(startCtx, {
2671
+ id: startCtx?.id ?? 0,
2672
+ txId: startCtx?.txId ?? 0
2673
+ });
2674
+ };
2675
+ const releaseError = (error) => {
2676
+ if (isReleased) {
2677
+ return;
2678
+ }
2679
+ isReleased = true;
2680
+ releaseMethodProfileCtx2(startCtx, {
2681
+ id: startCtx?.id ?? 0,
2682
+ txId: startCtx?.txId ?? 0,
2683
+ error: error ? {
2684
+ message: error?.message,
2685
+ stack: error?.stack
2686
+ } : void 0
2687
+ });
2688
+ };
2689
+ try {
2690
+ const result = originalAddCommand.apply(this, args);
2691
+ if (result && typeof result.then === "function") {
2692
+ return result.then(
2693
+ (value) => {
2694
+ releaseSuccess2();
2695
+ return value;
2696
+ },
2697
+ (error) => {
2698
+ releaseError(error);
2699
+ throw error;
2700
+ }
2701
+ );
2702
+ }
2703
+ releaseSuccess2();
2704
+ return result;
2705
+ } catch (error) {
2706
+ releaseError(error);
2707
+ throw error;
2708
+ }
2709
+ };
2710
+ wrapper[JENNIFER_REDIS_ADD_COMMAND_WRAPPED] = true;
2711
+ return wrapper;
2712
+ });
2713
+ return true;
2714
+ }
2715
+ function resolveRedisConnectPrototype(client) {
2716
+ let current = client;
2717
+ while (current) {
2718
+ const descriptor = Object.getOwnPropertyDescriptor(current, "connect");
2719
+ if (descriptor && typeof descriptor.value === "function") {
2720
+ return current;
2721
+ }
2722
+ current = Object.getPrototypeOf(current);
2723
+ }
2724
+ return void 0;
2725
+ }
2726
+ function resolveRedisCommandsQueueConstructor(redisCommandsQueueModule) {
2727
+ if (typeof redisCommandsQueueModule === "function") {
2728
+ return redisCommandsQueueModule;
2729
+ }
2730
+ if (typeof redisCommandsQueueModule?.default === "function") {
2731
+ return redisCommandsQueueModule.default;
2732
+ }
2733
+ return void 0;
2734
+ }
2735
+ function buildRedisConnectionString2(options) {
2736
+ const socket = options?.socket;
2737
+ const host = socket?.host || options?.host || "localhost";
2738
+ const port = Number(socket?.port || options?.port || 6379);
2739
+ const rawDb = options?.database ?? options?.db ?? 0;
2740
+ const db = rawDb === void 0 || rawDb === null || rawDb === "" ? "0" : String(rawDb);
2741
+ return `datasource : redis://${host}:${port}/${db}`;
2742
+ }
2743
+
2744
+ // src/instrumentations/tedious.ts
2745
+ import {
2746
+ configEnableTediousProfile,
2747
+ createSqlProfileCtx as createSqlProfileCtx6,
2748
+ SqlExecuteMethod as SqlExecuteMethod6,
2749
+ info as info14,
2750
+ warn as warn16
2751
+ } from "@jennifersoft/jennifer5-agent";
2752
+ var JENNIFER_TEDIOUS_MAKE_REQUEST_WRAPPED = /* @__PURE__ */ Symbol.for(
2753
+ "jennifer.tedious.connection.makeRequest.wrapped"
2754
+ );
2755
+ function patchTediousModule(tediousModule, moduleName) {
2756
+ try {
2757
+ if (instrumentConnectionPrototype3(tediousModule?.Connection?.prototype)) {
2758
+ info14(`${moduleName}.Connection.prototype.makeRequest instrumented`);
2759
+ }
2760
+ } catch (error) {
2761
+ warn16(`Failed to register ${moduleName} instrumentation: ${error}`);
2762
+ }
2763
+ }
2764
+ function instrumentConnectionPrototype3(connectionPrototype) {
2765
+ if (!connectionPrototype || typeof connectionPrototype.makeRequest !== "function" || connectionPrototype.makeRequest?.[JENNIFER_TEDIOUS_MAKE_REQUEST_WRAPPED]) {
2766
+ return false;
2767
+ }
2768
+ wrap(connectionPrototype, "makeRequest", (originalMakeRequest) => {
2769
+ const wrapper = function(request, ...args) {
2770
+ const ctx = contextManager.getCurrentContext();
2771
+ if (!ctx || !ctx.enable || !configEnableTediousProfile()) {
2772
+ return originalMakeRequest.call(this, request, ...args);
2773
+ }
2774
+ const sqlInfo = extractSqlInfo(request);
2775
+ if (!sqlInfo?.sql) {
2776
+ return originalMakeRequest.call(this, request, ...args);
2777
+ }
2778
+ const startCtx = createSqlProfileCtx6(
2779
+ sqlInfo.sql,
2780
+ SqlExecuteMethod6.Execute,
2781
+ extractBoundParameters5(request),
2782
+ ctx?.id
2783
+ );
2784
+ if (!startCtx) {
2785
+ return originalMakeRequest.call(this, request, ...args);
2786
+ }
2787
+ let isReleased = false;
2788
+ const releaseSuccess2 = () => {
2789
+ if (isReleased) {
2790
+ return;
2791
+ }
2792
+ isReleased = true;
2793
+ releaseSqlProfile(startCtx);
2794
+ };
2795
+ const releaseError = (error) => {
2796
+ if (isReleased) {
2797
+ return;
2798
+ }
2799
+ isReleased = true;
2800
+ releaseSqlProfile(startCtx, error);
2801
+ };
2802
+ const originalCallback = request?.callback;
2803
+ if (typeof originalCallback === "function") {
2804
+ request.callback = function(error, ...callbackArgs) {
2805
+ if (error) {
2806
+ releaseError(error);
2807
+ } else {
2808
+ releaseSuccess2();
2809
+ }
2810
+ return contextManager.run(ctx, () => originalCallback.call(this, error, ...callbackArgs));
2811
+ };
2812
+ }
2813
+ try {
2814
+ const result = originalMakeRequest.call(this, request, ...args);
2815
+ if (typeof originalCallback !== "function") {
2816
+ releaseSuccess2();
2817
+ }
2818
+ return result;
2819
+ } catch (error) {
2820
+ releaseError(error);
2821
+ throw error;
2822
+ }
2823
+ };
2824
+ wrapper[JENNIFER_TEDIOUS_MAKE_REQUEST_WRAPPED] = true;
2825
+ return wrapper;
2826
+ });
2827
+ return true;
2828
+ }
2829
+ function extractSqlInfo(request) {
2830
+ if (!request || typeof request !== "object") {
2831
+ return void 0;
2832
+ }
2833
+ const statement = request?.parametersByName?.statement;
2834
+ if (statement && typeof statement.value === "string") {
2835
+ return { sql: statement.value, sqlContainer: statement, sqlField: "value" };
2836
+ }
2837
+ const stmt = request?.parametersByName?.stmt;
2838
+ if (stmt && typeof stmt.value === "string") {
2839
+ return { sql: stmt.value, sqlContainer: stmt, sqlField: "value" };
2840
+ }
2841
+ if (typeof request.sqlTextOrProcedure === "string") {
2842
+ return {
2843
+ sql: request.sqlTextOrProcedure,
2844
+ sqlContainer: request,
2845
+ sqlField: "sqlTextOrProcedure"
2846
+ };
2847
+ }
2848
+ return void 0;
2849
+ }
2850
+ function extractBoundParameters5(request) {
2851
+ const parameters = request?.parameters;
2852
+ if (!Array.isArray(parameters) || parameters.length === 0) {
2853
+ return void 0;
2854
+ }
2855
+ const values = parameters.filter((parameter) => parameter && typeof parameter === "object").map((parameter) => parameter.value);
2856
+ return toSqlParams(values);
2857
+ }
2858
+
2859
+ // src/instrumentations/typeorm.ts
2860
+ import {
2861
+ configEnableTypeormProfile,
2862
+ createSqlProfileCtx as createSqlProfileCtx7,
2863
+ SqlExecuteMethod as SqlExecuteMethod7,
2864
+ info as info15,
2865
+ warn as warn17
2866
+ } from "@jennifersoft/jennifer5-agent";
2867
+ var JENNIFER_DATASOURCE_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.typeorm.datasource.wrapped");
2868
+ var JENNIFER_QUERYRUNNER_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.typeorm.queryrunner.wrapped");
2869
+ function patchTypeormModule(typeormModule, moduleName) {
2870
+ try {
2871
+ if (instrumentDataSource(typeormModule?.DataSource)) {
2872
+ info15(`${moduleName}.DataSource instrumented`);
2873
+ }
2874
+ } catch (error) {
2875
+ warn17(`Failed to register ${moduleName} instrumentation: ${error}`);
2876
+ }
2877
+ }
2878
+ function instrumentDataSource(dataSourceClass) {
2879
+ const prototype = dataSourceClass?.prototype;
2880
+ if (!prototype || prototype.createQueryRunner?.[JENNIFER_DATASOURCE_WRAPPED]) {
2881
+ return false;
2882
+ }
2883
+ wrap(prototype, "createQueryRunner", (originalCreateQueryRunner) => {
2884
+ const wrapper = function(...args) {
2885
+ const queryRunner = originalCreateQueryRunner.apply(this, args);
2886
+ instrumentQueryRunner(queryRunner);
2887
+ return queryRunner;
2888
+ };
2889
+ wrapper[JENNIFER_DATASOURCE_WRAPPED] = true;
2890
+ return wrapper;
2891
+ });
2892
+ return true;
2893
+ }
2894
+ function instrumentQueryRunner(queryRunner) {
2895
+ if (!queryRunner || typeof queryRunner.query !== "function" || queryRunner.query?.[JENNIFER_QUERYRUNNER_WRAPPED]) {
2896
+ return;
2897
+ }
2898
+ wrap(queryRunner, "query", (originalQuery) => {
2899
+ const wrapper = function(...args) {
2900
+ const ctx = contextManager.getCurrentContext();
2901
+ if (!ctx || !ctx.enable || !configEnableTypeormProfile()) {
2902
+ return originalQuery.apply(this, args);
2903
+ }
2904
+ const sql = args[0];
2905
+ if (typeof sql !== "string") {
2906
+ return originalQuery.apply(this, args);
2907
+ }
2908
+ const params = extractBoundParameters6(args[1]);
2909
+ const startCtx = createSqlProfileCtx7(sql, SqlExecuteMethod7.Execute, params, ctx?.id);
2910
+ if (!startCtx) {
2911
+ return originalQuery.apply(this, args);
2912
+ }
2913
+ try {
2914
+ const result = originalQuery.apply(this, args);
2915
+ if (result && typeof result.then === "function") {
2916
+ return result.then(
2917
+ (value) => {
2918
+ releaseSqlProfile(startCtx);
2919
+ return value;
2920
+ },
2921
+ (error) => {
2922
+ releaseSqlProfile(startCtx, error);
2923
+ throw error;
2924
+ }
2925
+ );
2926
+ }
2927
+ releaseSqlProfile(startCtx);
2928
+ return result;
2929
+ } catch (error) {
2930
+ releaseSqlProfile(startCtx, error);
2931
+ throw error;
2932
+ }
2933
+ };
2934
+ wrapper[JENNIFER_QUERYRUNNER_WRAPPED] = true;
2935
+ return wrapper;
2936
+ });
2937
+ }
2938
+ function extractBoundParameters6(params) {
2939
+ return toSqlParams(params);
2940
+ }
2941
+
2942
+ // src/instrumentations/undici.ts
2943
+ import {
2944
+ info as info16,
2945
+ warn as warn18,
2946
+ isAgentId as isAgentId2,
2947
+ createHttpProfileCtx as createHttpProfileCtx3,
2948
+ releaseHttpProfileCtx as releaseHttpProfileCtx3,
2949
+ configEnableHttpClientProfile as configEnableHttpClientProfile3,
2950
+ configEnableHttpTopologyMode as configEnableHttpTopologyMode2,
2951
+ configTopologyHttpHeaderKey as configTopologyHttpHeaderKey2
2952
+ } from "@jennifersoft/jennifer5-agent";
2953
+ var JENNIFER_UNDICI_FETCH_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.undici.fetch.wrapped");
2954
+ var JENNIFER_UNDICI_REQUEST_WRAPPED = /* @__PURE__ */ Symbol.for("jennifer.undici.request.wrapped");
2955
+ var X_DOMAIN_ID2 = "x-domainid";
2956
+ var X_AGENT_ID2 = "x-agentid";
2957
+ function resolveHeadersCtor(undiciModule) {
2958
+ return undiciModule.Headers ?? globalThis.Headers;
2959
+ }
2960
+ function resolveRequestCtor(undiciModule) {
2961
+ return undiciModule.Request ?? globalThis.Request;
2962
+ }
2963
+ function patchUndiciModule(undiciModule, moduleName) {
2964
+ try {
2965
+ let patched = false;
2966
+ if (typeof undiciModule?.fetch === "function" && !undiciModule.fetch[JENNIFER_UNDICI_FETCH_WRAPPED]) {
2967
+ wrap(undiciModule, "fetch", (originalFetch) => {
2968
+ const wrapper = createUndiciFetchWrapper(originalFetch, undiciModule);
2969
+ wrapper[JENNIFER_UNDICI_FETCH_WRAPPED] = true;
2970
+ return wrapper;
2971
+ });
2972
+ patched = true;
2973
+ }
2974
+ if (typeof undiciModule?.request === "function" && !undiciModule.request[JENNIFER_UNDICI_REQUEST_WRAPPED]) {
2975
+ wrap(undiciModule, "request", (originalRequest) => {
2976
+ const wrapper = createUndiciRequestWrapper(
2977
+ originalRequest,
2978
+ resolveHeadersCtor(undiciModule)
2979
+ );
2980
+ wrapper[JENNIFER_UNDICI_REQUEST_WRAPPED] = true;
2981
+ return wrapper;
2982
+ });
2983
+ patched = true;
2984
+ }
2985
+ if (patched) {
2986
+ info16(`${moduleName} instrumentation registered`);
2987
+ }
2988
+ } catch (error) {
2989
+ warn18(`Failed to register ${moduleName} instrumentation: ${error}`);
2990
+ }
2991
+ }
2992
+ function createUndiciFetchWrapper(originalFetch, undiciModule) {
2993
+ return function(...args) {
2994
+ const ctx = contextManager.getCurrentContext();
2995
+ if (!ctx || !ctx.enable || !configEnableHttpClientProfile3()) {
2996
+ return originalFetch(...args);
2997
+ }
2998
+ const [input, init] = args;
2999
+ const HeadersCtor = resolveHeadersCtor(undiciModule);
3000
+ const RequestCtor = resolveRequestCtor(undiciModule);
3001
+ let startCtx = null;
3002
+ try {
3003
+ if (RequestCtor && input instanceof RequestCtor) {
3004
+ const normalizedRequest = init ? new RequestCtor(input, init) : input;
3005
+ const fetchHeaders2 = toHeaders(normalizedRequest.headers, HeadersCtor);
3006
+ setTopologyFetchHeaders(fetchHeaders2);
3007
+ const headers2 = headersToRecord(fetchHeaders2);
3008
+ const wrappedRequest = new RequestCtor(normalizedRequest, { headers: fetchHeaders2 });
3009
+ startCtx = createHttpProfileCtx3(
3010
+ normalizedRequest.method || "GET",
3011
+ normalizedRequest.url,
3012
+ headers2,
3013
+ ctx.id
3014
+ );
3015
+ return handleFetchResult(originalFetch(wrappedRequest), startCtx);
3016
+ }
3017
+ const url = typeof input === "string" ? input : input?.href || String(input);
3018
+ const method = init?.method || "GET";
3019
+ const fetchHeaders = toHeaders(init?.headers, HeadersCtor);
3020
+ setTopologyFetchHeaders(fetchHeaders);
3021
+ const headers = headersToRecord(fetchHeaders);
3022
+ const modifiedInit = {
3023
+ ...init,
3024
+ headers: fetchHeaders
3025
+ };
3026
+ startCtx = createHttpProfileCtx3(method, url, headers, ctx.id);
3027
+ return handleFetchResult(originalFetch(input, modifiedInit), startCtx);
3028
+ } catch (error) {
3029
+ releaseHttpProfileCtx3(startCtx, {
3030
+ error: {
3031
+ message: error?.message,
3032
+ stack: error?.stack
3033
+ }
3034
+ });
3035
+ throw error;
3036
+ }
3037
+ };
3038
+ }
3039
+ function handleFetchResult(result, startCtx) {
3040
+ return result.then(
3041
+ (response) => {
3042
+ const contentLength = response.headers.get("content-length");
3043
+ const responseSize = contentLength ? parseInt(contentLength, 10) : void 0;
3044
+ const remoteCallInfo = getTopologyInfoFromFetch(response);
3045
+ releaseHttpProfileCtx3(startCtx, {
3046
+ statusCode: response.status,
3047
+ responseSize,
3048
+ remoteCallInfo
3049
+ });
3050
+ return response;
3051
+ },
3052
+ (error) => {
3053
+ releaseHttpProfileCtx3(startCtx, {
3054
+ error: {
3055
+ message: error?.message,
3056
+ stack: error?.stack
3057
+ }
3058
+ });
3059
+ throw error;
3060
+ }
3061
+ );
3062
+ }
3063
+ function createUndiciRequestWrapper(originalRequest, HeadersCtor) {
3064
+ return function(...args) {
3065
+ const ctx = contextManager.getCurrentContext();
3066
+ if (!ctx || !ctx.enable || !configEnableHttpClientProfile3()) {
3067
+ return originalRequest(...args);
3068
+ }
3069
+ const { callArgs, method, url, headers } = normalizeUndiciRequestCall(args, HeadersCtor);
3070
+ const startCtx = createHttpProfileCtx3(method, url, headers, ctx.id);
3071
+ try {
3072
+ return originalRequest(...callArgs).then(
3073
+ (response) => {
3074
+ const responseSize = getResponseSizeFromUndiciHeaders(response?.headers);
3075
+ const remoteCallInfo = getTopologyInfoFromUndiciHeaders(response?.headers);
3076
+ releaseHttpProfileCtx3(startCtx, {
3077
+ statusCode: response?.statusCode,
3078
+ responseSize,
3079
+ remoteCallInfo
3080
+ });
3081
+ return response;
3082
+ },
3083
+ (error) => {
3084
+ releaseHttpProfileCtx3(startCtx, {
3085
+ error: {
3086
+ message: error?.message,
3087
+ stack: error?.stack
3088
+ }
3089
+ });
3090
+ throw error;
3091
+ }
3092
+ );
3093
+ } catch (error) {
3094
+ releaseHttpProfileCtx3(startCtx, {
3095
+ error: {
3096
+ message: error?.message,
3097
+ stack: error?.stack
3098
+ }
3099
+ });
3100
+ throw error;
3101
+ }
3102
+ };
3103
+ }
3104
+ function normalizeUndiciRequestCall(args, HeadersCtor) {
3105
+ const [firstArg, secondArg] = args;
3106
+ if (typeof firstArg === "string" || firstArg instanceof URL) {
3107
+ const options = secondArg && typeof secondArg === "object" ? secondArg : {};
3108
+ const requestHeaders = toHeaders(options.headers, HeadersCtor);
3109
+ setTopologyFetchHeaders(requestHeaders);
3110
+ const headersRecord = headersToRecord(requestHeaders);
3111
+ const callArgs = [
3112
+ firstArg,
3113
+ {
3114
+ ...options,
3115
+ headers: headersRecord
3116
+ }
3117
+ ];
3118
+ return {
3119
+ callArgs,
3120
+ method: options.method || "GET",
3121
+ url: typeof firstArg === "string" ? firstArg : firstArg.href,
3122
+ headers: headersRecord
3123
+ };
3124
+ }
3125
+ if (firstArg && typeof firstArg === "object") {
3126
+ const requestHeaders = toHeaders(firstArg.headers, HeadersCtor);
3127
+ setTopologyFetchHeaders(requestHeaders);
3128
+ const headersRecord = headersToRecord(requestHeaders);
3129
+ const callArg = {
3130
+ ...firstArg,
3131
+ headers: headersRecord
3132
+ };
3133
+ return {
3134
+ callArgs: [callArg],
3135
+ method: firstArg.method || "GET",
3136
+ url: getRequestUrlFromOptions(firstArg),
3137
+ headers: headersRecord
3138
+ };
3139
+ }
3140
+ return {
3141
+ callArgs: args,
3142
+ method: "GET",
3143
+ url: String(firstArg),
3144
+ headers: {}
3145
+ };
3146
+ }
3147
+ function getRequestUrlFromOptions(options) {
3148
+ if (!options || typeof options !== "object") {
3149
+ return String(options);
3150
+ }
3151
+ if (typeof options.href === "string") {
3152
+ return options.href;
3153
+ }
3154
+ if (typeof options.origin === "string" && typeof options.path === "string") {
3155
+ return `${options.origin}${options.path}`;
3156
+ }
3157
+ if (options.origin instanceof URL && typeof options.path === "string") {
3158
+ return `${options.origin.href.replace(/\/$/, "")}${options.path}`;
3159
+ }
3160
+ if (typeof options.path === "string") {
3161
+ return options.path;
3162
+ }
3163
+ return "[undici.request]";
3164
+ }
3165
+ function toHeaders(input, HeadersCtor) {
3166
+ const headers = new HeadersCtor();
3167
+ if (!input) {
3168
+ return headers;
3169
+ }
3170
+ try {
3171
+ if (input instanceof HeadersCtor) {
3172
+ input.forEach((value, key) => {
3173
+ headers.append(key, value);
3174
+ });
3175
+ return headers;
3176
+ }
3177
+ } catch {
3178
+ }
3179
+ if (Array.isArray(input)) {
3180
+ for (const entry of input) {
3181
+ if (!Array.isArray(entry) || entry.length < 2) {
3182
+ continue;
3183
+ }
3184
+ headers.append(String(entry[0]), String(entry[1]));
3185
+ }
3186
+ return headers;
3187
+ }
3188
+ if (typeof input === "object") {
3189
+ for (const [key, value] of Object.entries(input)) {
3190
+ if (value === void 0 || value === null) {
3191
+ continue;
3192
+ }
3193
+ if (Array.isArray(value)) {
3194
+ headers.set(key, value.map(String).join(", "));
3195
+ } else {
3196
+ headers.set(key, String(value));
3197
+ }
3198
+ }
3199
+ return headers;
3200
+ }
3201
+ return headers;
3202
+ }
3203
+ function headersToRecord(headers) {
3204
+ const record = {};
3205
+ headers.forEach((value, key) => {
3206
+ record[key] = value;
3207
+ });
3208
+ return record;
3209
+ }
3210
+ function getResponseSizeFromUndiciHeaders(headers) {
3211
+ const contentLength = getHeaderValue(headers, "content-length");
3212
+ if (!contentLength) {
3213
+ return void 0;
3214
+ }
3215
+ const parsed = Number(contentLength);
3216
+ return Number.isNaN(parsed) ? void 0 : parsed;
3217
+ }
3218
+ function getTopologyInfoFromUndiciHeaders(headers) {
3219
+ if (!configEnableHttpTopologyMode2()) {
3220
+ return void 0;
3221
+ }
3222
+ const topologyHeaderKey = configTopologyHttpHeaderKey2();
3223
+ const remoteCallKey = parseNumber2(getHeaderValue(headers, topologyHeaderKey));
3224
+ const sid = parseNumber2(getHeaderValue(headers, X_DOMAIN_ID2));
3225
+ const oid = parseNumber2(getHeaderValue(headers, X_AGENT_ID2));
3226
+ if ([remoteCallKey, sid, oid].some((v) => v === void 0)) {
3227
+ return void 0;
3228
+ }
3229
+ if (!isAgentId2(oid)) {
3230
+ return void 0;
3231
+ }
3232
+ return {
3233
+ remoteCallKey,
3234
+ domainId: sid,
3235
+ oid
3236
+ };
3237
+ }
3238
+ function getHeaderValue(headers, key) {
3239
+ if (!headers) {
3240
+ return void 0;
3241
+ }
3242
+ const value = headers[key.toLowerCase()] ?? headers[key];
3243
+ if (Array.isArray(value)) {
3244
+ return value[0];
3245
+ }
3246
+ return typeof value === "string" ? value : void 0;
3247
+ }
3248
+ function parseNumber2(value) {
3249
+ if (!value) {
3250
+ return void 0;
3251
+ }
3252
+ const parsed = Number(value);
3253
+ return Number.isNaN(parsed) ? void 0 : parsed;
3254
+ }
3255
+
3256
+ // src/instrumentations/register-ritm.ts
3257
+ function registerHook(definition) {
3258
+ new Hook(definition.modules, (module, moduleName) => {
3259
+ for (const patch of definition.patches) {
3260
+ patch(module, moduleName);
3261
+ }
3262
+ return module;
3263
+ });
3264
+ }
3265
+ function registerRitmHooks() {
3266
+ const hookDefinitions = [
3267
+ {
3268
+ modules: ["http", "https", "node:http", "node:https"],
3269
+ patches: [patchHttpServer, patchHttpClient]
3270
+ },
3271
+ {
3272
+ modules: ["@apollo/server"],
3273
+ patches: [patchApolloServerModule]
3274
+ },
3275
+ {
3276
+ modules: ["fs", "node:fs"],
3277
+ patches: [patchFsSync, patchFsAsync, patchFsPromise]
3278
+ },
3279
+ {
3280
+ modules: ["mariadb", "mariadb/callback.js"],
3281
+ patches: [patchMariadbModule]
3282
+ },
3283
+ {
3284
+ modules: ["mariadb/lib/cmd/query.js", "mariadb/lib/cmd/query"],
3285
+ patches: [patchMariadbQueryCommandModule]
3286
+ },
3287
+ {
3288
+ modules: ["mariadb/lib/cmd/execute.js", "mariadb/lib/cmd/execute"],
3289
+ patches: [patchMariadbExecuteCommandModule]
3290
+ },
3291
+ {
3292
+ modules: ["mysql2/promise"],
3293
+ patches: [patchMysql2PromiseModule]
3294
+ },
3295
+ {
3296
+ modules: ["mysql2"],
3297
+ patches: [patchMysql2Module]
3298
+ },
3299
+ {
3300
+ modules: ["ioredis"],
3301
+ patches: [patchIoredisModule]
3302
+ },
3303
+ {
3304
+ modules: ["redis"],
3305
+ patches: [patchRedisModule]
3306
+ },
3307
+ {
3308
+ modules: [
3309
+ "@redis/client/dist/lib/client/commands-queue.js",
3310
+ "@redis/client/dist/lib/client/commands-queue"
3311
+ ],
3312
+ patches: [patchRedisCommandsQueueModule]
3313
+ },
3314
+ {
3315
+ modules: ["oracledb"],
3316
+ patches: [patchOracleDbModule]
3317
+ },
3318
+ {
3319
+ modules: ["pg/lib/client.js", "pg/lib/client"],
3320
+ patches: [patchPgClientModule]
3321
+ },
3322
+ {
3323
+ modules: ["pg/lib/native/client.js", "pg/lib/native/client"],
3324
+ patches: [patchPgClientModule]
3325
+ },
3326
+ {
3327
+ modules: ["tedious"],
3328
+ patches: [patchTediousModule]
3329
+ },
3330
+ {
3331
+ modules: ["@prisma/client"],
3332
+ patches: [patchPrismaModule]
3333
+ },
3334
+ {
3335
+ modules: ["typeorm", "@n8n/typeorm"],
3336
+ patches: [patchTypeormModule]
3337
+ },
3338
+ {
3339
+ modules: ["undici"],
3340
+ patches: [patchUndiciModule]
3341
+ }
3342
+ ];
3343
+ for (const definition of hookDefinitions) {
3344
+ registerHook(definition);
3345
+ }
3346
+ patchGlobalFetch();
3347
+ new Hook(
3348
+ null,
3349
+ // null = intercept all modules
3350
+ { internals: true },
3351
+ // include internal/relative requires
3352
+ (exports, moduleName) => {
3353
+ if (moduleName.includes("workflow-runner")) {
3354
+ patchN8nWorkflowRunner(exports, moduleName);
3355
+ }
3356
+ if (moduleName.includes("active-executions")) {
3357
+ patchN8nActiveExecutions(exports, moduleName);
3358
+ }
3359
+ return exports;
3360
+ }
3361
+ );
3362
+ }
3363
+
3364
+ // src/instrumentations/register-iitm.ts
3365
+ import { Hook as Hook2 } from "import-in-the-middle";
3366
+ import { info as info17 } from "@jennifersoft/jennifer5-agent";
3367
+ function patchWithDefaultExport(module, patcher) {
3368
+ const defaultExport = module?.default;
3369
+ if (defaultExport && defaultExport !== module) {
3370
+ patcher(defaultExport);
3371
+ }
3372
+ patcher(module);
3373
+ }
3374
+ function registerDefaultExportHook(definition) {
3375
+ new Hook2(definition.modules, (module, moduleName) => {
3376
+ patchWithDefaultExport(module, (target) => {
3377
+ for (const patch of definition.patches) {
3378
+ patch(target, moduleName);
3379
+ }
3380
+ });
3381
+ return module;
3382
+ });
3383
+ }
3384
+ function registerIitmHooks() {
3385
+ const hookDefinitions = [
3386
+ {
3387
+ modules: ["http", "https", "node:http", "node:https"],
3388
+ patches: [patchHttpServer, patchHttpClient]
3389
+ },
3390
+ {
3391
+ modules: ["@apollo/server"],
3392
+ patches: [patchApolloServerModule]
3393
+ },
3394
+ {
3395
+ modules: ["fs", "node:fs"],
3396
+ patches: [patchFsSync, patchFsAsync, patchFsPromise]
3397
+ },
3398
+ {
3399
+ modules: ["mariadb", "mariadb/callback.js"],
3400
+ patches: [patchMariadbModule]
3401
+ },
3402
+ {
3403
+ modules: ["mariadb/lib/cmd/query.js", "mariadb/lib/cmd/query"],
3404
+ patches: [patchMariadbQueryCommandModule]
3405
+ },
3406
+ {
3407
+ modules: ["mariadb/lib/cmd/execute.js", "mariadb/lib/cmd/execute"],
3408
+ patches: [patchMariadbExecuteCommandModule]
3409
+ },
3410
+ {
3411
+ modules: ["mysql2/promise"],
3412
+ patches: [patchMysql2PromiseModule]
3413
+ },
3414
+ {
3415
+ modules: ["mysql2"],
3416
+ patches: [patchMysql2Module]
3417
+ },
3418
+ {
3419
+ modules: ["ioredis"],
3420
+ patches: [patchIoredisModule]
3421
+ },
3422
+ {
3423
+ modules: ["redis"],
3424
+ patches: [patchRedisModule]
3425
+ },
3426
+ {
3427
+ modules: [
3428
+ "@redis/client/dist/lib/client/commands-queue.js",
3429
+ "@redis/client/dist/lib/client/commands-queue"
3430
+ ],
3431
+ patches: [patchRedisCommandsQueueModule]
3432
+ },
3433
+ {
3434
+ modules: ["oracledb"],
3435
+ patches: [patchOracleDbModule]
3436
+ },
3437
+ {
3438
+ modules: ["pg/lib/client.js", "pg/lib/client"],
3439
+ patches: [patchPgClientModule]
3440
+ },
3441
+ {
3442
+ modules: ["pg/lib/native/client.js", "pg/lib/native/client"],
3443
+ patches: [patchPgClientModule]
3444
+ },
3445
+ {
3446
+ modules: ["tedious"],
3447
+ patches: [patchTediousModule]
3448
+ },
3449
+ {
3450
+ modules: ["@prisma/client"],
3451
+ patches: [patchPrismaModule]
3452
+ },
3453
+ {
3454
+ modules: ["typeorm", "@n8n/typeorm"],
3455
+ patches: [patchTypeormModule]
3456
+ },
3457
+ {
3458
+ modules: ["undici"],
3459
+ patches: [patchUndiciModule]
3460
+ }
3461
+ ];
3462
+ for (const definition of hookDefinitions) {
3463
+ registerDefaultExportHook(definition);
3464
+ }
3465
+ patchGlobalFetch();
3466
+ info17("IITM hooks registered");
3467
+ }
3468
+
3469
+ // src/feat/heap-collector.ts
3470
+ import { sendHeapMetrics, trace } from "@jennifersoft/jennifer5-agent";
3471
+ var HEAP_COLLECTOR_STARTED = /* @__PURE__ */ Symbol.for("jennifer.heap-collector.started");
3472
+ function startHeapMetricsCollection(intervalMs = 1e3, callback) {
3473
+ if (global[HEAP_COLLECTOR_STARTED]) {
3474
+ return () => {
3475
+ };
3476
+ }
3477
+ global[HEAP_COLLECTOR_STARTED] = true;
3478
+ const sendMetrics = callback || sendHeapMetrics;
3479
+ let hasErrored = false;
3480
+ const cleanup = () => {
3481
+ global[HEAP_COLLECTOR_STARTED] = false;
3482
+ clearInterval(timer);
3483
+ };
3484
+ const timer = setInterval(() => {
3485
+ if (hasErrored) {
3486
+ return;
3487
+ }
3488
+ try {
3489
+ const mem = process.memoryUsage();
3490
+ sendMetrics(mem.heapUsed, mem.heapTotal, mem.external, mem.arrayBuffers);
3491
+ } catch (error) {
3492
+ hasErrored = true;
3493
+ trace(`Failed to collect heap metrics, stopping collection: ${error}`);
3494
+ cleanup();
3495
+ }
3496
+ }, intervalMs);
3497
+ timer.unref();
3498
+ return cleanup;
3499
+ }
3500
+
3501
+ // src/feat/gc-collector.ts
3502
+ import { sendGcMetrics, trace as trace2 } from "@jennifersoft/jennifer5-agent";
3503
+ import { PerformanceObserver } from "perf_hooks";
3504
+ var GC_COLLECTOR_STARTED = /* @__PURE__ */ Symbol.for("jennifer.gc-collector.started");
3505
+ function startGcMetricsCollection(intervalMs = 1e3, callback) {
3506
+ if (global[GC_COLLECTOR_STARTED]) {
3507
+ return null;
3508
+ }
3509
+ global[GC_COLLECTOR_STARTED] = true;
3510
+ const sendMetrics = callback || ((gcCount, gcTime, gcCountDelta) => sendGcMetrics(gcCount, gcTime, gcCountDelta));
3511
+ if (typeof PerformanceObserver === "undefined") {
3512
+ trace2(
3513
+ "PerformanceObserver not available, GC metrics collection disabled (requires Node 16.7+)"
3514
+ );
3515
+ return null;
3516
+ }
3517
+ let accumulatedGcCount = 0;
3518
+ let accumulatedGcTimeMs = 0;
3519
+ let lastSentGcCount = 0;
3520
+ let hasErrored = false;
3521
+ let observer = null;
3522
+ let timer = null;
3523
+ const disableCollection = (message, error, log = true) => {
3524
+ if (!hasErrored) {
3525
+ hasErrored = true;
3526
+ if (log) {
3527
+ trace2(error ? `${message}: ${error}` : message);
3528
+ }
3529
+ }
3530
+ if (observer) {
3531
+ observer.disconnect();
3532
+ observer = null;
3533
+ }
3534
+ if (timer) {
3535
+ clearInterval(timer);
3536
+ timer = null;
3537
+ }
3538
+ };
3539
+ try {
3540
+ observer = new PerformanceObserver((list) => {
3541
+ try {
3542
+ const entries = list.getEntries();
3543
+ for (const entry of entries) {
3544
+ if (entry.entryType === "gc") {
3545
+ accumulatedGcCount++;
3546
+ accumulatedGcTimeMs += entry.duration;
3547
+ }
3548
+ }
3549
+ } catch (error) {
3550
+ disableCollection("Error processing GC entries", error);
3551
+ }
3552
+ });
3553
+ observer.observe({ entryTypes: ["gc"] });
3554
+ } catch (error) {
3555
+ disableCollection(
3556
+ "Failed to create PerformanceObserver for GC events (requires Node 16.7+)",
3557
+ error
3558
+ );
3559
+ return null;
3560
+ }
3561
+ timer = setInterval(() => {
3562
+ if (hasErrored) {
3563
+ return;
3564
+ }
3565
+ try {
3566
+ const gcCountDelta = Math.max(0, accumulatedGcCount - lastSentGcCount);
3567
+ lastSentGcCount = accumulatedGcCount;
3568
+ sendMetrics(accumulatedGcCount, Math.round(accumulatedGcTimeMs), gcCountDelta);
3569
+ } catch (error) {
3570
+ disableCollection("Failed to send GC metrics", error);
3571
+ }
3572
+ }, intervalMs);
3573
+ timer.unref();
3574
+ const cleanup = () => {
3575
+ global[GC_COLLECTOR_STARTED] = false;
3576
+ disableCollection("GC metrics collection stopped", void 0, false);
3577
+ };
3578
+ return cleanup;
3579
+ }
3580
+
3581
+ // src/helpers/nextjs/with-jennifer-route-tx.ts
3582
+ import { createTransactionCtx as createTransactionCtx3, releaseTransactionCtx as releaseTransactionCtx4 } from "@jennifersoft/jennifer5-agent";
3583
+ function toHeaderLines(headers) {
3584
+ const entries = [];
3585
+ headers.forEach((value, key) => {
3586
+ entries.push(`${key}:${value}`);
3587
+ });
3588
+ return entries;
3589
+ }
3590
+ function resolveHttpUrl(request) {
3591
+ if (request.nextUrl) {
3592
+ return `${request.nextUrl.pathname}${request.nextUrl.search}`;
3593
+ }
3594
+ const parsed = new URL(request.url);
3595
+ return `${parsed.pathname}${parsed.search}`;
3596
+ }
3597
+ function withJenniferNextRouteTx(handler) {
3598
+ return async function wrappedHandler(request) {
3599
+ const ctx = contextManager.start();
3600
+ const txId = ctx.id;
3601
+ const httpUrl = resolveHttpUrl(request);
3602
+ if (!ctx.enable) {
3603
+ return handler(request);
3604
+ }
3605
+ createTransactionCtx3({
3606
+ txId,
3607
+ method: "next.route",
3608
+ httpMethod: request.method,
3609
+ httpUrl,
3610
+ httpHeaders: toHeaderLines(request.headers)
3611
+ });
3612
+ return contextManager.run(ctx, async () => {
3613
+ try {
3614
+ const response = await handler(request);
3615
+ releaseTransactionCtx4(txId, {
3616
+ httpStatusCode: response.status
3617
+ });
3618
+ return response;
3619
+ } catch (error) {
3620
+ releaseTransactionCtx4(txId, {
3621
+ httpStatusCode: 500
3622
+ });
3623
+ throw error;
3624
+ }
3625
+ });
3626
+ };
3627
+ }
3628
+ export {
3629
+ TransactionContextManager,
3630
+ contextManager,
3631
+ registerIitmHooks,
3632
+ registerRitmHooks,
3633
+ startGcMetricsCollection,
3634
+ startHeapMetricsCollection,
3635
+ withJenniferNextRouteTx
3636
+ };