@opentelemetry/instrumentation-http 0.222.0 → 0.300.0-development.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.
Files changed (56) hide show
  1. package/README.md +0 -2
  2. package/dist/_virtual/_rolldown/runtime.mjs +5 -0
  3. package/dist/http.cjs +425 -0
  4. package/dist/http.cjs.map +1 -0
  5. package/dist/http.d.cts +61 -0
  6. package/dist/http.d.cts.map +1 -0
  7. package/dist/http.d.mts +61 -0
  8. package/dist/http.d.mts.map +1 -0
  9. package/dist/http.mjs +425 -0
  10. package/dist/http.mjs.map +1 -0
  11. package/dist/index.cjs +3 -0
  12. package/dist/index.d.cts +3 -0
  13. package/dist/index.d.mts +3 -0
  14. package/dist/index.mjs +2 -0
  15. package/dist/internal-types.cjs +32 -0
  16. package/dist/internal-types.cjs.map +1 -0
  17. package/dist/internal-types.mjs +29 -0
  18. package/dist/internal-types.mjs.map +1 -0
  19. package/dist/semconv.cjs +18 -0
  20. package/dist/semconv.cjs.map +1 -0
  21. package/dist/semconv.mjs +17 -0
  22. package/dist/semconv.mjs.map +1 -0
  23. package/dist/types.d.cts +112 -0
  24. package/dist/types.d.cts.map +1 -0
  25. package/dist/types.d.mts +112 -0
  26. package/dist/types.d.mts.map +1 -0
  27. package/dist/utils.cjs +486 -0
  28. package/dist/utils.cjs.map +1 -0
  29. package/dist/utils.mjs +471 -0
  30. package/dist/utils.mjs.map +1 -0
  31. package/dist/version.cjs +6 -0
  32. package/dist/version.cjs.map +1 -0
  33. package/dist/version.mjs +6 -0
  34. package/dist/version.mjs.map +1 -0
  35. package/package.json +35 -25
  36. package/build/src/http.d.ts +0 -61
  37. package/build/src/http.js +0 -562
  38. package/build/src/http.js.map +0 -1
  39. package/build/src/index.d.ts +0 -3
  40. package/build/src/index.js +0 -10
  41. package/build/src/index.js.map +0 -1
  42. package/build/src/internal-types.d.ts +0 -42
  43. package/build/src/internal-types.js +0 -32
  44. package/build/src/internal-types.js.map +0 -1
  45. package/build/src/semconv.d.ts +0 -17
  46. package/build/src/semconv.js +0 -29
  47. package/build/src/semconv.js.map +0 -1
  48. package/build/src/types.d.ts +0 -115
  49. package/build/src/types.js +0 -3
  50. package/build/src/types.js.map +0 -1
  51. package/build/src/utils.d.ts +0 -105
  52. package/build/src/utils.js +0 -655
  53. package/build/src/utils.js.map +0 -1
  54. package/build/src/version.d.ts +0 -2
  55. package/build/src/version.js +0 -10
  56. package/build/src/version.js.map +0 -1
@@ -1,655 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.headerCapture = exports.getIncomingStableRequestMetricAttributesOnResponse = exports.getIncomingRequestAttributesOnResponse = exports.getIncomingRequestAttributes = exports.getRemoteClientAddress = exports.getOutgoingStableRequestMetricAttributesOnResponse = exports.getOutgoingRequestAttributesOnResponse = exports.getOutgoingRequestAttributes = exports.extractHostnameAndPort = exports.isValidOptionsType = exports.getRequestInfo = exports.isCompressed = exports.setSpanWithError = exports.satisfiesPattern = exports.parseResponseStatus = exports.getAbsoluteUrl = exports.redactQueryString = void 0;
4
- const api_1 = require("@opentelemetry/api");
5
- const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
6
- const semconv_1 = require("./semconv");
7
- const core_1 = require("@opentelemetry/core");
8
- const url = require("url");
9
- const internal_types_1 = require("./internal-types");
10
- const internal_types_2 = require("./internal-types");
11
- // eslint-disable-next-line @typescript-eslint/no-require-imports
12
- const forwardedParse = require("forwarded-parse");
13
- const defaultQueryStringsToRedact = Array.from(internal_types_2.DEFAULT_QUERY_STRINGS_TO_REDACT);
14
- /**
15
- * Redacts sensitive query parameters from a query string (without leading '?').
16
- * Returns the input unchanged if it cannot be parsed.
17
- */
18
- const redactQueryString = (searchParams, paramsToRedact) => {
19
- const params = new URLSearchParams(searchParams);
20
- for (const param of paramsToRedact) {
21
- if (params.has(param)) {
22
- params.set(param, internal_types_2.STR_REDACTED);
23
- }
24
- }
25
- return params.toString();
26
- };
27
- exports.redactQueryString = redactQueryString;
28
- /**
29
- * Get an absolute url
30
- */
31
- const getAbsoluteUrl = (requestUrl, headers, fallbackProtocol = 'http:', redactedQueryParams = Array.from(internal_types_2.DEFAULT_QUERY_STRINGS_TO_REDACT)) => {
32
- const reqUrlObject = requestUrl || {};
33
- const protocol = reqUrlObject.protocol || fallbackProtocol;
34
- const port = (reqUrlObject.port || '').toString();
35
- let path = reqUrlObject.path || '/';
36
- let host = reqUrlObject.host || reqUrlObject.hostname || headers.host || 'localhost';
37
- // if there is no port in host and there is a port
38
- // it should be displayed if it's not 80 and 443 (default ports)
39
- if (host.indexOf(':') === -1 &&
40
- port &&
41
- port !== '80' &&
42
- port !== '443') {
43
- host += `:${port}`;
44
- }
45
- if (path.includes('?')) {
46
- try {
47
- const parsedUrl = new URL(path, 'http://localhost');
48
- const redacted = (0, exports.redactQueryString)(parsedUrl.searchParams, redactedQueryParams);
49
- path = `${parsedUrl.pathname}?${redacted}`;
50
- }
51
- catch {
52
- // Ignore error, as the path was not a valid URL.
53
- }
54
- }
55
- const authPart = reqUrlObject.auth ? `${internal_types_2.STR_REDACTED}:${internal_types_2.STR_REDACTED}@` : '';
56
- return `${protocol}//${authPart}${host}${path}`;
57
- };
58
- exports.getAbsoluteUrl = getAbsoluteUrl;
59
- /**
60
- * Parse status code from HTTP response. [More details](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-http.md#status)
61
- */
62
- const parseResponseStatus = (kind, statusCode) => {
63
- const upperBound = kind === api_1.SpanKind.CLIENT ? 400 : 500;
64
- // 1xx, 2xx, 3xx are OK on client and server
65
- // 4xx is OK on server
66
- if (statusCode && statusCode >= 100 && statusCode < upperBound) {
67
- return api_1.SpanStatusCode.UNSET;
68
- }
69
- // All other codes are error
70
- return api_1.SpanStatusCode.ERROR;
71
- };
72
- exports.parseResponseStatus = parseResponseStatus;
73
- /**
74
- * Check whether the given obj match pattern
75
- * @param constant e.g URL of request
76
- * @param pattern Match pattern
77
- */
78
- const satisfiesPattern = (constant, pattern) => {
79
- if (typeof pattern === 'string') {
80
- return pattern === constant;
81
- }
82
- else if (pattern instanceof RegExp) {
83
- return pattern.test(constant);
84
- }
85
- else if (typeof pattern === 'function') {
86
- return pattern(constant);
87
- }
88
- else {
89
- throw new TypeError('Pattern is in unsupported datatype');
90
- }
91
- };
92
- exports.satisfiesPattern = satisfiesPattern;
93
- /**
94
- * Sets the span with the error passed in params
95
- * @param {Span} span the span that need to be set
96
- * @param {Error} error error that will be set to span
97
- */
98
- const setSpanWithError = (span, error) => {
99
- const message = error.message;
100
- span.setAttribute(semantic_conventions_1.ATTR_ERROR_TYPE, error.name);
101
- span.setStatus({ code: api_1.SpanStatusCode.ERROR, message });
102
- span.recordException(error);
103
- };
104
- exports.setSpanWithError = setSpanWithError;
105
- const isCompressed = (headers) => {
106
- const encoding = headers['content-encoding'];
107
- return !!encoding && encoding !== 'identity';
108
- };
109
- exports.isCompressed = isCompressed;
110
- /**
111
- * Mimics Node.js conversion of URL strings to RequestOptions expected by
112
- * `http.request` and `https.request` APIs.
113
- *
114
- * See https://github.com/nodejs/node/blob/2505e217bba05fc581b572c685c5cf280a16c5a3/lib/internal/url.js#L1415-L1437
115
- *
116
- * @param stringUrl
117
- * @throws TypeError if the URL is not valid.
118
- */
119
- function stringUrlToHttpOptions(stringUrl) {
120
- // This is heavily inspired by Node.js handling of the same situation, trying
121
- // to follow it as closely as possible while keeping in mind that we only
122
- // deal with string URLs, not URL objects.
123
- const { hostname, pathname, port, username, password, search, protocol, hash, href, origin, host, } = new URL(stringUrl);
124
- const options = {
125
- protocol: protocol,
126
- hostname: hostname && hostname[0] === '[' ? hostname.slice(1, -1) : hostname,
127
- hash: hash,
128
- search: search,
129
- pathname: pathname,
130
- path: `${pathname || ''}${search || ''}`,
131
- href: href,
132
- origin: origin,
133
- host: host,
134
- };
135
- if (port !== '') {
136
- options.port = Number(port);
137
- }
138
- if (username || password) {
139
- options.auth = `${decodeURIComponent(username)}:${decodeURIComponent(password)}`;
140
- }
141
- return options;
142
- }
143
- /**
144
- * Makes sure options is an url object
145
- * return an object with default value and parsed options
146
- * @param logger component logger
147
- * @param options original options for the request
148
- * @param [extraOptions] additional options for the request
149
- */
150
- const getRequestInfo = (logger, options, extraOptions) => {
151
- let pathname;
152
- let origin;
153
- let optionsParsed;
154
- let invalidUrl = false;
155
- if (typeof options === 'string') {
156
- try {
157
- const convertedOptions = stringUrlToHttpOptions(options);
158
- optionsParsed = convertedOptions;
159
- pathname = convertedOptions.pathname || '/';
160
- }
161
- catch (e) {
162
- invalidUrl = true;
163
- logger.verbose('Unable to parse URL provided to HTTP request, using fallback to determine path. Original error:', e);
164
- // for backward compatibility with how url.parse() behaved.
165
- optionsParsed = {
166
- path: options,
167
- };
168
- pathname = optionsParsed.path || '/';
169
- }
170
- origin = `${optionsParsed.protocol || 'http:'}//${optionsParsed.host}`;
171
- if (extraOptions !== undefined) {
172
- Object.assign(optionsParsed, extraOptions);
173
- }
174
- }
175
- else if (options instanceof url.URL) {
176
- optionsParsed = {
177
- protocol: options.protocol,
178
- hostname: typeof options.hostname === 'string' && options.hostname.startsWith('[')
179
- ? options.hostname.slice(1, -1)
180
- : options.hostname,
181
- path: `${options.pathname || ''}${options.search || ''}`,
182
- };
183
- if (options.port !== '') {
184
- optionsParsed.port = Number(options.port);
185
- }
186
- if (options.username || options.password) {
187
- optionsParsed.auth = `${options.username}:${options.password}`;
188
- }
189
- pathname = options.pathname;
190
- origin = options.origin;
191
- if (extraOptions !== undefined) {
192
- Object.assign(optionsParsed, extraOptions);
193
- }
194
- }
195
- else {
196
- optionsParsed = Object.assign({ protocol: options.host ? 'http:' : undefined }, options);
197
- const hostname = optionsParsed.host ||
198
- (optionsParsed.port != null
199
- ? `${optionsParsed.hostname}${optionsParsed.port}`
200
- : optionsParsed.hostname);
201
- origin = `${optionsParsed.protocol || 'http:'}//${hostname}`;
202
- pathname = options.pathname;
203
- if (!pathname && optionsParsed.path) {
204
- try {
205
- const parsedUrl = new URL(optionsParsed.path, origin);
206
- pathname = parsedUrl.pathname || '/';
207
- }
208
- catch {
209
- pathname = '/';
210
- }
211
- }
212
- }
213
- // some packages return method in lowercase..
214
- // ensure upperCase for consistency
215
- const method = optionsParsed.method
216
- ? optionsParsed.method.toUpperCase()
217
- : 'GET';
218
- return { origin, pathname, method, optionsParsed, invalidUrl };
219
- };
220
- exports.getRequestInfo = getRequestInfo;
221
- /**
222
- * Makes sure options is of type string or object
223
- * @param options for the request
224
- */
225
- const isValidOptionsType = (options) => {
226
- if (!options) {
227
- return false;
228
- }
229
- const type = typeof options;
230
- return type === 'string' || (type === 'object' && !Array.isArray(options));
231
- };
232
- exports.isValidOptionsType = isValidOptionsType;
233
- const extractHostnameAndPort = (requestOptions) => {
234
- if (requestOptions.hostname && requestOptions.port) {
235
- return { hostname: requestOptions.hostname, port: requestOptions.port };
236
- }
237
- const matches = requestOptions.host?.match(/^([^:/ ]+)(:\d{1,5})?/) || null;
238
- const hostname = requestOptions.hostname || (matches === null ? 'localhost' : matches[1]);
239
- let port = requestOptions.port;
240
- if (!port) {
241
- if (matches && matches[2]) {
242
- // remove the leading ":". The extracted port would be something like ":8080"
243
- port = matches[2].substring(1);
244
- }
245
- else {
246
- port = requestOptions.protocol === 'https:' ? '443' : '80';
247
- }
248
- }
249
- return { hostname, port };
250
- };
251
- exports.extractHostnameAndPort = extractHostnameAndPort;
252
- /**
253
- * Returns outgoing request attributes scoped to the options passed to the request
254
- * @param {ParsedRequestOptions} requestOptions the same options used to make the request
255
- * @param {{ component: string, hostname: string, hookAttributes?: Attributes }} options used to pass data needed to create attributes
256
- */
257
- const getOutgoingRequestAttributes = (requestOptions, options, enableSyntheticSourceDetection) => {
258
- const hostname = options.hostname;
259
- const port = options.port;
260
- const method = requestOptions.method ?? 'GET';
261
- const normalizedMethod = normalizeMethod(method);
262
- const headers = (requestOptions.headers || {});
263
- const userAgent = headers['user-agent'];
264
- const urlFull = (0, exports.getAbsoluteUrl)(requestOptions, headers, `${options.component}:`, options.redactedQueryParams);
265
- const attributes = {
266
- // Required attributes
267
- [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,
268
- [semantic_conventions_1.ATTR_SERVER_ADDRESS]: hostname,
269
- [semantic_conventions_1.ATTR_SERVER_PORT]: Number(port),
270
- [semantic_conventions_1.ATTR_URL_FULL]: urlFull,
271
- [semantic_conventions_1.ATTR_USER_AGENT_ORIGINAL]: userAgent,
272
- // leaving out protocol version, it is not yet negotiated
273
- // leaving out protocol name, it is only required when protocol version is set
274
- // retries and redirects not supported
275
- // Opt-in attributes left off for now
276
- };
277
- // conditionally required if request method required case normalization
278
- if (method !== normalizedMethod) {
279
- attributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;
280
- }
281
- if (enableSyntheticSourceDetection && userAgent) {
282
- attributes[semconv_1.ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent);
283
- }
284
- return Object.assign(attributes, options.hookAttributes);
285
- };
286
- exports.getOutgoingRequestAttributes = getOutgoingRequestAttributes;
287
- /**
288
- * Returns the type of synthetic source based on the user agent
289
- * @param {OutgoingHttpHeader} userAgent the user agent string
290
- */
291
- const getSyntheticType = (userAgent) => {
292
- const userAgentString = String(userAgent).toLowerCase();
293
- for (const name of internal_types_1.SYNTHETIC_TEST_NAMES) {
294
- if (userAgentString.includes(name)) {
295
- return semconv_1.USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST;
296
- }
297
- }
298
- for (const name of internal_types_1.SYNTHETIC_BOT_NAMES) {
299
- if (userAgentString.includes(name)) {
300
- return semconv_1.USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT;
301
- }
302
- }
303
- return;
304
- };
305
- /**
306
- * Returns outgoing request attributes scoped to the response data
307
- * @param {IncomingMessage} response the response object
308
- */
309
- const getOutgoingRequestAttributesOnResponse = (response) => {
310
- const { statusCode, socket } = response;
311
- const attributes = {};
312
- if (statusCode != null) {
313
- attributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;
314
- }
315
- if (socket) {
316
- const { remoteAddress, remotePort } = socket;
317
- // Recommended
318
- attributes[semantic_conventions_1.ATTR_NETWORK_PEER_ADDRESS] = remoteAddress;
319
- attributes[semantic_conventions_1.ATTR_NETWORK_PEER_PORT] = remotePort;
320
- attributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = response.httpVersion;
321
- }
322
- return attributes;
323
- };
324
- exports.getOutgoingRequestAttributesOnResponse = getOutgoingRequestAttributesOnResponse;
325
- /**
326
- * Returns outgoing request Metric attributes scoped to the response data
327
- * @param {Attributes} spanAttributes the span attributes
328
- */
329
- const getOutgoingStableRequestMetricAttributesOnResponse = (spanAttributes) => {
330
- const metricAttributes = {};
331
- if (spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]) {
332
- metricAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] =
333
- spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION];
334
- }
335
- const statusCode = spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE];
336
- if (statusCode) {
337
- metricAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;
338
- if (typeof statusCode === 'number' &&
339
- statusCode >= 400 &&
340
- statusCode < 600) {
341
- metricAttributes[semantic_conventions_1.ATTR_ERROR_TYPE] ??= String(statusCode);
342
- }
343
- }
344
- return metricAttributes;
345
- };
346
- exports.getOutgoingStableRequestMetricAttributesOnResponse = getOutgoingStableRequestMetricAttributesOnResponse;
347
- function parseHostHeader(hostHeader, proto) {
348
- const parts = hostHeader.split(':');
349
- // no semicolon implies ipv4 dotted syntax or host name without port
350
- // x.x.x.x
351
- // example.com
352
- if (parts.length === 1) {
353
- if (proto === 'http') {
354
- return { host: parts[0], port: '80' };
355
- }
356
- if (proto === 'https') {
357
- return { host: parts[0], port: '443' };
358
- }
359
- return { host: parts[0] };
360
- }
361
- // single semicolon implies ipv4 dotted syntax or host name with port
362
- // x.x.x.x:yyyy
363
- // example.com:yyyy
364
- if (parts.length === 2) {
365
- return {
366
- host: parts[0],
367
- port: parts[1],
368
- };
369
- }
370
- // more than 2 parts implies ipv6 syntax with multiple colons
371
- // [x:x:x:x:x:x:x:x]
372
- // [x:x:x:x:x:x:x:x]:yyyy
373
- if (parts[0].startsWith('[')) {
374
- if (parts[parts.length - 1].endsWith(']')) {
375
- if (proto === 'http') {
376
- return { host: hostHeader, port: '80' };
377
- }
378
- if (proto === 'https') {
379
- return { host: hostHeader, port: '443' };
380
- }
381
- }
382
- else if (parts[parts.length - 2].endsWith(']')) {
383
- return {
384
- host: parts.slice(0, -1).join(':'),
385
- port: parts[parts.length - 1],
386
- };
387
- }
388
- }
389
- // if nothing above matches just return the host header
390
- return { host: hostHeader };
391
- }
392
- /**
393
- * Get server.address and port according to http semconv 1.27
394
- * https://github.com/open-telemetry/semantic-conventions/blob/bf0a2c1134f206f034408b201dbec37960ed60ec/docs/http/http-spans.md#setting-serveraddress-and-serverport-attributes
395
- */
396
- function getServerAddress(request, component) {
397
- const forwardedHeader = request.headers['forwarded'];
398
- if (forwardedHeader) {
399
- for (const entry of parseForwardedHeader(forwardedHeader)) {
400
- if (entry.host) {
401
- return parseHostHeader(entry.host, entry.proto);
402
- }
403
- }
404
- }
405
- const xForwardedHost = request.headers['x-forwarded-host'];
406
- if (typeof xForwardedHost === 'string') {
407
- if (typeof request.headers['x-forwarded-proto'] === 'string') {
408
- return parseHostHeader(xForwardedHost, request.headers['x-forwarded-proto']);
409
- }
410
- if (Array.isArray(request.headers['x-forwarded-proto'])) {
411
- return parseHostHeader(xForwardedHost, request.headers['x-forwarded-proto'][0]);
412
- }
413
- return parseHostHeader(xForwardedHost);
414
- }
415
- else if (Array.isArray(xForwardedHost) &&
416
- typeof xForwardedHost[0] === 'string' &&
417
- xForwardedHost[0].length > 0) {
418
- if (typeof request.headers['x-forwarded-proto'] === 'string') {
419
- return parseHostHeader(xForwardedHost[0], request.headers['x-forwarded-proto']);
420
- }
421
- if (Array.isArray(request.headers['x-forwarded-proto'])) {
422
- return parseHostHeader(xForwardedHost[0], request.headers['x-forwarded-proto'][0]);
423
- }
424
- return parseHostHeader(xForwardedHost[0]);
425
- }
426
- const host = request.headers['host'];
427
- if (typeof host === 'string' && host.length > 0) {
428
- return parseHostHeader(host, component);
429
- }
430
- return null;
431
- }
432
- /**
433
- * Get server.address and port according to http semconv 1.27
434
- * https://github.com/open-telemetry/semantic-conventions/blob/bf0a2c1134f206f034408b201dbec37960ed60ec/docs/http/http-spans.md#setting-serveraddress-and-serverport-attributes
435
- */
436
- function getRemoteClientAddress(request) {
437
- const forwardedHeader = request.headers['forwarded'];
438
- if (forwardedHeader) {
439
- for (const entry of parseForwardedHeader(forwardedHeader)) {
440
- if (entry.for) {
441
- return removePortFromAddress(entry.for);
442
- }
443
- }
444
- }
445
- const xForwardedFor = request.headers['x-forwarded-for'];
446
- if (xForwardedFor) {
447
- let xForwardedForVal;
448
- if (typeof xForwardedFor === 'string') {
449
- xForwardedForVal = xForwardedFor;
450
- }
451
- else if (Array.isArray(xForwardedFor)) {
452
- xForwardedForVal = xForwardedFor[0];
453
- }
454
- if (typeof xForwardedForVal === 'string') {
455
- xForwardedForVal = xForwardedForVal.split(',')[0].trim();
456
- return removePortFromAddress(xForwardedForVal);
457
- }
458
- }
459
- const remote = request.socket.remoteAddress;
460
- if (remote) {
461
- return remote;
462
- }
463
- return null;
464
- }
465
- exports.getRemoteClientAddress = getRemoteClientAddress;
466
- function removePortFromAddress(input) {
467
- // This function can be replaced with SocketAddress.parse() once the minimum
468
- // supported Node.js version allows it.
469
- try {
470
- const { hostname: address } = new URL(`http://${input}`);
471
- if (address.startsWith('[') && address.endsWith(']')) {
472
- return address.slice(1, -1);
473
- }
474
- return address;
475
- }
476
- catch {
477
- return input;
478
- }
479
- }
480
- function getInfoFromIncomingMessage(component, request, logger) {
481
- try {
482
- if (request.headers.host) {
483
- return new URL(request.url ?? '/', `${component}://${request.headers.host}`);
484
- }
485
- else {
486
- const unsafeParsedUrl = new URL(request.url ?? '/',
487
- // using localhost as a workaround to still use the URL constructor for parsing
488
- `${component}://localhost`);
489
- // since we use localhost as a workaround, ensure we hide the rest of the properties to avoid
490
- // our workaround leaking though.
491
- return {
492
- pathname: unsafeParsedUrl.pathname,
493
- search: unsafeParsedUrl.search,
494
- toString: function () {
495
- // we cannot use the result of unsafeParsedUrl.toString as it's potentially wrong.
496
- return unsafeParsedUrl.pathname + unsafeParsedUrl.search;
497
- },
498
- };
499
- }
500
- }
501
- catch (e) {
502
- // something is wrong, use undefined - this *should* never happen, logging
503
- // for troubleshooting in case it does happen.
504
- logger.verbose('Unable to get URL from request', e);
505
- return {};
506
- }
507
- }
508
- /**
509
- * Returns incoming request attributes scoped to the request data
510
- * @param {IncomingMessage} request the request object
511
- * @param {{ component: string, hookAttributes?: Attributes, enableSyntheticSourceDetection: boolean }} options used to pass data needed to create attributes
512
- */
513
- const getIncomingRequestAttributes = (request, options, logger) => {
514
- const { component, enableSyntheticSourceDetection, hookAttributes, redactedQueryParams, } = options;
515
- const { headers, method } = request;
516
- const { 'user-agent': userAgent } = headers;
517
- const parsedUrl = getInfoFromIncomingMessage(component, request, logger);
518
- // Stable attributes are used.
519
- const normalizedMethod = normalizeMethod(method);
520
- const serverAddress = getServerAddress(request, component);
521
- const remoteClientAddress = getRemoteClientAddress(request);
522
- const attributes = {
523
- [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,
524
- [semantic_conventions_1.ATTR_URL_SCHEME]: component,
525
- [semantic_conventions_1.ATTR_SERVER_ADDRESS]: serverAddress?.host,
526
- [semantic_conventions_1.ATTR_NETWORK_PEER_ADDRESS]: request.socket.remoteAddress,
527
- [semantic_conventions_1.ATTR_NETWORK_PEER_PORT]: request.socket.remotePort,
528
- [semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]: request.httpVersion,
529
- [semantic_conventions_1.ATTR_USER_AGENT_ORIGINAL]: userAgent,
530
- };
531
- if (parsedUrl.pathname != null) {
532
- attributes[semantic_conventions_1.ATTR_URL_PATH] = parsedUrl.pathname;
533
- }
534
- if (parsedUrl.search) {
535
- // Remove leading '?' from URL search (https://developer.mozilla.org/en-US/docs/Web/API/URL/search).
536
- const paramsToRedact = redactedQueryParams ?? defaultQueryStringsToRedact;
537
- attributes[semantic_conventions_1.ATTR_URL_QUERY] = (0, exports.redactQueryString)(new URLSearchParams(parsedUrl.search.slice(1)), paramsToRedact);
538
- }
539
- if (remoteClientAddress != null) {
540
- attributes[semantic_conventions_1.ATTR_CLIENT_ADDRESS] = remoteClientAddress;
541
- }
542
- if (serverAddress?.port != null) {
543
- attributes[semantic_conventions_1.ATTR_SERVER_PORT] = Number(serverAddress.port);
544
- }
545
- // Conditionally required if request method required case normalization.
546
- if (method !== normalizedMethod) {
547
- attributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;
548
- }
549
- if (enableSyntheticSourceDetection && userAgent) {
550
- attributes[semconv_1.ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent);
551
- }
552
- return Object.assign(attributes, hookAttributes);
553
- };
554
- exports.getIncomingRequestAttributes = getIncomingRequestAttributes;
555
- /**
556
- * Returns incoming request attributes scoped to the response data
557
- * @param {(ServerResponse & { socket: Socket; })} response the response object
558
- */
559
- const getIncomingRequestAttributesOnResponse = (response) => {
560
- const { statusCode } = response;
561
- const attributes = {
562
- [semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]: statusCode,
563
- };
564
- const rpcMetadata = (0, core_1.getRPCMetadata)(api_1.context.active());
565
- if (rpcMetadata?.type === core_1.RPCType.HTTP && rpcMetadata.route !== undefined) {
566
- attributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = rpcMetadata.route;
567
- }
568
- return attributes;
569
- };
570
- exports.getIncomingRequestAttributesOnResponse = getIncomingRequestAttributesOnResponse;
571
- /**
572
- * Returns incoming stable request Metric attributes scoped to the request data
573
- * @param {Attributes} spanAttributes the span attributes
574
- */
575
- const getIncomingStableRequestMetricAttributesOnResponse = (spanAttributes) => {
576
- const metricAttributes = {};
577
- if (spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] !== undefined) {
578
- metricAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE];
579
- }
580
- // required if and only if one was sent, same as span requirement
581
- const statusCode = spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE];
582
- if (statusCode) {
583
- metricAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;
584
- if (typeof statusCode === 'number' &&
585
- statusCode >= 500 &&
586
- statusCode < 600) {
587
- metricAttributes[semantic_conventions_1.ATTR_ERROR_TYPE] ??= String(statusCode);
588
- }
589
- }
590
- return metricAttributes;
591
- };
592
- exports.getIncomingStableRequestMetricAttributesOnResponse = getIncomingStableRequestMetricAttributesOnResponse;
593
- function headerCapture(type, headers) {
594
- const normalizedHeaders = new Map();
595
- for (let i = 0, len = headers.length; i < len; i++) {
596
- const capturedHeader = headers[i].toLowerCase();
597
- normalizedHeaders.set(capturedHeader, capturedHeader);
598
- }
599
- return (getHeader) => {
600
- const attributes = {};
601
- for (const capturedHeader of normalizedHeaders.keys()) {
602
- const value = getHeader(capturedHeader);
603
- if (value === undefined) {
604
- continue;
605
- }
606
- const normalizedHeader = normalizedHeaders.get(capturedHeader);
607
- const key = `http.${type}.header.${normalizedHeader}`;
608
- if (typeof value === 'string') {
609
- attributes[key] = [value];
610
- }
611
- else if (Array.isArray(value)) {
612
- attributes[key] = value;
613
- }
614
- else {
615
- attributes[key] = [value];
616
- }
617
- }
618
- return attributes;
619
- };
620
- }
621
- exports.headerCapture = headerCapture;
622
- const KNOWN_METHODS = new Set([
623
- // methods from https://www.rfc-editor.org/rfc/rfc9110.html#name-methods
624
- 'GET',
625
- 'HEAD',
626
- 'POST',
627
- 'PUT',
628
- 'DELETE',
629
- 'CONNECT',
630
- 'OPTIONS',
631
- 'TRACE',
632
- // PATCH from https://www.rfc-editor.org/rfc/rfc5789.html
633
- 'PATCH',
634
- // QUERY from https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/
635
- 'QUERY',
636
- ]);
637
- function normalizeMethod(method) {
638
- if (method == null) {
639
- return 'GET';
640
- }
641
- const upper = method.toUpperCase();
642
- if (KNOWN_METHODS.has(upper)) {
643
- return upper;
644
- }
645
- return '_OTHER';
646
- }
647
- function parseForwardedHeader(header) {
648
- try {
649
- return forwardedParse(header);
650
- }
651
- catch {
652
- return [];
653
- }
654
- }
655
- //# sourceMappingURL=utils.js.map