@geekmidas/telescope 10.0.0-alpha.15 → 10.0.0-alpha.151

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 (132) hide show
  1. package/README.md +14 -14
  2. package/dist/{MetricsAggregator-BxBLQUPj.d.cts → MetricsAggregator-BJdIvfEv.d.mts} +2 -2
  3. package/dist/MetricsAggregator-BJdIvfEv.d.mts.map +1 -0
  4. package/dist/{MetricsAggregator-j9wmZ0K_.d.mts → MetricsAggregator-CnC3oT5q.d.cts} +2 -2
  5. package/dist/MetricsAggregator-CnC3oT5q.d.cts.map +1 -0
  6. package/dist/{Telescope-BcrWTaar.d.mts → Telescope-BVfDvVvY.d.mts} +3 -3
  7. package/dist/{Telescope-BcrWTaar.d.mts.map → Telescope-BVfDvVvY.d.mts.map} +1 -1
  8. package/dist/{Telescope-DnCMZT7V.d.cts → Telescope-DeqSHfuB.d.cts} +3 -3
  9. package/dist/{Telescope-DnCMZT7V.d.cts.map → Telescope-DeqSHfuB.d.cts.map} +1 -1
  10. package/dist/Telescope.d.cts +1 -1
  11. package/dist/Telescope.d.mts +1 -1
  12. package/dist/adapters/lambda.d.cts +1 -1
  13. package/dist/adapters/lambda.d.cts.map +1 -1
  14. package/dist/adapters/lambda.d.mts +1 -1
  15. package/dist/adapters/lambda.d.mts.map +1 -1
  16. package/dist/adapters/middy.d.cts +1 -1
  17. package/dist/adapters/middy.d.mts +1 -1
  18. package/dist/index.d.cts +3 -3
  19. package/dist/index.d.mts +3 -3
  20. package/dist/instrumentation/hono.cjs +47 -7
  21. package/dist/instrumentation/hono.cjs.map +1 -1
  22. package/dist/instrumentation/hono.d.cts +19 -0
  23. package/dist/instrumentation/hono.d.cts.map +1 -1
  24. package/dist/instrumentation/hono.d.mts +19 -0
  25. package/dist/instrumentation/hono.d.mts.map +1 -1
  26. package/dist/instrumentation/hono.mjs +48 -8
  27. package/dist/instrumentation/hono.mjs.map +1 -1
  28. package/dist/instrumentation/http.cjs +29 -4
  29. package/dist/instrumentation/http.cjs.map +1 -1
  30. package/dist/instrumentation/http.d.cts +18 -2
  31. package/dist/instrumentation/http.d.cts.map +1 -1
  32. package/dist/instrumentation/http.d.mts +18 -2
  33. package/dist/instrumentation/http.d.mts.map +1 -1
  34. package/dist/instrumentation/http.mjs +30 -6
  35. package/dist/instrumentation/http.mjs.map +1 -1
  36. package/dist/instrumentation/index.cjs +9 -0
  37. package/dist/instrumentation/index.d.cts +5 -3
  38. package/dist/instrumentation/index.d.mts +5 -3
  39. package/dist/instrumentation/index.mjs +5 -3
  40. package/dist/instrumentation/middleware.cjs +4 -2
  41. package/dist/instrumentation/middleware.cjs.map +1 -1
  42. package/dist/instrumentation/middleware.d.cts +13 -0
  43. package/dist/instrumentation/middleware.d.cts.map +1 -1
  44. package/dist/instrumentation/middleware.d.mts +13 -0
  45. package/dist/instrumentation/middleware.d.mts.map +1 -1
  46. package/dist/instrumentation/middleware.mjs +5 -3
  47. package/dist/instrumentation/middleware.mjs.map +1 -1
  48. package/dist/instrumentation/otel.d.cts.map +1 -1
  49. package/dist/instrumentation/otel.d.mts.map +1 -1
  50. package/dist/instrumentation/sampler.cjs +54 -0
  51. package/dist/instrumentation/sampler.cjs.map +1 -0
  52. package/dist/instrumentation/sampler.d.cts +38 -0
  53. package/dist/instrumentation/sampler.d.cts.map +1 -0
  54. package/dist/instrumentation/sampler.d.mts +38 -0
  55. package/dist/instrumentation/sampler.d.mts.map +1 -0
  56. package/dist/instrumentation/sampler.mjs +52 -0
  57. package/dist/instrumentation/sampler.mjs.map +1 -0
  58. package/dist/instrumentation/setup.cjs +63 -21
  59. package/dist/instrumentation/setup.cjs.map +1 -1
  60. package/dist/instrumentation/setup.d.cts +59 -3
  61. package/dist/instrumentation/setup.d.cts.map +1 -1
  62. package/dist/instrumentation/setup.d.mts +59 -3
  63. package/dist/instrumentation/setup.d.mts.map +1 -1
  64. package/dist/instrumentation/setup.mjs +64 -23
  65. package/dist/instrumentation/setup.mjs.map +1 -1
  66. package/dist/instrumentation/trust.cjs +116 -0
  67. package/dist/instrumentation/trust.cjs.map +1 -0
  68. package/dist/instrumentation/trust.d.cts +59 -0
  69. package/dist/instrumentation/trust.d.cts.map +1 -0
  70. package/dist/instrumentation/trust.d.mts +59 -0
  71. package/dist/instrumentation/trust.d.mts.map +1 -0
  72. package/dist/instrumentation/trust.mjs +113 -0
  73. package/dist/instrumentation/trust.mjs.map +1 -0
  74. package/dist/logger/console.d.cts +1 -1
  75. package/dist/logger/console.d.cts.map +1 -1
  76. package/dist/logger/console.d.mts +1 -1
  77. package/dist/logger/console.d.mts.map +1 -1
  78. package/dist/logger/pino.d.cts +1 -1
  79. package/dist/logger/pino.d.mts +1 -1
  80. package/dist/metrics/MetricsAggregator.d.cts +1 -1
  81. package/dist/metrics/MetricsAggregator.d.mts +1 -1
  82. package/dist/metrics/index.d.cts +1 -1
  83. package/dist/metrics/index.d.mts +1 -1
  84. package/dist/metrics/storage/InMemoryMetricsStorage.d.cts.map +1 -1
  85. package/dist/metrics/storage/InMemoryMetricsStorage.d.mts.map +1 -1
  86. package/dist/otlp/index.d.cts +1 -1
  87. package/dist/otlp/index.d.mts +1 -1
  88. package/dist/otlp/receiver.d.cts +2 -2
  89. package/dist/otlp/receiver.d.cts.map +1 -1
  90. package/dist/otlp/receiver.d.mts +2 -2
  91. package/dist/otlp/receiver.d.mts.map +1 -1
  92. package/dist/otlp/transformer.d.cts +1 -1
  93. package/dist/otlp/transformer.d.mts +1 -1
  94. package/dist/redact.d.cts +1 -1
  95. package/dist/redact.d.mts +1 -1
  96. package/dist/server/hono.cjs +11 -23
  97. package/dist/server/hono.cjs.map +1 -1
  98. package/dist/server/hono.d.cts +11 -3
  99. package/dist/server/hono.d.cts.map +1 -1
  100. package/dist/server/hono.d.mts +11 -3
  101. package/dist/server/hono.d.mts.map +1 -1
  102. package/dist/server/hono.mjs +11 -23
  103. package/dist/server/hono.mjs.map +1 -1
  104. package/dist/storage/kysely.d.cts +1 -1
  105. package/dist/storage/kysely.d.cts.map +1 -1
  106. package/dist/storage/kysely.d.mts +1 -1
  107. package/dist/storage/kysely.d.mts.map +1 -1
  108. package/dist/storage/memory.d.cts +1 -1
  109. package/dist/storage/memory.d.cts.map +1 -1
  110. package/dist/storage/memory.d.mts +1 -1
  111. package/dist/storage/memory.d.mts.map +1 -1
  112. package/dist/{transformer-DlESim6Q.d.cts → transformer-BtqjAs0b.d.cts} +2 -2
  113. package/dist/{transformer-BBBXCjHP.d.mts.map → transformer-BtqjAs0b.d.cts.map} +1 -1
  114. package/dist/{transformer-BBBXCjHP.d.mts → transformer-DI6t8-YA.d.mts} +2 -2
  115. package/dist/{transformer-DlESim6Q.d.cts.map → transformer-DI6t8-YA.d.mts.map} +1 -1
  116. package/dist/{types-a9Vistj1.d.cts → types-BVujq4zd.d.cts} +2 -2
  117. package/dist/{types-a9Vistj1.d.cts.map → types-BVujq4zd.d.cts.map} +1 -1
  118. package/dist/{types-a9Vistj1.d.mts → types-BVujq4zd.d.mts} +2 -2
  119. package/dist/{types-a9Vistj1.d.mts.map → types-BVujq4zd.d.mts.map} +1 -1
  120. package/dist/types.d.cts +1 -1
  121. package/dist/types.d.mts +1 -1
  122. package/package.json +7 -5
  123. package/dist/MetricsAggregator-BxBLQUPj.d.cts.map +0 -1
  124. package/dist/MetricsAggregator-j9wmZ0K_.d.mts.map +0 -1
  125. package/dist/ui-assets.cjs +0 -32
  126. package/dist/ui-assets.cjs.map +0 -1
  127. package/dist/ui-assets.d.cts +0 -11
  128. package/dist/ui-assets.d.cts.map +0 -1
  129. package/dist/ui-assets.d.mts +0 -11
  130. package/dist/ui-assets.d.mts.map +0 -1
  131. package/dist/ui-assets.mjs +0 -29
  132. package/dist/ui-assets.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"hono.mjs","names":[],"sources":["../../src/instrumentation/hono.ts"],"sourcesContent":["import { context, type Span, trace } from '@opentelemetry/api';\n/**\n * OpenTelemetry instrumentation middleware for Hono\n *\n * This middleware automatically creates spans for HTTP requests,\n * extracts trace context from incoming headers, and records\n * request/response metadata as span attributes.\n */\nimport type { Context, MiddlewareHandler } from 'hono';\nimport {\n\tcreateHttpServerSpan,\n\tendHttpSpan,\n\textractTraceContext,\n\ttype HttpSpanAttributes,\n} from './http';\n\n/**\n * Options for the Hono telemetry middleware\n */\nexport interface HonoTelemetryMiddlewareOptions {\n\t/**\n\t * Whether to record request body as span attribute\n\t * @default false\n\t */\n\trecordBody?: boolean;\n\n\t/**\n\t * Whether to record response body as span attribute\n\t * @default false\n\t */\n\trecordResponseBody?: boolean;\n\n\t/**\n\t * Custom function to extract user ID from context\n\t */\n\tgetUserId?: (c: Context) => string | undefined;\n\n\t/**\n\t * Paths to skip tracing (supports wildcards)\n\t */\n\tignorePaths?: string[];\n\n\t/**\n\t * Whether to skip tracing for this request\n\t */\n\tshouldSkip?: (c: Context) => boolean;\n}\n\n// Key for storing span on context\nconst SPAN_KEY = 'telemetry.span';\nconst CONTEXT_KEY = 'telemetry.context';\n\n/**\n * Get the current span from Hono context\n */\nexport function getSpanFromContext(c: Context): Span | undefined {\n\treturn c.get(SPAN_KEY);\n}\n\n/**\n * Get the current trace context from Hono context\n */\nexport function getTraceContextFromHono(c: Context): any {\n\treturn c.get(CONTEXT_KEY);\n}\n\n/**\n * Create a telemetry middleware for Hono applications\n *\n * @example\n * ```typescript\n * import { honoTelemetryMiddleware } from '@geekmidas/telescope/instrumentation';\n *\n * const app = new Hono();\n * app.use('*', honoTelemetryMiddleware());\n * ```\n */\nexport function honoTelemetryMiddleware(\n\toptions: HonoTelemetryMiddlewareOptions = {},\n): MiddlewareHandler {\n\treturn async (c, next) => {\n\t\t// Check if path should be ignored\n\t\tif (\n\t\t\toptions.ignorePaths &&\n\t\t\tshouldIgnorePath(c.req.path, options.ignorePaths)\n\t\t) {\n\t\t\treturn next();\n\t\t}\n\n\t\t// Skip if custom skip function returns true\n\t\tif (options.shouldSkip?.(c)) {\n\t\t\treturn next();\n\t\t}\n\n\t\t// Extract trace context from headers\n\t\tconst headers: Record<string, string | string[] | undefined> = {};\n\t\tc.req.raw.headers.forEach((value, key) => {\n\t\t\theaders[key] = value;\n\t\t});\n\t\tconst parentContext = extractTraceContext(headers);\n\n\t\t// Build span attributes from request\n\t\tconst attrs = buildHonoSpanAttributes(c, options);\n\n\t\t// Create the span\n\t\tconst span = createHttpServerSpan(attrs, parentContext);\n\t\tconst spanContext = trace.setSpan(parentContext, span);\n\n\t\t// Store span and context on Hono context\n\t\tc.set(SPAN_KEY, span);\n\t\tc.set(CONTEXT_KEY, spanContext);\n\n\t\t// Record body if requested\n\t\tif (options.recordBody) {\n\t\t\ttry {\n\t\t\t\tconst body = await c.req.text();\n\t\t\t\tif (body) {\n\t\t\t\t\tspan.setAttribute(\n\t\t\t\t\t\t'http.request.body',\n\t\t\t\t\t\tbody.length > 4096 ? `${body.slice(0, 4096)}...` : body,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Body may have already been consumed\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// Execute the rest of the middleware chain within span context\n\t\t\tawait context.with(spanContext, async () => {\n\t\t\t\tawait next();\n\t\t\t});\n\n\t\t\t// Record response\n\t\t\tconst statusCode = c.res.status;\n\n\t\t\tif (options.recordResponseBody) {\n\t\t\t\ttry {\n\t\t\t\t\tconst body = await c.res.clone().text();\n\t\t\t\t\tif (body) {\n\t\t\t\t\t\tspan.setAttribute(\n\t\t\t\t\t\t\t'http.response.body',\n\t\t\t\t\t\t\tbody.length > 4096 ? `${body.slice(0, 4096)}...` : body,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Response body may not be available\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tendHttpSpan(span, { statusCode });\n\t\t} catch (error) {\n\t\t\tendHttpSpan(\n\t\t\t\tspan,\n\t\t\t\t{ statusCode: 500 },\n\t\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\t};\n}\n\n/**\n * Build span attributes from Hono context\n */\nfunction buildHonoSpanAttributes(\n\tc: Context,\n\toptions: HonoTelemetryMiddlewareOptions,\n): HttpSpanAttributes {\n\tconst req = c.req;\n\tconst url = new URL(req.url);\n\n\t// Use actual path for route unless it's a specific route pattern\n\tconst routePath = c.req.routePath;\n\tconst route =\n\t\troutePath && routePath !== '*' && !routePath.includes('/*')\n\t\t\t? routePath\n\t\t\t: url.pathname;\n\n\tconst attrs: HttpSpanAttributes = {\n\t\tmethod: req.method,\n\t\turl: req.url,\n\t\tpath: url.pathname,\n\t\troute,\n\t\thost: url.host,\n\t\tscheme: url.protocol.replace(':', '') as 'http' | 'https',\n\t\tuserAgent: req.header('user-agent'),\n\t\tclientIp: getClientIp(c),\n\t\trequestId: req.header('x-request-id') || req.header('x-amzn-requestid'),\n\t};\n\n\t// Add user metadata if extractor provided\n\tif (options.getUserId) {\n\t\tconst userId = options.getUserId(c);\n\t\tif (userId) {\n\t\t\tattrs.user = { userId };\n\t\t}\n\t}\n\n\treturn attrs;\n}\n\n/**\n * Extract client IP from Hono context\n */\nfunction getClientIp(c: Context): string | undefined {\n\t// Try various headers in order of preference\n\tconst xForwardedFor = c.req.header('x-forwarded-for');\n\tif (xForwardedFor) {\n\t\tconst first = xForwardedFor.split(',')[0];\n\t\treturn first?.trim();\n\t}\n\n\tconst xRealIp = c.req.header('x-real-ip');\n\tif (xRealIp) {\n\t\treturn xRealIp;\n\t}\n\n\t// Try CF-Connecting-IP (Cloudflare)\n\tconst cfConnectingIp = c.req.header('cf-connecting-ip');\n\tif (cfConnectingIp) {\n\t\treturn cfConnectingIp;\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Check if path should be ignored\n */\nfunction shouldIgnorePath(path: string, ignorePaths: string[]): boolean {\n\tfor (const pattern of ignorePaths) {\n\t\tif (pattern.endsWith('*')) {\n\t\t\t// Wildcard match\n\t\t\tconst prefix = pattern.slice(0, -1);\n\t\t\tif (path.startsWith(prefix)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} else if (path === pattern) {\n\t\t\t// Exact match\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n/**\n * Run a function within the span context from Hono context\n *\n * @example\n * ```typescript\n * app.get('/api/users', async (c) => {\n * return withHonoSpanContext(c, async () => {\n * // Any spans created here will be children of the request span\n * const users = await fetchUsers();\n * return c.json(users);\n * });\n * });\n * ```\n */\nexport async function withHonoSpanContext<T>(\n\tc: Context,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tconst ctx = getTraceContextFromHono(c);\n\tif (!ctx) {\n\t\treturn fn();\n\t}\n\treturn context.with(ctx, fn);\n}\n"],"mappings":";;;AAiDA,MAAM,WAAW;AACjB,MAAM,cAAc;;;;AAKpB,SAAgB,mBAAmB,GAA8B;CAChE,OAAO,EAAE,IAAI,QAAQ;AACtB;;;;AAKA,SAAgB,wBAAwB,GAAiB;CACxD,OAAO,EAAE,IAAI,WAAW;AACzB;;;;;;;;;;;;AAaA,SAAgB,wBACf,UAA0C,CAAC,GACvB;CACpB,OAAO,OAAO,GAAG,SAAS;EAEzB,IACC,QAAQ,eACR,iBAAiB,EAAE,IAAI,MAAM,QAAQ,WAAW,GAEhD,OAAO,KAAK;EAIb,IAAI,QAAQ,aAAa,CAAC,GACzB,OAAO,KAAK;EAIb,MAAM,UAAyD,CAAC;EAChE,EAAE,IAAI,IAAI,QAAQ,SAAS,OAAO,QAAQ;GACzC,QAAQ,OAAO;EAChB,CAAC;EACD,MAAM,gBAAgB,oBAAoB,OAAO;EAGjD,MAAM,QAAQ,wBAAwB,GAAG,OAAO;EAGhD,MAAM,OAAO,qBAAqB,OAAO,aAAa;EACtD,MAAM,cAAc,MAAM,QAAQ,eAAe,IAAI;EAGrD,EAAE,IAAI,UAAU,IAAI;EACpB,EAAE,IAAI,aAAa,WAAW;EAG9B,IAAI,QAAQ,YACX,IAAI;GACH,MAAM,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;;;;AAKA,SAAS,YAAY,GAAgC;CAEpD,MAAM,gBAAgB,EAAE,IAAI,OAAO,iBAAiB;CACpD,IAAI,eAEH,OADc,cAAc,MAAM,GAAG,CAAC,CAAC,EAC3B,EAAE,KAAK;CAGpB,MAAM,UAAU,EAAE,IAAI,OAAO,WAAW;CACxC,IAAI,SACH,OAAO;CAIR,MAAM,iBAAiB,EAAE,IAAI,OAAO,kBAAkB;CACtD,IAAI,gBACH,OAAO;AAIT;;;;AAKA,SAAS,iBAAiB,MAAc,aAAgC;CACvE,KAAK,MAAM,WAAW,aACrB,IAAI,QAAQ,SAAS,GAAG,GAAG;EAE1B,MAAM,SAAS,QAAQ,MAAM,GAAG,EAAE;EAClC,IAAI,KAAK,WAAW,MAAM,GACzB,OAAO;CAET,OAAO,IAAI,SAAS,SAEnB,OAAO;CAGT,OAAO;AACR;;;;;;;;;;;;;;;AAgBA,eAAsB,oBACrB,GACA,IACa;CACb,MAAM,MAAM,wBAAwB,CAAC;CACrC,IAAI,CAAC,KACJ,OAAO,GAAG;CAEX,OAAO,QAAQ,KAAK,KAAK,EAAE;AAC5B"}
1
+ {"version":3,"file":"hono.mjs","names":[],"sources":["../../src/instrumentation/hono.ts"],"sourcesContent":["import { context, type Span, trace } from '@opentelemetry/api';\n/**\n * OpenTelemetry instrumentation middleware for Hono\n *\n * This middleware automatically creates spans for HTTP requests,\n * extracts trace context from incoming headers, and records\n * request/response metadata as span attributes.\n */\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { routePath } from 'hono/route';\nimport {\n\tcreateHttpServerSpan,\n\tendHttpSpan,\n\ttype HttpSpanAttributes,\n\tincomingTraceContext,\n} from './http';\nimport { isInternalCaller, isTrustedOrigin } from './trust';\n\n/**\n * Options for the Hono telemetry middleware\n */\nexport interface HonoTelemetryMiddlewareOptions {\n\t/**\n\t * Whether to record request body as span attribute\n\t * @default false\n\t */\n\trecordBody?: boolean;\n\n\t/**\n\t * Whether to record response body as span attribute\n\t * @default false\n\t */\n\trecordResponseBody?: boolean;\n\n\t/**\n\t * Custom function to extract user ID from context\n\t */\n\tgetUserId?: (c: Context) => string | undefined;\n\n\t/**\n\t * Paths to skip tracing (supports wildcards)\n\t */\n\tignorePaths?: string[];\n\n\t/**\n\t * Whether to skip tracing for this request\n\t */\n\tshouldSkip?: (c: Context) => boolean;\n\n\t/**\n\t * The origins whose `traceparent` is continued: the API's own sites, the\n\t * same list its CORS allows. A request from any other origin starts a new\n\t * trace linked to the one it claimed.\n\t *\n\t * A function is read on each request, for a server that learns its origins\n\t * only once the app has loaded its configuration.\n\t */\n\ttrustedOrigins?: readonly string[] | (() => readonly string[] | undefined);\n\n\t/**\n\t * Whether a request with no `Origin` from an internal caller continues its\n\t * `traceparent` — another service on the private network (see `./trust`):\n\t * no `Origin`, no proxy's forwarding header, and a loopback or private\n\t * peer address, read from `@hono/node-server`'s socket.\n\t *\n\t * `false` trusts no caller without an origin; a function decides itself.\n\t * @default true\n\t */\n\tinternalCallers?: boolean | ((c: Context) => boolean);\n}\n\n// Key for storing span on context\nconst SPAN_KEY = 'telemetry.span';\nconst CONTEXT_KEY = 'telemetry.context';\n\n/**\n * Get the current span from Hono context\n */\nexport function getSpanFromContext(c: Context): Span | undefined {\n\treturn c.get(SPAN_KEY);\n}\n\n/**\n * Get the current trace context from Hono context\n */\nexport function getTraceContextFromHono(c: Context): any {\n\treturn c.get(CONTEXT_KEY);\n}\n\n/**\n * Create a telemetry middleware for Hono applications\n *\n * @example\n * ```typescript\n * import { honoTelemetryMiddleware } from '@geekmidas/telescope/instrumentation';\n *\n * const app = new Hono();\n * app.use('*', honoTelemetryMiddleware());\n * ```\n */\nexport function honoTelemetryMiddleware(\n\toptions: HonoTelemetryMiddlewareOptions = {},\n): MiddlewareHandler {\n\treturn async (c, next) => {\n\t\t// Check if path should be ignored\n\t\tif (\n\t\t\toptions.ignorePaths &&\n\t\t\tshouldIgnorePath(c.req.path, options.ignorePaths)\n\t\t) {\n\t\t\treturn next();\n\t\t}\n\n\t\t// Skip if custom skip function returns true\n\t\tif (options.shouldSkip?.(c)) {\n\t\t\treturn next();\n\t\t}\n\n\t\t// Extract trace context from headers\n\t\tconst headers: Record<string, string | string[] | undefined> = {};\n\t\tc.req.raw.headers.forEach((value, key) => {\n\t\t\theaders[key] = value;\n\t\t});\n\t\t// Continued only from a trusted caller; anyone else gets a new trace\n\t\t// that links to the one they claimed.\n\t\tconst { parent: parentContext, links } = incomingTraceContext(\n\t\t\theaders,\n\t\t\tisTrustedCaller(c, options),\n\t\t);\n\n\t\t// Build span attributes from request\n\t\tconst attrs = buildHonoSpanAttributes(c, options);\n\n\t\t// Create the span\n\t\tconst span = createHttpServerSpan(attrs, parentContext, links);\n\t\tconst spanContext = trace.setSpan(parentContext, span);\n\n\t\t// Store span and context on Hono context\n\t\tc.set(SPAN_KEY, span);\n\t\tc.set(CONTEXT_KEY, spanContext);\n\n\t\t// Record body if requested\n\t\tif (options.recordBody) {\n\t\t\ttry {\n\t\t\t\tconst body = await c.req.text();\n\t\t\t\tif (body) {\n\t\t\t\t\tspan.setAttribute(\n\t\t\t\t\t\t'http.request.body',\n\t\t\t\t\t\tbody.length > 4096 ? `${body.slice(0, 4096)}...` : body,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Body may have already been consumed\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// Execute the rest of the middleware chain within span context, so\n\t\t\t// the handler's logs and outbound spans nest under this one.\n\t\t\tawait context.with(spanContext, async () => {\n\t\t\t\tawait next();\n\t\t\t});\n\n\t\t\tnameAfterRoute(c, span);\n\n\t\t\t// Record response\n\t\t\tconst statusCode = c.res.status;\n\n\t\t\tif (options.recordResponseBody) {\n\t\t\t\ttry {\n\t\t\t\t\tconst body = await c.res.clone().text();\n\t\t\t\t\tif (body) {\n\t\t\t\t\t\tspan.setAttribute(\n\t\t\t\t\t\t\t'http.response.body',\n\t\t\t\t\t\t\tbody.length > 4096 ? `${body.slice(0, 4096)}...` : body,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Response body may not be available\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Hono hands a thrown error to `onError` and sets `c.error`\n\t\t\t// rather than rethrowing, so that is where it is found.\n\t\t\tendHttpSpan(span, { statusCode }, c.error);\n\t\t} catch (error) {\n\t\t\tnameAfterRoute(c, span);\n\t\t\tendHttpSpan(\n\t\t\t\tspan,\n\t\t\t\t{ statusCode: 500 },\n\t\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\t};\n}\n\n/**\n * Whether this request's `traceparent` is continued: from one of the API's\n * own origins, or from an internal caller.\n */\nfunction isTrustedCaller(\n\tc: Context,\n\toptions: HonoTelemetryMiddlewareOptions,\n): boolean {\n\tconst origin = c.req.header('origin');\n\tif (origin) {\n\t\tconst trusted =\n\t\t\ttypeof options.trustedOrigins === 'function'\n\t\t\t\t? options.trustedOrigins()\n\t\t\t\t: options.trustedOrigins;\n\t\treturn isTrustedOrigin(origin, trusted);\n\t}\n\n\tconst internal = options.internalCallers ?? true;\n\tif (typeof internal === 'function') return internal(c);\n\tif (!internal) return false;\n\treturn isInternalCaller({\n\t\theaders: c.req.raw.headers,\n\t\tremoteAddress: remoteAddressOf(c),\n\t});\n}\n\n/** The TCP peer's address under `@hono/node-server`, or undefined. */\nfunction remoteAddressOf(c: Context): string | undefined {\n\tconst env = c.env as\n\t\t| { incoming?: { socket?: { remoteAddress?: string } } }\n\t\t| undefined;\n\treturn env?.incoming?.socket?.remoteAddress;\n}\n\n/**\n * The route the request matched, once the handler has run — `/users/:id`,\n * never `/users/42` — or undefined when only middleware ran (a 404).\n *\n * Read after `next()`: before it, the route is this middleware's own `*`.\n */\nfunction matchedRoute(c: Context): string | undefined {\n\tconst path = routePath(c);\n\treturn path && !path.includes('*') ? path : undefined;\n}\n\n/** `GET /users/:id`, or the bare method when no route matched. */\nfunction nameAfterRoute(c: Context, span: Span): void {\n\tconst route = matchedRoute(c);\n\tif (route) {\n\t\tspan.setAttribute('http.route', route);\n\t\tspan.updateName(`${c.req.method} ${route}`);\n\t} else {\n\t\tspan.updateName(c.req.method);\n\t}\n}\n\n/**\n * Build span attributes from Hono context\n */\nfunction buildHonoSpanAttributes(\n\tc: Context,\n\toptions: HonoTelemetryMiddlewareOptions,\n): HttpSpanAttributes {\n\tconst req = c.req;\n\tconst url = new URL(req.url);\n\n\t// No `url.full`: a query string can carry a token, and the span would\n\t// keep it. The route is named once the handler has run.\n\tconst attrs: HttpSpanAttributes = {\n\t\tmethod: req.method,\n\t\tpath: url.pathname,\n\t\thost: url.host,\n\t\tscheme: url.protocol.replace(':', '') as 'http' | 'https',\n\t\tuserAgent: req.header('user-agent'),\n\t\tclientIp: getClientIp(c),\n\t\trequestId: req.header('x-request-id') || req.header('x-amzn-requestid'),\n\t};\n\n\t// Add user metadata if extractor provided\n\tif (options.getUserId) {\n\t\tconst userId = options.getUserId(c);\n\t\tif (userId) {\n\t\t\tattrs.user = { userId };\n\t\t}\n\t}\n\n\treturn attrs;\n}\n\n/**\n * Extract client IP from Hono context\n */\nfunction getClientIp(c: Context): string | undefined {\n\t// Try various headers in order of preference\n\tconst xForwardedFor = c.req.header('x-forwarded-for');\n\tif (xForwardedFor) {\n\t\tconst first = xForwardedFor.split(',')[0];\n\t\treturn first?.trim();\n\t}\n\n\tconst xRealIp = c.req.header('x-real-ip');\n\tif (xRealIp) {\n\t\treturn xRealIp;\n\t}\n\n\t// Try CF-Connecting-IP (Cloudflare)\n\tconst cfConnectingIp = c.req.header('cf-connecting-ip');\n\tif (cfConnectingIp) {\n\t\treturn cfConnectingIp;\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Check if path should be ignored\n */\nfunction shouldIgnorePath(path: string, ignorePaths: string[]): boolean {\n\tfor (const pattern of ignorePaths) {\n\t\tif (pattern.endsWith('*')) {\n\t\t\t// Wildcard match\n\t\t\tconst prefix = pattern.slice(0, -1);\n\t\t\tif (path.startsWith(prefix)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} else if (path === pattern) {\n\t\t\t// Exact match\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n/**\n * Run a function within the span context from Hono context\n *\n * @example\n * ```typescript\n * app.get('/api/users', async (c) => {\n * return withHonoSpanContext(c, async () => {\n * // Any spans created here will be children of the request span\n * const users = await fetchUsers();\n * return c.json(users);\n * });\n * });\n * ```\n */\nexport async function withHonoSpanContext<T>(\n\tc: Context,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tconst ctx = getTraceContextFromHono(c);\n\tif (!ctx) {\n\t\treturn fn();\n\t}\n\treturn context.with(ctx, fn);\n}\n"],"mappings":";;;;;AAwEA,MAAM,WAAW;AACjB,MAAM,cAAc;;;;AAKpB,SAAgB,mBAAmB,GAA8B;CAChE,OAAO,EAAE,IAAI,QAAQ;AACtB;;;;AAKA,SAAgB,wBAAwB,GAAiB;CACxD,OAAO,EAAE,IAAI,WAAW;AACzB;;;;;;;;;;;;AAaA,SAAgB,wBACf,UAA0C,CAAC,GACvB;CACpB,OAAO,OAAO,GAAG,SAAS;EAEzB,IACC,QAAQ,eACR,iBAAiB,EAAE,IAAI,MAAM,QAAQ,WAAW,GAEhD,OAAO,KAAK;EAIb,IAAI,QAAQ,aAAa,CAAC,GACzB,OAAO,KAAK;EAIb,MAAM,UAAyD,CAAC;EAChE,EAAE,IAAI,IAAI,QAAQ,SAAS,OAAO,QAAQ;GACzC,QAAQ,OAAO;EAChB,CAAC;EAGD,MAAM,EAAE,QAAQ,eAAe,UAAU,qBACxC,SACA,gBAAgB,GAAG,OAAO,CAC3B;EAGA,MAAM,QAAQ,wBAAwB,GAAG,OAAO;EAGhD,MAAM,OAAO,qBAAqB,OAAO,eAAe,KAAK;EAC7D,MAAM,cAAc,MAAM,QAAQ,eAAe,IAAI;EAGrD,EAAE,IAAI,UAAU,IAAI;EACpB,EAAE,IAAI,aAAa,WA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MAAM,GAAG,EAAE;EAClC,IAAI,KAAK,WAAW,MAAM,GACzB,OAAO;CAET,OAAO,IAAI,SAAS,SAEnB,OAAO;CAGT,OAAO;AACR;;;;;;;;;;;;;;;AAgBA,eAAsB,oBACrB,GACA,IACa;CACb,MAAM,MAAM,wBAAwB,CAAC;CACrC,IAAI,CAAC,KACJ,OAAO,GAAG;CAEX,OAAO,QAAQ,KAAK,KAAK,EAAE;AAC5B"}
@@ -45,6 +45,29 @@ function extractTraceContext(headers) {
45
45
  return _opentelemetry_api.propagation.extract(_opentelemetry_api.context.active(), normalizedHeaders);
46
46
  }
47
47
  /**
48
+ * The trace a request's span belongs to.
49
+ *
50
+ * From a trusted caller (see `./trust`) its `traceparent` is continued, and
51
+ * the span is its child. From anyone else the span starts a new trace — no
52
+ * parent, no baggage — with a link to the context the caller claimed, so the
53
+ * hop can still be followed without the caller choosing this trace.
54
+ */
55
+ function incomingTraceContext(headers, trusted) {
56
+ const extracted = extractTraceContext(headers);
57
+ if (trusted) return {
58
+ parent: extracted,
59
+ links: []
60
+ };
61
+ const claimed = _opentelemetry_api.trace.getSpanContext(extracted);
62
+ return {
63
+ parent: _opentelemetry_api.trace.deleteSpan(_opentelemetry_api.context.active()),
64
+ links: claimed && (0, _opentelemetry_api.isSpanContextValid)(claimed) ? [{
65
+ context: claimed,
66
+ attributes: { "gkm.trace.untrusted_parent": true }
67
+ }] : []
68
+ };
69
+ }
70
+ /**
48
71
  * Inject trace context into HTTP headers
49
72
  */
50
73
  function injectTraceContext(headers, ctx) {
@@ -55,13 +78,14 @@ function injectTraceContext(headers, ctx) {
55
78
  /**
56
79
  * Create an HTTP server span for an incoming request
57
80
  */
58
- function createHttpServerSpan(attrs, parentContext) {
81
+ function createHttpServerSpan(attrs, parentContext, links) {
59
82
  const tracer = getConstructsTracer();
60
83
  const spanName = attrs.route ? `${attrs.method} ${attrs.route}` : `${attrs.method} ${attrs.path || "/"}`;
61
84
  const ctx = parentContext ?? _opentelemetry_api.context.active();
62
85
  return tracer.startSpan(spanName, {
63
86
  kind: _opentelemetry_api.SpanKind.SERVER,
64
- attributes: toOtelAttributes(attrs)
87
+ attributes: toOtelAttributes(attrs),
88
+ ...links?.length ? { links } : {}
65
89
  }, ctx);
66
90
  }
67
91
  /**
@@ -76,11 +100,11 @@ function endHttpSpan(span, response, error) {
76
100
  code: _opentelemetry_api.SpanStatusCode.ERROR,
77
101
  message: error.message
78
102
  });
79
- } else if (response.statusCode >= 400) span.setStatus({
103
+ } else if (response.statusCode >= 500) span.setStatus({
80
104
  code: _opentelemetry_api.SpanStatusCode.ERROR,
81
105
  message: `HTTP ${response.statusCode}`
82
106
  });
83
- else span.setStatus({ code: _opentelemetry_api.SpanStatusCode.OK });
107
+ else if (response.statusCode < 400) span.setStatus({ code: _opentelemetry_api.SpanStatusCode.OK });
84
108
  span.end();
85
109
  }
86
110
  /**
@@ -156,6 +180,7 @@ exports.createHttpServerSpan = createHttpServerSpan;
156
180
  exports.endHttpSpan = endHttpSpan;
157
181
  exports.extractTraceContext = extractTraceContext;
158
182
  exports.getConstructsTracer = getConstructsTracer;
183
+ exports.incomingTraceContext = incomingTraceContext;
159
184
  exports.injectTraceContext = injectTraceContext;
160
185
  exports.isTracingEnabled = isTracingEnabled;
161
186
  exports.toOtelAttributes = toOtelAttributes;
@@ -1 +1 @@
1
- {"version":3,"file":"http.cjs","names":["trace","propagation","context","SpanKind","SpanStatusCode"],"sources":["../../src/instrumentation/http.ts"],"sourcesContent":["import {\n\ttype Attributes,\n\ttype Context,\n\tcontext,\n\tpropagation,\n\ttype Span,\n\tSpanKind,\n\tSpanStatusCode,\n\ttrace,\n} from '@opentelemetry/api';\n\n/**\n * HTTP request attributes following OpenTelemetry semantic conventions\n */\nexport interface HttpRequestAttributes {\n\tmethod: string;\n\turl?: string;\n\tpath?: string;\n\troute?: string;\n\thost?: string;\n\tscheme?: 'http' | 'https';\n\tuserAgent?: string;\n\tclientIp?: string;\n\trequestId?: string;\n}\n\n/**\n * HTTP response attributes\n */\nexport interface HttpResponseAttributes {\n\tstatusCode: number;\n\tresponseSize?: number;\n}\n\n/**\n * Endpoint-specific attributes\n */\nexport interface EndpointAttributes {\n\tname?: string;\n\toperationId?: string;\n\ttags?: string[];\n}\n\n/**\n * User/session attributes\n */\nexport interface UserAttributes {\n\tuserId?: string;\n\tsessionId?: string;\n\troles?: string[];\n}\n\n/**\n * Full span attributes for HTTP requests\n */\nexport interface HttpSpanAttributes extends HttpRequestAttributes {\n\tresponse?: HttpResponseAttributes;\n\tendpoint?: EndpointAttributes;\n\tuser?: UserAttributes;\n\tcustom?: Attributes;\n}\n\nconst TRACER_NAME = '@geekmidas/constructs';\n\n/**\n * Get or create a tracer for constructs instrumentation\n */\nexport function getConstructsTracer() {\n\treturn trace.getTracer(TRACER_NAME);\n}\n\n/**\n * Convert HTTP attributes to OpenTelemetry semantic conventions\n */\nexport function toOtelAttributes(attrs: HttpSpanAttributes): Attributes {\n\tconst otelAttrs: Attributes = {};\n\n\t// HTTP request attributes (OpenTelemetry semantic conventions)\n\tif (attrs.method) otelAttrs['http.request.method'] = attrs.method;\n\tif (attrs.url) otelAttrs['url.full'] = attrs.url;\n\tif (attrs.path) otelAttrs['url.path'] = attrs.path;\n\tif (attrs.route) otelAttrs['http.route'] = attrs.route;\n\tif (attrs.host) otelAttrs['server.address'] = attrs.host;\n\tif (attrs.scheme) otelAttrs['url.scheme'] = attrs.scheme;\n\tif (attrs.userAgent) otelAttrs['user_agent.original'] = attrs.userAgent;\n\tif (attrs.clientIp) otelAttrs['client.address'] = attrs.clientIp;\n\tif (attrs.requestId) otelAttrs['http.request.id'] = attrs.requestId;\n\n\t// HTTP response attributes\n\tif (attrs.response?.statusCode) {\n\t\totelAttrs['http.response.status_code'] = attrs.response.statusCode;\n\t}\n\tif (attrs.response?.responseSize) {\n\t\totelAttrs['http.response.body.size'] = attrs.response.responseSize;\n\t}\n\n\t// Endpoint attributes\n\tif (attrs.endpoint?.name) otelAttrs['endpoint.name'] = attrs.endpoint.name;\n\tif (attrs.endpoint?.operationId) {\n\t\totelAttrs['endpoint.operation_id'] = attrs.endpoint.operationId;\n\t}\n\tif (attrs.endpoint?.tags?.length) {\n\t\totelAttrs['endpoint.tags'] = attrs.endpoint.tags;\n\t}\n\n\t// User attributes\n\tif (attrs.user?.userId) otelAttrs['enduser.id'] = attrs.user.userId;\n\tif (attrs.user?.sessionId) otelAttrs['session.id'] = attrs.user.sessionId;\n\tif (attrs.user?.roles?.length)\n\t\totelAttrs['enduser.role'] = attrs.user.roles.join(',');\n\n\t// Custom attributes\n\tif (attrs.custom) {\n\t\tObject.assign(otelAttrs, attrs.custom);\n\t}\n\n\treturn otelAttrs;\n}\n\n/**\n * Extract trace context from HTTP headers\n */\nexport function extractTraceContext(\n\theaders: Record<string, string | string[] | undefined>,\n): Context {\n\t// Normalize headers to Record<string, string>\n\tconst normalizedHeaders: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (value) {\n\t\t\tconst stringValue = Array.isArray(value) ? value[0] : value;\n\t\t\tif (stringValue) {\n\t\t\t\tnormalizedHeaders[key.toLowerCase()] = stringValue;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn propagation.extract(context.active(), normalizedHeaders);\n}\n\n/**\n * Inject trace context into HTTP headers\n */\nexport function injectTraceContext(\n\theaders: Record<string, string>,\n\tctx?: Context,\n): Record<string, string> {\n\tconst result = { ...headers };\n\tpropagation.inject(ctx ?? context.active(), result);\n\treturn result;\n}\n\n/**\n * Create an HTTP server span for an incoming request\n */\nexport function createHttpServerSpan(\n\tattrs: HttpSpanAttributes,\n\tparentContext?: Context,\n): Span {\n\tconst tracer = getConstructsTracer();\n\tconst spanName = attrs.route\n\t\t? `${attrs.method} ${attrs.route}`\n\t\t: `${attrs.method} ${attrs.path || '/'}`;\n\n\tconst ctx = parentContext ?? context.active();\n\n\treturn tracer.startSpan(\n\t\tspanName,\n\t\t{\n\t\t\tkind: SpanKind.SERVER,\n\t\t\tattributes: toOtelAttributes(attrs),\n\t\t},\n\t\tctx,\n\t);\n}\n\n/**\n * End an HTTP span with response data\n */\nexport function endHttpSpan(\n\tspan: Span,\n\tresponse: HttpResponseAttributes,\n\terror?: Error,\n): void {\n\tspan.setAttribute('http.response.status_code', response.statusCode);\n\n\tif (response.responseSize) {\n\t\tspan.setAttribute('http.response.body.size', response.responseSize);\n\t}\n\n\tif (error) {\n\t\tspan.recordException(error);\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: error.message,\n\t\t});\n\t} else if (response.statusCode >= 400) {\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: `HTTP ${response.statusCode}`,\n\t\t});\n\t} else {\n\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t}\n\n\tspan.end();\n}\n\n/**\n * Execute a function within an HTTP server span context\n *\n * @example\n * ```typescript\n * const result = await withHttpSpan(\n * { method: 'GET', path: '/users', route: '/users' },\n * async (span) => {\n * const users = await getUsers();\n * return { statusCode: 200, body: users };\n * }\n * );\n * ```\n */\nexport async function withHttpSpan<T>(\n\tattrs: HttpSpanAttributes,\n\tfn: (span: Span) => Promise<T & { statusCode?: number }>,\n\tparentContext?: Context,\n): Promise<T> {\n\tconst span = createHttpServerSpan(attrs, parentContext);\n\n\ttry {\n\t\tconst result = await context.with(\n\t\t\ttrace.setSpan(parentContext ?? context.active(), span),\n\t\t\t() => fn(span),\n\t\t);\n\n\t\tconst statusCode = (result as { statusCode?: number }).statusCode ?? 200;\n\t\tendHttpSpan(span, { statusCode });\n\n\t\treturn result;\n\t} catch (error) {\n\t\tendHttpSpan(\n\t\t\tspan,\n\t\t\t{ statusCode: 500 },\n\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Create a child span for internal operations (middleware, handlers, etc.)\n */\nexport function createChildSpan(name: string, attributes?: Attributes): Span {\n\tconst tracer = getConstructsTracer();\n\treturn tracer.startSpan(name, {\n\t\tkind: SpanKind.INTERNAL,\n\t\tattributes,\n\t});\n}\n\n/**\n * Execute a function within a child span\n */\nexport async function withChildSpan<T>(\n\tname: string,\n\tfn: (span: Span) => Promise<T>,\n\tattributes?: Attributes,\n): Promise<T> {\n\tconst span = createChildSpan(name, attributes);\n\n\ttry {\n\t\tconst result = await context.with(\n\t\t\ttrace.setSpan(context.active(), span),\n\t\t\t() => fn(span),\n\t\t);\n\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t\treturn result;\n\t} catch (error) {\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: error instanceof Error ? error.message : 'Unknown error',\n\t\t});\n\t\tspan.recordException(\n\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t);\n\t\tthrow error;\n\t} finally {\n\t\tspan.end();\n\t}\n}\n\n/**\n * Check if tracing is enabled (OpenTelemetry API is available and configured)\n */\nexport function isTracingEnabled(): boolean {\n\ttry {\n\t\tconst tracer = trace.getTracer(TRACER_NAME);\n\t\t// Check if we have a real tracer (not a no-op)\n\t\tconst span = tracer.startSpan('test');\n\t\tconst isReal =\n\t\t\tspan.spanContext().traceId !== '00000000000000000000000000000000';\n\t\tspan.end();\n\t\treturn isReal;\n\t} catch {\n\t\treturn false;\n\t}\n}\n"],"mappings":";;;AA8DA,MAAM,cAAc;;;;AAKpB,SAAgB,sBAAsB;CACrC,OAAOA,mBAAAA,MAAM,UAAU,WAAW;AACnC;;;;AAKA,SAAgB,iBAAiB,OAAuC;CACvE,MAAM,YAAwB,CAAC;CAG/B,IAAI,MAAM,QAAQ,UAAU,yBAAyB,MAAM;CAC3D,IAAI,MAAM,KAAK,UAAU,cAAc,MAAM;CAC7C,IAAI,MAAM,MAAM,UAAU,cAAc,MAAM;CAC9C,IAAI,MAAM,OAAO,UAAU,gBAAgB,MAAM;CACjD,IAAI,MAAM,MAAM,UAAU,oBAAoB,MAAM;CACpD,IAAI,MAAM,QAA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EAC7B,MAAMC,mBAAAA,SAAS;EACf;CACD,CAAC;AACF;;;;AAKA,eAAsB,cACrB,MACA,IACA,YACa;CACb,MAAM,OAAO,gBAAgB,MAAM,UAAU;CAE7C,IAAI;EACH,MAAM,SAAS,MAAMD,mBAAAA,QAAQ,KAC5BF,mBAAAA,MAAM,QAAQE,mBAAAA,QAAQ,OAAO,GAAG,IAAI,SAC9B,GAAG,IAAI,CACd;EACA,KAAK,UAAU,EAAE,MAAME,mBAAAA,eAAe,GAAG,CAAC;EAC1C,OAAO;CACR,SAAS,OAAO;EACf,KAAK,UAAU;GACd,MAAMA,mBAAAA,eAAe;GACrB,SAAS,iBAAiB,QAAQ,MAAM,UAAU;EACnD,CAAC;EACD,KAAK,gBACJ,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CACzD;EACA,MAAM;CACP,UAAU;EACT,KAAK,IAAI;CACV;AACD;;;;AAKA,SAAgB,mBAA4B;CAC3C,IAAI;EAGH,MAAM,OAFSJ,mBAAAA,MAAM,UAAU,WAEb,CAAC,CAAC,UAAU,MAAM;EACpC,MAAM,SACL,KAAK,YAAY,CAAC,CAAC,YAAY;EAChC,KAAK,IAAI;EACT,OAAO;CACR,QAAQ;EACP,OAAO;CACR;AACD"}
1
+ {"version":3,"file":"http.cjs","names":["trace","propagation","context","isSpanContextValid","SpanKind","SpanStatusCode"],"sources":["../../src/instrumentation/http.ts"],"sourcesContent":["import {\n\ttype Attributes,\n\ttype Context,\n\tcontext,\n\tisSpanContextValid,\n\ttype Link,\n\tpropagation,\n\ttype Span,\n\tSpanKind,\n\tSpanStatusCode,\n\ttrace,\n} from '@opentelemetry/api';\n\n/**\n * HTTP request attributes following OpenTelemetry semantic conventions\n */\nexport interface HttpRequestAttributes {\n\tmethod: string;\n\turl?: string;\n\tpath?: string;\n\troute?: string;\n\thost?: string;\n\tscheme?: 'http' | 'https';\n\tuserAgent?: string;\n\tclientIp?: string;\n\trequestId?: string;\n}\n\n/**\n * HTTP response attributes\n */\nexport interface HttpResponseAttributes {\n\tstatusCode: number;\n\tresponseSize?: number;\n}\n\n/**\n * Endpoint-specific attributes\n */\nexport interface EndpointAttributes {\n\tname?: string;\n\toperationId?: string;\n\ttags?: string[];\n}\n\n/**\n * User/session attributes\n */\nexport interface UserAttributes {\n\tuserId?: string;\n\tsessionId?: string;\n\troles?: string[];\n}\n\n/**\n * Full span attributes for HTTP requests\n */\nexport interface HttpSpanAttributes extends HttpRequestAttributes {\n\tresponse?: HttpResponseAttributes;\n\tendpoint?: EndpointAttributes;\n\tuser?: UserAttributes;\n\tcustom?: Attributes;\n}\n\nconst TRACER_NAME = '@geekmidas/constructs';\n\n/**\n * Get or create a tracer for constructs instrumentation\n */\nexport function getConstructsTracer() {\n\treturn trace.getTracer(TRACER_NAME);\n}\n\n/**\n * Convert HTTP attributes to OpenTelemetry semantic conventions\n */\nexport function toOtelAttributes(attrs: HttpSpanAttributes): Attributes {\n\tconst otelAttrs: Attributes = {};\n\n\t// HTTP request attributes (OpenTelemetry semantic conventions)\n\tif (attrs.method) otelAttrs['http.request.method'] = attrs.method;\n\tif (attrs.url) otelAttrs['url.full'] = attrs.url;\n\tif (attrs.path) otelAttrs['url.path'] = attrs.path;\n\tif (attrs.route) otelAttrs['http.route'] = attrs.route;\n\tif (attrs.host) otelAttrs['server.address'] = attrs.host;\n\tif (attrs.scheme) otelAttrs['url.scheme'] = attrs.scheme;\n\tif (attrs.userAgent) otelAttrs['user_agent.original'] = attrs.userAgent;\n\tif (attrs.clientIp) otelAttrs['client.address'] = attrs.clientIp;\n\tif (attrs.requestId) otelAttrs['http.request.id'] = attrs.requestId;\n\n\t// HTTP response attributes\n\tif (attrs.response?.statusCode) {\n\t\totelAttrs['http.response.status_code'] = attrs.response.statusCode;\n\t}\n\tif (attrs.response?.responseSize) {\n\t\totelAttrs['http.response.body.size'] = attrs.response.responseSize;\n\t}\n\n\t// Endpoint attributes\n\tif (attrs.endpoint?.name) otelAttrs['endpoint.name'] = attrs.endpoint.name;\n\tif (attrs.endpoint?.operationId) {\n\t\totelAttrs['endpoint.operation_id'] = attrs.endpoint.operationId;\n\t}\n\tif (attrs.endpoint?.tags?.length) {\n\t\totelAttrs['endpoint.tags'] = attrs.endpoint.tags;\n\t}\n\n\t// User attributes\n\tif (attrs.user?.userId) otelAttrs['enduser.id'] = attrs.user.userId;\n\tif (attrs.user?.sessionId) otelAttrs['session.id'] = attrs.user.sessionId;\n\tif (attrs.user?.roles?.length)\n\t\totelAttrs['enduser.role'] = attrs.user.roles.join(',');\n\n\t// Custom attributes\n\tif (attrs.custom) {\n\t\tObject.assign(otelAttrs, attrs.custom);\n\t}\n\n\treturn otelAttrs;\n}\n\n/**\n * Extract trace context from HTTP headers\n */\nexport function extractTraceContext(\n\theaders: Record<string, string | string[] | undefined>,\n): Context {\n\t// Normalize headers to Record<string, string>\n\tconst normalizedHeaders: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (value) {\n\t\t\tconst stringValue = Array.isArray(value) ? value[0] : value;\n\t\t\tif (stringValue) {\n\t\t\t\tnormalizedHeaders[key.toLowerCase()] = stringValue;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn propagation.extract(context.active(), normalizedHeaders);\n}\n\n/** Where a request's span goes: under a parent, or a new root with links. */\nexport interface IncomingTraceContext {\n\t/** The context the request span starts in. */\n\tparent: Context;\n\t/** The untrusted caller's context, linked rather than continued. */\n\tlinks: Link[];\n}\n\n/**\n * The trace a request's span belongs to.\n *\n * From a trusted caller (see `./trust`) its `traceparent` is continued, and\n * the span is its child. From anyone else the span starts a new trace — no\n * parent, no baggage — with a link to the context the caller claimed, so the\n * hop can still be followed without the caller choosing this trace.\n */\nexport function incomingTraceContext(\n\theaders: Record<string, string | string[] | undefined>,\n\ttrusted: boolean,\n): IncomingTraceContext {\n\tconst extracted = extractTraceContext(headers);\n\tif (trusted) return { parent: extracted, links: [] };\n\n\tconst claimed = trace.getSpanContext(extracted);\n\treturn {\n\t\tparent: trace.deleteSpan(context.active()),\n\t\tlinks:\n\t\t\tclaimed && isSpanContextValid(claimed)\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext: claimed,\n\t\t\t\t\t\t\tattributes: { 'gkm.trace.untrusted_parent': true },\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t};\n}\n\n/**\n * Inject trace context into HTTP headers\n */\nexport function injectTraceContext(\n\theaders: Record<string, string>,\n\tctx?: Context,\n): Record<string, string> {\n\tconst result = { ...headers };\n\tpropagation.inject(ctx ?? context.active(), result);\n\treturn result;\n}\n\n/**\n * Create an HTTP server span for an incoming request\n */\nexport function createHttpServerSpan(\n\tattrs: HttpSpanAttributes,\n\tparentContext?: Context,\n\tlinks?: Link[],\n): Span {\n\tconst tracer = getConstructsTracer();\n\tconst spanName = attrs.route\n\t\t? `${attrs.method} ${attrs.route}`\n\t\t: `${attrs.method} ${attrs.path || '/'}`;\n\n\tconst ctx = parentContext ?? context.active();\n\n\treturn tracer.startSpan(\n\t\tspanName,\n\t\t{\n\t\t\tkind: SpanKind.SERVER,\n\t\t\tattributes: toOtelAttributes(attrs),\n\t\t\t...(links?.length ? { links } : {}),\n\t\t},\n\t\tctx,\n\t);\n}\n\n/**\n * End an HTTP span with response data\n */\nexport function endHttpSpan(\n\tspan: Span,\n\tresponse: HttpResponseAttributes,\n\terror?: Error,\n): void {\n\tspan.setAttribute('http.response.status_code', response.statusCode);\n\n\tif (response.responseSize) {\n\t\tspan.setAttribute('http.response.body.size', response.responseSize);\n\t}\n\n\tif (error) {\n\t\tspan.recordException(error);\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: error.message,\n\t\t});\n\t} else if (response.statusCode >= 500) {\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: `HTTP ${response.statusCode}`,\n\t\t});\n\t} else if (response.statusCode < 400) {\n\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t}\n\t// A 4xx leaves the status unset: on a server span it is the client's\n\t// mistake, not the server's failure (HTTP semantic conventions).\n\n\tspan.end();\n}\n\n/**\n * Execute a function within an HTTP server span context\n *\n * @example\n * ```typescript\n * const result = await withHttpSpan(\n * { method: 'GET', path: '/users', route: '/users' },\n * async (span) => {\n * const users = await getUsers();\n * return { statusCode: 200, body: users };\n * }\n * );\n * ```\n */\nexport async function withHttpSpan<T>(\n\tattrs: HttpSpanAttributes,\n\tfn: (span: Span) => Promise<T & { statusCode?: number }>,\n\tparentContext?: Context,\n): Promise<T> {\n\tconst span = createHttpServerSpan(attrs, parentContext);\n\n\ttry {\n\t\tconst result = await context.with(\n\t\t\ttrace.setSpan(parentContext ?? context.active(), span),\n\t\t\t() => fn(span),\n\t\t);\n\n\t\tconst statusCode = (result as { statusCode?: number }).statusCode ?? 200;\n\t\tendHttpSpan(span, { statusCode });\n\n\t\treturn result;\n\t} catch (error) {\n\t\tendHttpSpan(\n\t\t\tspan,\n\t\t\t{ statusCode: 500 },\n\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Create a child span for internal operations (middleware, handlers, etc.)\n */\nexport function createChildSpan(name: string, attributes?: Attributes): Span {\n\tconst tracer = getConstructsTracer();\n\treturn tracer.startSpan(name, {\n\t\tkind: SpanKind.INTERNAL,\n\t\tattributes,\n\t});\n}\n\n/**\n * Execute a function within a child span\n */\nexport async function withChildSpan<T>(\n\tname: string,\n\tfn: (span: Span) => Promise<T>,\n\tattributes?: Attributes,\n): Promise<T> {\n\tconst span = createChildSpan(name, attributes);\n\n\ttry {\n\t\tconst result = await context.with(\n\t\t\ttrace.setSpan(context.active(), span),\n\t\t\t() => fn(span),\n\t\t);\n\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t\treturn result;\n\t} catch (error) {\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: error instanceof Error ? error.message : 'Unknown error',\n\t\t});\n\t\tspan.recordException(\n\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t);\n\t\tthrow error;\n\t} finally {\n\t\tspan.end();\n\t}\n}\n\n/**\n * Check if tracing is enabled (OpenTelemetry API is available and configured)\n */\nexport function isTracingEnabled(): boolean {\n\ttry {\n\t\tconst tracer = trace.getTracer(TRACER_NAME);\n\t\t// Check if we have a real tracer (not a no-op)\n\t\tconst span = tracer.startSpan('test');\n\t\tconst isReal =\n\t\t\tspan.spanContext().traceId !== '00000000000000000000000000000000';\n\t\tspan.end();\n\t\treturn isReal;\n\t} catch {\n\t\treturn false;\n\t}\n}\n"],"mappings":";;;AAgEA,MAAM,cAAc;;;;AAKpB,SAAgB,sBAAsB;CACrC,OAAOA,mBAAAA,MAAM,UAAU,WAAW;AACnC;;;;AAKA,SAAgB,iBAAiB,OAAuC;CACvE,MAAM,YAAwB,CAAC;CAG/B,IAAI,MAAM,QAAQ,UAAU,yBAAyB,MAAM;CAC3D,IAAI,MAAM,KAAK,UAAU,cAAc,MAAM;CAC7C,IAAI,MAAM,MAAM,UAAU,cAAc,MAAM;CAC9C,IAAI,MAAM,OAAO,UAAU,gBAAgB,MAAM;CACjD,IAAI,MAAM,MAAM,UAAU,oBAAoB,MAAM;CACpD,IAAI,MAAM,QAAQ,UAAU,gBAAgB,MAAM;CAClD,IAAI,MAAM,WAAW,UAAU,yBAAyB,MAAM;CAC9D,IAAI,MAAM,UAAU,UAAU,oBAAoB,MAAM;CACxD,IAAI,MAAM,WAAW,UAAU,qBAAqB,MAAM;CAG1D,IAAI,MAAM,UAAU,YACnB,UAAU,+BAA+B,MAAM,SAAS;CAEzD,IAAI,MAAM,UAAU,cACnB,UAAU,6BAA6B,MAAM,SAAS;CAIvD,IAAI,MAAM,UAAU,MAAM,UAAU,mBAAmB,MAAM,SAAS;CACtE,IAAI,MAAM,UAAU,aACnB,UAAU,2BAA2B,MAAM,SAAS;CAErD,IAAI,MAAM,U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gBAAgB,MAAc,YAA+B;CAE5E,OADe,oBACH,CAAC,CAAC,UAAU,MAAM;EAC7B,MAAME,mBAAAA,SAAS;EACf;CACD,CAAC;AACF;;;;AAKA,eAAsB,cACrB,MACA,IACA,YACa;CACb,MAAM,OAAO,gBAAgB,MAAM,UAAU;CAE7C,IAAI;EACH,MAAM,SAAS,MAAMF,mBAAAA,QAAQ,KAC5BF,mBAAAA,MAAM,QAAQE,mBAAAA,QAAQ,OAAO,GAAG,IAAI,SAC9B,GAAG,IAAI,CACd;EACA,KAAK,UAAU,EAAE,MAAMG,mBAAAA,eAAe,GAAG,CAAC;EAC1C,OAAO;CACR,SAAS,OAAO;EACf,KAAK,UAAU;GACd,MAAMA,mBAAAA,eAAe;GACrB,SAAS,iBAAiB,QAAQ,MAAM,UAAU;EACnD,CAAC;EACD,KAAK,gBACJ,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CACzD;EACA,MAAM;CACP,UAAU;EACT,KAAK,IAAI;CACV;AACD;;;;AAKA,SAAgB,mBAA4B;CAC3C,IAAI;EAGH,MAAM,OAFSL,mBAAAA,MAAM,UAAU,WAEb,CAAC,CAAC,UAAU,MAAM;EACpC,MAAM,SACL,KAAK,YAAY,CAAC,CAAC,YAAY;EAChC,KAAK,IAAI;EACT,OAAO;CACR,QAAQ;EACP,OAAO;CACR;AACD"}
@@ -1,4 +1,4 @@
1
- import { Attributes, Context, Span } from "@opentelemetry/api";
1
+ import { Attributes, Context, Link, Span } from "@opentelemetry/api";
2
2
  //#region src/instrumentation/http.d.ts
3
3
  /**
4
4
  * HTTP request attributes following OpenTelemetry semantic conventions
@@ -58,6 +58,22 @@ export declare function toOtelAttributes(attrs: HttpSpanAttributes): Attributes;
58
58
  * Extract trace context from HTTP headers
59
59
  */
60
60
  export declare function extractTraceContext(headers: Record<string, string | string[] | undefined>): Context;
61
+ /** Where a request's span goes: under a parent, or a new root with links. */
62
+ export interface IncomingTraceContext {
63
+ /** The context the request span starts in. */
64
+ parent: Context;
65
+ /** The untrusted caller's context, linked rather than continued. */
66
+ links: Link[];
67
+ }
68
+ /**
69
+ * The trace a request's span belongs to.
70
+ *
71
+ * From a trusted caller (see `./trust`) its `traceparent` is continued, and
72
+ * the span is its child. From anyone else the span starts a new trace — no
73
+ * parent, no baggage — with a link to the context the caller claimed, so the
74
+ * hop can still be followed without the caller choosing this trace.
75
+ */
76
+ export declare function incomingTraceContext(headers: Record<string, string | string[] | undefined>, trusted: boolean): IncomingTraceContext;
61
77
  /**
62
78
  * Inject trace context into HTTP headers
63
79
  */
@@ -65,7 +81,7 @@ export declare function injectTraceContext(headers: Record<string, string>, ctx?
65
81
  /**
66
82
  * Create an HTTP server span for an incoming request
67
83
  */
68
- export declare function createHttpServerSpan(attrs: HttpSpanAttributes, parentContext?: Context): Span;
84
+ export declare function createHttpServerSpan(attrs: HttpSpanAttributes, parentContext?: Context, links?: Link[]): Span;
69
85
  /**
70
86
  * End an HTTP span with response data
71
87
  */
@@ -1 +1 @@
1
- {"version":3,"file":"http.d.cts","names":[],"sources":["../../src/instrumentation/http.ts"],"mappings":";;;;;iBAciB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;iBAMgB;EAChB;EACA;;;;;iBAMgB;EAChB;EACA;EACA;;;;;iBAMgB;EAChB;EACA;EACA;;;;;iBAMgB,2BAA2B;EAC3C,WAAW;EACX,WAAW;EACX,OAAO;EACP,SAAS;;;;;wBAQM,oDAAmB;;;;wBAOnB,iBAAiB,OAAO,qBAAqB;;;;wBAgD7C,oBACf,SAAS,gDACP;;;;wBAkBa,mBACf,SAAS,wBACT,MAAM,UACJ;;;;wBASa,qBACf,OAAO,oBACP,gBAAgB,UACd;;;;wBAqBa,YACf,MAAM,MACN,UAAU,wBACV,QAAQ;;;;;;;;;;;;;;;wBAwCa,aAAa,GAClC,OAAO,oBACP,KAAK,MAAM,SAAS,QAAQ;EAAM;IAClC,gBAAgB,UACd,QAAQ;;;;wBA0BK,gBAAgB,cAAc,aAAa,aAAa;;;;wBAWlD,cAAc,GACnC,cACA,KAAK,MAAM,SAAS,QAAQ,IAC5B,aAAa,aACX,QAAQ;;;;wBA2BK"}
1
+ {"version":3,"file":"http.d.cts","names":[],"sources":["../../src/instrumentation/http.ts"],"mappings":";;;;;iBAgBiB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;iBAMgB;EAChB;EACA;;;;;iBAMgB;EAChB;EACA;EACA;;;;;iBAMgB;EAChB;EACA;EACA;;;;;iBAMgB,2BAA2B;EAC3C,WAAW;EACX,WAAW;EACX,OAAO;EACP,SAAS;;;;;wBAQM,oDAAmB;;;;wBAOnB,iBAAiB,OAAO,qBAAqB;;;;wBAgD7C,oBACf,SAAS,gDACP;;iBAgBc;;EAEhB,QAAQ;;EAER,OAAO;;;;;;;;;;wBAWQ,qBACf,SAAS,+CACT,mBACE;;;;wBAsBa,mBACf,SAAS,wBACT,MAAM,UACJ;;;;wBASa,qBACf,OAAO,oBACP,gBAAgB,SAChB,QAAQ,SACN;;;;wBAsBa,YACf,MAAM,MACN,UAAU,wBACV,QAAQ;;;;;;;;;;;;;;;wBA0Ca,aAAa,GAClC,OAAO,oBACP,KAAK,MAAM,SAAS,QAAQ;EAAM;IAClC,gBAAgB,UACd,QAAQ;;;;wBA0BK,gBAAgB,cAAc,aAAa,aAAa;;;;wBAWlD,cAAc,GACnC,cACA,KAAK,MAAM,SAAS,QAAQ,IAC5B,aAAa,aACX,QAAQ;;;;wBA2BK"}
@@ -1,4 +1,4 @@
1
- import { Attributes, Context, Span } from "@opentelemetry/api";
1
+ import { Attributes, Context, Link, Span } from "@opentelemetry/api";
2
2
  //#region src/instrumentation/http.d.ts
3
3
  /**
4
4
  * HTTP request attributes following OpenTelemetry semantic conventions
@@ -58,6 +58,22 @@ export declare function toOtelAttributes(attrs: HttpSpanAttributes): Attributes;
58
58
  * Extract trace context from HTTP headers
59
59
  */
60
60
  export declare function extractTraceContext(headers: Record<string, string | string[] | undefined>): Context;
61
+ /** Where a request's span goes: under a parent, or a new root with links. */
62
+ export interface IncomingTraceContext {
63
+ /** The context the request span starts in. */
64
+ parent: Context;
65
+ /** The untrusted caller's context, linked rather than continued. */
66
+ links: Link[];
67
+ }
68
+ /**
69
+ * The trace a request's span belongs to.
70
+ *
71
+ * From a trusted caller (see `./trust`) its `traceparent` is continued, and
72
+ * the span is its child. From anyone else the span starts a new trace — no
73
+ * parent, no baggage — with a link to the context the caller claimed, so the
74
+ * hop can still be followed without the caller choosing this trace.
75
+ */
76
+ export declare function incomingTraceContext(headers: Record<string, string | string[] | undefined>, trusted: boolean): IncomingTraceContext;
61
77
  /**
62
78
  * Inject trace context into HTTP headers
63
79
  */
@@ -65,7 +81,7 @@ export declare function injectTraceContext(headers: Record<string, string>, ctx?
65
81
  /**
66
82
  * Create an HTTP server span for an incoming request
67
83
  */
68
- export declare function createHttpServerSpan(attrs: HttpSpanAttributes, parentContext?: Context): Span;
84
+ export declare function createHttpServerSpan(attrs: HttpSpanAttributes, parentContext?: Context, links?: Link[]): Span;
69
85
  /**
70
86
  * End an HTTP span with response data
71
87
  */
@@ -1 +1 @@
1
- {"version":3,"file":"http.d.mts","names":[],"sources":["../../src/instrumentation/http.ts"],"mappings":";;;;;iBAciB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;iBAMgB;EAChB;EACA;;;;;iBAMgB;EAChB;EACA;EACA;;;;;iBAMgB;EAChB;EACA;EACA;;;;;iBAMgB,2BAA2B;EAC3C,WAAW;EACX,WAAW;EACX,OAAO;EACP,SAAS;;;;;wBAQM,oDAAmB;;;;wBAOnB,iBAAiB,OAAO,qBAAqB;;;;wBAgD7C,oBACf,SAAS,gDACP;;;;wBAkBa,mBACf,SAAS,wBACT,MAAM,UACJ;;;;wBASa,qBACf,OAAO,oBACP,gBAAgB,UACd;;;;wBAqBa,YACf,MAAM,MACN,UAAU,wBACV,QAAQ;;;;;;;;;;;;;;;wBAwCa,aAAa,GAClC,OAAO,oBACP,KAAK,MAAM,SAAS,QAAQ;EAAM;IAClC,gBAAgB,UACd,QAAQ;;;;wBA0BK,gBAAgB,cAAc,aAAa,aAAa;;;;wBAWlD,cAAc,GACnC,cACA,KAAK,MAAM,SAAS,QAAQ,IAC5B,aAAa,aACX,QAAQ;;;;wBA2BK"}
1
+ {"version":3,"file":"http.d.mts","names":[],"sources":["../../src/instrumentation/http.ts"],"mappings":";;;;;iBAgBiB;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;iBAMgB;EAChB;EACA;;;;;iBAMgB;EAChB;EACA;EACA;;;;;iBAMgB;EAChB;EACA;EACA;;;;;iBAMgB,2BAA2B;EAC3C,WAAW;EACX,WAAW;EACX,OAAO;EACP,SAAS;;;;;wBAQM,oDAAmB;;;;wBAOnB,iBAAiB,OAAO,qBAAqB;;;;wBAgD7C,oBACf,SAAS,gDACP;;iBAgBc;;EAEhB,QAAQ;;EAER,OAAO;;;;;;;;;;wBAWQ,qBACf,SAAS,+CACT,mBACE;;;;wBAsBa,mBACf,SAAS,wBACT,MAAM,UACJ;;;;wBASa,qBACf,OAAO,oBACP,gBAAgB,SAChB,QAAQ,SACN;;;;wBAsBa,YACf,MAAM,MACN,UAAU,wBACV,QAAQ;;;;;;;;;;;;;;;wBA0Ca,aAAa,GAClC,OAAO,oBACP,KAAK,MAAM,SAAS,QAAQ;EAAM;IAClC,gBAAgB,UACd,QAAQ;;;;wBA0BK,gBAAgB,cAAc,aAAa,aAAa;;;;wBAWlD,cAAc,GACnC,cACA,KAAK,MAAM,SAAS,QAAQ,IAC5B,aAAa,aACX,QAAQ;;;;wBA2BK"}
@@ -1,4 +1,4 @@
1
- import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
1
+ import { SpanKind, SpanStatusCode, context, isSpanContextValid, propagation, trace } from "@opentelemetry/api";
2
2
  //#region src/instrumentation/http.ts
3
3
  const TRACER_NAME = "@geekmidas/constructs";
4
4
  /**
@@ -44,6 +44,29 @@ function extractTraceContext(headers) {
44
44
  return propagation.extract(context.active(), normalizedHeaders);
45
45
  }
46
46
  /**
47
+ * The trace a request's span belongs to.
48
+ *
49
+ * From a trusted caller (see `./trust`) its `traceparent` is continued, and
50
+ * the span is its child. From anyone else the span starts a new trace — no
51
+ * parent, no baggage — with a link to the context the caller claimed, so the
52
+ * hop can still be followed without the caller choosing this trace.
53
+ */
54
+ function incomingTraceContext(headers, trusted) {
55
+ const extracted = extractTraceContext(headers);
56
+ if (trusted) return {
57
+ parent: extracted,
58
+ links: []
59
+ };
60
+ const claimed = trace.getSpanContext(extracted);
61
+ return {
62
+ parent: trace.deleteSpan(context.active()),
63
+ links: claimed && isSpanContextValid(claimed) ? [{
64
+ context: claimed,
65
+ attributes: { "gkm.trace.untrusted_parent": true }
66
+ }] : []
67
+ };
68
+ }
69
+ /**
47
70
  * Inject trace context into HTTP headers
48
71
  */
49
72
  function injectTraceContext(headers, ctx) {
@@ -54,13 +77,14 @@ function injectTraceContext(headers, ctx) {
54
77
  /**
55
78
  * Create an HTTP server span for an incoming request
56
79
  */
57
- function createHttpServerSpan(attrs, parentContext) {
80
+ function createHttpServerSpan(attrs, parentContext, links) {
58
81
  const tracer = getConstructsTracer();
59
82
  const spanName = attrs.route ? `${attrs.method} ${attrs.route}` : `${attrs.method} ${attrs.path || "/"}`;
60
83
  const ctx = parentContext ?? context.active();
61
84
  return tracer.startSpan(spanName, {
62
85
  kind: SpanKind.SERVER,
63
- attributes: toOtelAttributes(attrs)
86
+ attributes: toOtelAttributes(attrs),
87
+ ...links?.length ? { links } : {}
64
88
  }, ctx);
65
89
  }
66
90
  /**
@@ -75,11 +99,11 @@ function endHttpSpan(span, response, error) {
75
99
  code: SpanStatusCode.ERROR,
76
100
  message: error.message
77
101
  });
78
- } else if (response.statusCode >= 400) span.setStatus({
102
+ } else if (response.statusCode >= 500) span.setStatus({
79
103
  code: SpanStatusCode.ERROR,
80
104
  message: `HTTP ${response.statusCode}`
81
105
  });
82
- else span.setStatus({ code: SpanStatusCode.OK });
106
+ else if (response.statusCode < 400) span.setStatus({ code: SpanStatusCode.OK });
83
107
  span.end();
84
108
  }
85
109
  /**
@@ -150,6 +174,6 @@ function isTracingEnabled() {
150
174
  }
151
175
  }
152
176
  //#endregion
153
- export { createChildSpan, createHttpServerSpan, endHttpSpan, extractTraceContext, getConstructsTracer, injectTraceContext, isTracingEnabled, toOtelAttributes, withChildSpan, withHttpSpan };
177
+ export { createChildSpan, createHttpServerSpan, endHttpSpan, extractTraceContext, getConstructsTracer, incomingTraceContext, injectTraceContext, isTracingEnabled, toOtelAttributes, withChildSpan, withHttpSpan };
154
178
 
155
179
  //# sourceMappingURL=http.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"http.mjs","names":[],"sources":["../../src/instrumentation/http.ts"],"sourcesContent":["import {\n\ttype Attributes,\n\ttype Context,\n\tcontext,\n\tpropagation,\n\ttype Span,\n\tSpanKind,\n\tSpanStatusCode,\n\ttrace,\n} from '@opentelemetry/api';\n\n/**\n * HTTP request attributes following OpenTelemetry semantic conventions\n */\nexport interface HttpRequestAttributes {\n\tmethod: string;\n\turl?: string;\n\tpath?: string;\n\troute?: string;\n\thost?: string;\n\tscheme?: 'http' | 'https';\n\tuserAgent?: string;\n\tclientIp?: string;\n\trequestId?: string;\n}\n\n/**\n * HTTP response attributes\n */\nexport interface HttpResponseAttributes {\n\tstatusCode: number;\n\tresponseSize?: number;\n}\n\n/**\n * Endpoint-specific attributes\n */\nexport interface EndpointAttributes {\n\tname?: string;\n\toperationId?: string;\n\ttags?: string[];\n}\n\n/**\n * User/session attributes\n */\nexport interface UserAttributes {\n\tuserId?: string;\n\tsessionId?: string;\n\troles?: string[];\n}\n\n/**\n * Full span attributes for HTTP requests\n */\nexport interface HttpSpanAttributes extends HttpRequestAttributes {\n\tresponse?: HttpResponseAttributes;\n\tendpoint?: EndpointAttributes;\n\tuser?: UserAttributes;\n\tcustom?: Attributes;\n}\n\nconst TRACER_NAME = '@geekmidas/constructs';\n\n/**\n * Get or create a tracer for constructs instrumentation\n */\nexport function getConstructsTracer() {\n\treturn trace.getTracer(TRACER_NAME);\n}\n\n/**\n * Convert HTTP attributes to OpenTelemetry semantic conventions\n */\nexport function toOtelAttributes(attrs: HttpSpanAttributes): Attributes {\n\tconst otelAttrs: Attributes = {};\n\n\t// HTTP request attributes (OpenTelemetry semantic conventions)\n\tif (attrs.method) otelAttrs['http.request.method'] = attrs.method;\n\tif (attrs.url) otelAttrs['url.full'] = attrs.url;\n\tif (attrs.path) otelAttrs['url.path'] = attrs.path;\n\tif (attrs.route) otelAttrs['http.route'] = attrs.route;\n\tif (attrs.host) otelAttrs['server.address'] = attrs.host;\n\tif (attrs.scheme) otelAttrs['url.scheme'] = attrs.scheme;\n\tif (attrs.userAgent) otelAttrs['user_agent.original'] = attrs.userAgent;\n\tif (attrs.clientIp) otelAttrs['client.address'] = attrs.clientIp;\n\tif (attrs.requestId) otelAttrs['http.request.id'] = attrs.requestId;\n\n\t// HTTP response attributes\n\tif (attrs.response?.statusCode) {\n\t\totelAttrs['http.response.status_code'] = attrs.response.statusCode;\n\t}\n\tif (attrs.response?.responseSize) {\n\t\totelAttrs['http.response.body.size'] = attrs.response.responseSize;\n\t}\n\n\t// Endpoint attributes\n\tif (attrs.endpoint?.name) otelAttrs['endpoint.name'] = attrs.endpoint.name;\n\tif (attrs.endpoint?.operationId) {\n\t\totelAttrs['endpoint.operation_id'] = attrs.endpoint.operationId;\n\t}\n\tif (attrs.endpoint?.tags?.length) {\n\t\totelAttrs['endpoint.tags'] = attrs.endpoint.tags;\n\t}\n\n\t// User attributes\n\tif (attrs.user?.userId) otelAttrs['enduser.id'] = attrs.user.userId;\n\tif (attrs.user?.sessionId) otelAttrs['session.id'] = attrs.user.sessionId;\n\tif (attrs.user?.roles?.length)\n\t\totelAttrs['enduser.role'] = attrs.user.roles.join(',');\n\n\t// Custom attributes\n\tif (attrs.custom) {\n\t\tObject.assign(otelAttrs, attrs.custom);\n\t}\n\n\treturn otelAttrs;\n}\n\n/**\n * Extract trace context from HTTP headers\n */\nexport function extractTraceContext(\n\theaders: Record<string, string | string[] | undefined>,\n): Context {\n\t// Normalize headers to Record<string, string>\n\tconst normalizedHeaders: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (value) {\n\t\t\tconst stringValue = Array.isArray(value) ? value[0] : value;\n\t\t\tif (stringValue) {\n\t\t\t\tnormalizedHeaders[key.toLowerCase()] = stringValue;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn propagation.extract(context.active(), normalizedHeaders);\n}\n\n/**\n * Inject trace context into HTTP headers\n */\nexport function injectTraceContext(\n\theaders: Record<string, string>,\n\tctx?: Context,\n): Record<string, string> {\n\tconst result = { ...headers };\n\tpropagation.inject(ctx ?? context.active(), result);\n\treturn result;\n}\n\n/**\n * Create an HTTP server span for an incoming request\n */\nexport function createHttpServerSpan(\n\tattrs: HttpSpanAttributes,\n\tparentContext?: Context,\n): Span {\n\tconst tracer = getConstructsTracer();\n\tconst spanName = attrs.route\n\t\t? `${attrs.method} ${attrs.route}`\n\t\t: `${attrs.method} ${attrs.path || '/'}`;\n\n\tconst ctx = parentContext ?? context.active();\n\n\treturn tracer.startSpan(\n\t\tspanName,\n\t\t{\n\t\t\tkind: SpanKind.SERVER,\n\t\t\tattributes: toOtelAttributes(attrs),\n\t\t},\n\t\tctx,\n\t);\n}\n\n/**\n * End an HTTP span with response data\n */\nexport function endHttpSpan(\n\tspan: Span,\n\tresponse: HttpResponseAttributes,\n\terror?: Error,\n): void {\n\tspan.setAttribute('http.response.status_code', response.statusCode);\n\n\tif (response.responseSize) {\n\t\tspan.setAttribute('http.response.body.size', response.responseSize);\n\t}\n\n\tif (error) {\n\t\tspan.recordException(error);\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: error.message,\n\t\t});\n\t} else if (response.statusCode >= 400) {\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: `HTTP ${response.statusCode}`,\n\t\t});\n\t} else {\n\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t}\n\n\tspan.end();\n}\n\n/**\n * Execute a function within an HTTP server span context\n *\n * @example\n * ```typescript\n * const result = await withHttpSpan(\n * { method: 'GET', path: '/users', route: '/users' },\n * async (span) => {\n * const users = await getUsers();\n * return { statusCode: 200, body: users };\n * }\n * );\n * ```\n */\nexport async function withHttpSpan<T>(\n\tattrs: HttpSpanAttributes,\n\tfn: (span: Span) => Promise<T & { statusCode?: number }>,\n\tparentContext?: Context,\n): Promise<T> {\n\tconst span = createHttpServerSpan(attrs, parentContext);\n\n\ttry {\n\t\tconst result = await context.with(\n\t\t\ttrace.setSpan(parentContext ?? context.active(), span),\n\t\t\t() => fn(span),\n\t\t);\n\n\t\tconst statusCode = (result as { statusCode?: number }).statusCode ?? 200;\n\t\tendHttpSpan(span, { statusCode });\n\n\t\treturn result;\n\t} catch (error) {\n\t\tendHttpSpan(\n\t\t\tspan,\n\t\t\t{ statusCode: 500 },\n\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Create a child span for internal operations (middleware, handlers, etc.)\n */\nexport function createChildSpan(name: string, attributes?: Attributes): Span {\n\tconst tracer = getConstructsTracer();\n\treturn tracer.startSpan(name, {\n\t\tkind: SpanKind.INTERNAL,\n\t\tattributes,\n\t});\n}\n\n/**\n * Execute a function within a child span\n */\nexport async function withChildSpan<T>(\n\tname: string,\n\tfn: (span: Span) => Promise<T>,\n\tattributes?: Attributes,\n): Promise<T> {\n\tconst span = createChildSpan(name, attributes);\n\n\ttry {\n\t\tconst result = await context.with(\n\t\t\ttrace.setSpan(context.active(), span),\n\t\t\t() => fn(span),\n\t\t);\n\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t\treturn result;\n\t} catch (error) {\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: error instanceof Error ? error.message : 'Unknown error',\n\t\t});\n\t\tspan.recordException(\n\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t);\n\t\tthrow error;\n\t} finally {\n\t\tspan.end();\n\t}\n}\n\n/**\n * Check if tracing is enabled (OpenTelemetry API is available and configured)\n */\nexport function isTracingEnabled(): boolean {\n\ttry {\n\t\tconst tracer = trace.getTracer(TRACER_NAME);\n\t\t// Check if we have a real tracer (not a no-op)\n\t\tconst span = tracer.startSpan('test');\n\t\tconst isReal =\n\t\t\tspan.spanContext().traceId !== '00000000000000000000000000000000';\n\t\tspan.end();\n\t\treturn isReal;\n\t} catch {\n\t\treturn false;\n\t}\n}\n"],"mappings":";;AA8DA,MAAM,cAAc;;;;AAKpB,SAAgB,sBAAsB;CACrC,OAAO,MAAM,UAAU,WAAW;AACnC;;;;AAKA,SAAgB,iBAAiB,OAAuC;CACvE,MAAM,YAAwB,CAAC;CAG/B,IAAI,MAAM,QAAQ,UAAU,yBAAyB,MAAM;CAC3D,IAAI,MAAM,KAAK,UAAU,cAAc,MAAM;CAC7C,IAAI,MAAM,MAAM,UAAU,cAAc,MAAM;CAC9C,IAAI,MAAM,OAAO,UAAU,gBAAgB,MAAM;CACjD,IAAI,MAAM,MAAM,UAAU,oBAAoB,MAAM;CACpD,IAAI,MAAM,QAAQ,UAAU,gBAAgB,MAAM;CAClD,IAAI,MAAM,WAAW,UAAU,yBAAyB,MAAM;CAC9D,IAAI,MAAM,UAAU,UAAU,oBAAoB,MAAM;CACxD,IAAI,MAAM,WAAW,UAAU,qBAAqB,MAAM;CAG1D,IAAI,MAAM,UAAU,YACnB,UAAU,+BAA+B,MAAM,SAAS;CAEzD,IAAI,MAAM,UAAU,cACnB,UAAU,6BAA6B,MAAM,SAAS;CAIvD,IAAI,MAAM,UAAU,MAAM,UAAU,mBAAmB,MAAM,SAAS;CACtE,IAAI,MAAM,UAAU,aACnB,UAAU,2BAA2B,MAAM,SAAS;CAErD,IAAI,MAAM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;AAKA,SAAgB,mBAA4B;CAC3C,IAAI;EAGH,MAAM,OAFS,MAAM,UAAU,WAEb,CAAC,CAAC,UAAU,MAAM;EACpC,MAAM,SACL,KAAK,YAAY,CAAC,CAAC,YAAY;EAChC,KAAK,IAAI;EACT,OAAO;CACR,QAAQ;EACP,OAAO;CACR;AACD"}
1
+ {"version":3,"file":"http.mjs","names":[],"sources":["../../src/instrumentation/http.ts"],"sourcesContent":["import {\n\ttype Attributes,\n\ttype Context,\n\tcontext,\n\tisSpanContextValid,\n\ttype Link,\n\tpropagation,\n\ttype Span,\n\tSpanKind,\n\tSpanStatusCode,\n\ttrace,\n} from '@opentelemetry/api';\n\n/**\n * HTTP request attributes following OpenTelemetry semantic conventions\n */\nexport interface HttpRequestAttributes {\n\tmethod: string;\n\turl?: string;\n\tpath?: string;\n\troute?: string;\n\thost?: string;\n\tscheme?: 'http' | 'https';\n\tuserAgent?: string;\n\tclientIp?: string;\n\trequestId?: string;\n}\n\n/**\n * HTTP response attributes\n */\nexport interface HttpResponseAttributes {\n\tstatusCode: number;\n\tresponseSize?: number;\n}\n\n/**\n * Endpoint-specific attributes\n */\nexport interface EndpointAttributes {\n\tname?: string;\n\toperationId?: string;\n\ttags?: string[];\n}\n\n/**\n * User/session attributes\n */\nexport interface UserAttributes {\n\tuserId?: string;\n\tsessionId?: string;\n\troles?: string[];\n}\n\n/**\n * Full span attributes for HTTP requests\n */\nexport interface HttpSpanAttributes extends HttpRequestAttributes {\n\tresponse?: HttpResponseAttributes;\n\tendpoint?: EndpointAttributes;\n\tuser?: UserAttributes;\n\tcustom?: Attributes;\n}\n\nconst TRACER_NAME = '@geekmidas/constructs';\n\n/**\n * Get or create a tracer for constructs instrumentation\n */\nexport function getConstructsTracer() {\n\treturn trace.getTracer(TRACER_NAME);\n}\n\n/**\n * Convert HTTP attributes to OpenTelemetry semantic conventions\n */\nexport function toOtelAttributes(attrs: HttpSpanAttributes): Attributes {\n\tconst otelAttrs: Attributes = {};\n\n\t// HTTP request attributes (OpenTelemetry semantic conventions)\n\tif (attrs.method) otelAttrs['http.request.method'] = attrs.method;\n\tif (attrs.url) otelAttrs['url.full'] = attrs.url;\n\tif (attrs.path) otelAttrs['url.path'] = attrs.path;\n\tif (attrs.route) otelAttrs['http.route'] = attrs.route;\n\tif (attrs.host) otelAttrs['server.address'] = attrs.host;\n\tif (attrs.scheme) otelAttrs['url.scheme'] = attrs.scheme;\n\tif (attrs.userAgent) otelAttrs['user_agent.original'] = attrs.userAgent;\n\tif (attrs.clientIp) otelAttrs['client.address'] = attrs.clientIp;\n\tif (attrs.requestId) otelAttrs['http.request.id'] = attrs.requestId;\n\n\t// HTTP response attributes\n\tif (attrs.response?.statusCode) {\n\t\totelAttrs['http.response.status_code'] = attrs.response.statusCode;\n\t}\n\tif (attrs.response?.responseSize) {\n\t\totelAttrs['http.response.body.size'] = attrs.response.responseSize;\n\t}\n\n\t// Endpoint attributes\n\tif (attrs.endpoint?.name) otelAttrs['endpoint.name'] = attrs.endpoint.name;\n\tif (attrs.endpoint?.operationId) {\n\t\totelAttrs['endpoint.operation_id'] = attrs.endpoint.operationId;\n\t}\n\tif (attrs.endpoint?.tags?.length) {\n\t\totelAttrs['endpoint.tags'] = attrs.endpoint.tags;\n\t}\n\n\t// User attributes\n\tif (attrs.user?.userId) otelAttrs['enduser.id'] = attrs.user.userId;\n\tif (attrs.user?.sessionId) otelAttrs['session.id'] = attrs.user.sessionId;\n\tif (attrs.user?.roles?.length)\n\t\totelAttrs['enduser.role'] = attrs.user.roles.join(',');\n\n\t// Custom attributes\n\tif (attrs.custom) {\n\t\tObject.assign(otelAttrs, attrs.custom);\n\t}\n\n\treturn otelAttrs;\n}\n\n/**\n * Extract trace context from HTTP headers\n */\nexport function extractTraceContext(\n\theaders: Record<string, string | string[] | undefined>,\n): Context {\n\t// Normalize headers to Record<string, string>\n\tconst normalizedHeaders: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tif (value) {\n\t\t\tconst stringValue = Array.isArray(value) ? value[0] : value;\n\t\t\tif (stringValue) {\n\t\t\t\tnormalizedHeaders[key.toLowerCase()] = stringValue;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn propagation.extract(context.active(), normalizedHeaders);\n}\n\n/** Where a request's span goes: under a parent, or a new root with links. */\nexport interface IncomingTraceContext {\n\t/** The context the request span starts in. */\n\tparent: Context;\n\t/** The untrusted caller's context, linked rather than continued. */\n\tlinks: Link[];\n}\n\n/**\n * The trace a request's span belongs to.\n *\n * From a trusted caller (see `./trust`) its `traceparent` is continued, and\n * the span is its child. From anyone else the span starts a new trace — no\n * parent, no baggage — with a link to the context the caller claimed, so the\n * hop can still be followed without the caller choosing this trace.\n */\nexport function incomingTraceContext(\n\theaders: Record<string, string | string[] | undefined>,\n\ttrusted: boolean,\n): IncomingTraceContext {\n\tconst extracted = extractTraceContext(headers);\n\tif (trusted) return { parent: extracted, links: [] };\n\n\tconst claimed = trace.getSpanContext(extracted);\n\treturn {\n\t\tparent: trace.deleteSpan(context.active()),\n\t\tlinks:\n\t\t\tclaimed && isSpanContextValid(claimed)\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext: claimed,\n\t\t\t\t\t\t\tattributes: { 'gkm.trace.untrusted_parent': true },\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t};\n}\n\n/**\n * Inject trace context into HTTP headers\n */\nexport function injectTraceContext(\n\theaders: Record<string, string>,\n\tctx?: Context,\n): Record<string, string> {\n\tconst result = { ...headers };\n\tpropagation.inject(ctx ?? context.active(), result);\n\treturn result;\n}\n\n/**\n * Create an HTTP server span for an incoming request\n */\nexport function createHttpServerSpan(\n\tattrs: HttpSpanAttributes,\n\tparentContext?: Context,\n\tlinks?: Link[],\n): Span {\n\tconst tracer = getConstructsTracer();\n\tconst spanName = attrs.route\n\t\t? `${attrs.method} ${attrs.route}`\n\t\t: `${attrs.method} ${attrs.path || '/'}`;\n\n\tconst ctx = parentContext ?? context.active();\n\n\treturn tracer.startSpan(\n\t\tspanName,\n\t\t{\n\t\t\tkind: SpanKind.SERVER,\n\t\t\tattributes: toOtelAttributes(attrs),\n\t\t\t...(links?.length ? { links } : {}),\n\t\t},\n\t\tctx,\n\t);\n}\n\n/**\n * End an HTTP span with response data\n */\nexport function endHttpSpan(\n\tspan: Span,\n\tresponse: HttpResponseAttributes,\n\terror?: Error,\n): void {\n\tspan.setAttribute('http.response.status_code', response.statusCode);\n\n\tif (response.responseSize) {\n\t\tspan.setAttribute('http.response.body.size', response.responseSize);\n\t}\n\n\tif (error) {\n\t\tspan.recordException(error);\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: error.message,\n\t\t});\n\t} else if (response.statusCode >= 500) {\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: `HTTP ${response.statusCode}`,\n\t\t});\n\t} else if (response.statusCode < 400) {\n\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t}\n\t// A 4xx leaves the status unset: on a server span it is the client's\n\t// mistake, not the server's failure (HTTP semantic conventions).\n\n\tspan.end();\n}\n\n/**\n * Execute a function within an HTTP server span context\n *\n * @example\n * ```typescript\n * const result = await withHttpSpan(\n * { method: 'GET', path: '/users', route: '/users' },\n * async (span) => {\n * const users = await getUsers();\n * return { statusCode: 200, body: users };\n * }\n * );\n * ```\n */\nexport async function withHttpSpan<T>(\n\tattrs: HttpSpanAttributes,\n\tfn: (span: Span) => Promise<T & { statusCode?: number }>,\n\tparentContext?: Context,\n): Promise<T> {\n\tconst span = createHttpServerSpan(attrs, parentContext);\n\n\ttry {\n\t\tconst result = await context.with(\n\t\t\ttrace.setSpan(parentContext ?? context.active(), span),\n\t\t\t() => fn(span),\n\t\t);\n\n\t\tconst statusCode = (result as { statusCode?: number }).statusCode ?? 200;\n\t\tendHttpSpan(span, { statusCode });\n\n\t\treturn result;\n\t} catch (error) {\n\t\tendHttpSpan(\n\t\t\tspan,\n\t\t\t{ statusCode: 500 },\n\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Create a child span for internal operations (middleware, handlers, etc.)\n */\nexport function createChildSpan(name: string, attributes?: Attributes): Span {\n\tconst tracer = getConstructsTracer();\n\treturn tracer.startSpan(name, {\n\t\tkind: SpanKind.INTERNAL,\n\t\tattributes,\n\t});\n}\n\n/**\n * Execute a function within a child span\n */\nexport async function withChildSpan<T>(\n\tname: string,\n\tfn: (span: Span) => Promise<T>,\n\tattributes?: Attributes,\n): Promise<T> {\n\tconst span = createChildSpan(name, attributes);\n\n\ttry {\n\t\tconst result = await context.with(\n\t\t\ttrace.setSpan(context.active(), span),\n\t\t\t() => fn(span),\n\t\t);\n\t\tspan.setStatus({ code: SpanStatusCode.OK });\n\t\treturn result;\n\t} catch (error) {\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: error instanceof Error ? error.message : 'Unknown error',\n\t\t});\n\t\tspan.recordException(\n\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t);\n\t\tthrow error;\n\t} finally {\n\t\tspan.end();\n\t}\n}\n\n/**\n * Check if tracing is enabled (OpenTelemetry API is available and configured)\n */\nexport function isTracingEnabled(): boolean {\n\ttry {\n\t\tconst tracer = trace.getTracer(TRACER_NAME);\n\t\t// Check if we have a real tracer (not a no-op)\n\t\tconst span = tracer.startSpan('test');\n\t\tconst isReal =\n\t\t\tspan.spanContext().traceId !== '00000000000000000000000000000000';\n\t\tspan.end();\n\t\treturn isReal;\n\t} catch {\n\t\treturn false;\n\t}\n}\n"],"mappings":";;AAgEA,MAAM,cAAc;;;;AAKpB,SAAgB,sBAAsB;CACrC,OAAO,MAAM,UAAU,WAAW;AACnC;;;;AAKA,SAAgB,iBAAiB,OAAuC;CACvE,MAAM,YAAwB,CAAC;CAG/B,IAAI,MAAM,QAAQ,UAAU,yBAAyB,MAAM;CAC3D,I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10 +2,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_instrumentation_core = require("./core.cjs");
3
3
  const require_instrumentation_tracing = require("./tracing.cjs");
4
4
  const require_instrumentation_http = require("./http.cjs");
5
+ const require_instrumentation_trust = require("./trust.cjs");
5
6
  const require_instrumentation_hono = require("./hono.cjs");
6
7
  const require_instrumentation_middleware = require("./middleware.cjs");
7
8
  const require_instrumentation_otel = require("./otel.cjs");
9
+ const require_instrumentation_sampler = require("./sampler.cjs");
8
10
  const require_instrumentation_setup = require("./setup.cjs");
11
+ exports.InvalidSampleRatio = require_instrumentation_setup.InvalidSampleRatio;
9
12
  exports.NoopSpanProcessor = require_instrumentation_core.NoopSpanProcessor;
10
13
  exports.OTelTelemetry = require_instrumentation_otel.OTelTelemetry;
11
14
  exports.addSpanEvent = require_instrumentation_tracing.addSpanEvent;
@@ -27,9 +30,13 @@ exports.getSpanId = require_instrumentation_tracing.getSpanId;
27
30
  exports.getTraceContextFromHono = require_instrumentation_hono.getTraceContextFromHono;
28
31
  exports.getTraceId = require_instrumentation_tracing.getTraceId;
29
32
  exports.honoTelemetryMiddleware = require_instrumentation_hono.honoTelemetryMiddleware;
33
+ exports.incomingTraceContext = require_instrumentation_http.incomingTraceContext;
30
34
  exports.injectTraceContext = require_instrumentation_http.injectTraceContext;
35
+ exports.isInternalCaller = require_instrumentation_trust.isInternalCaller;
36
+ exports.isPrivateAddress = require_instrumentation_trust.isPrivateAddress;
31
37
  exports.isTelemetryInitialized = require_instrumentation_core.isTelemetryInitialized;
32
38
  exports.isTracingEnabled = require_instrumentation_http.isTracingEnabled;
39
+ exports.isTrustedOrigin = require_instrumentation_trust.isTrustedOrigin;
33
40
  exports.recordException = require_instrumentation_tracing.recordException;
34
41
  exports.setGlobalLogProcessor = require_instrumentation_core.setGlobalLogProcessor;
35
42
  exports.setGlobalSpanProcessor = require_instrumentation_core.setGlobalSpanProcessor;
@@ -38,6 +45,8 @@ exports.setupTelemetry = require_instrumentation_setup.setupTelemetry;
38
45
  exports.shutdownTelemetry = require_instrumentation_setup.shutdownTelemetry;
39
46
  exports.telemetryMiddleware = require_instrumentation_middleware.telemetryMiddleware;
40
47
  exports.toOtelAttributes = require_instrumentation_http.toOtelAttributes;
48
+ exports.traceSampler = require_instrumentation_sampler.traceSampler;
49
+ exports.traceSamplerFromEnv = require_instrumentation_sampler.traceSamplerFromEnv;
41
50
  exports.withChildSpan = require_instrumentation_http.withChildSpan;
42
51
  exports.withEventContext = require_instrumentation_middleware.withEventContext;
43
52
  exports.withHonoSpanContext = require_instrumentation_hono.withHonoSpanContext;
@@ -2,8 +2,10 @@ import { SpanProcessorOptions, SpanProcessorStrategy } from "../adapters/types.c
2
2
  import { NoopSpanProcessor, createSpanProcessor, enableTelemetryDebug, flushTelemetry, getRecommendedStrategy, isTelemetryInitialized, setGlobalLogProcessor, setGlobalSpanProcessor, withTelemetryFlush } from "./core.cjs";
3
3
  import { addSpanEvent, createSpan, getActiveSpan, getSpanId, getTraceId, recordException, setSpanAttributes, withSpan, withSpanSync } from "./tracing.cjs";
4
4
  import { HonoTelemetryMiddlewareOptions, getSpanFromContext, getTraceContextFromHono, honoTelemetryMiddleware, withHonoSpanContext } from "./hono.cjs";
5
- import { EndpointAttributes, HttpRequestAttributes, HttpResponseAttributes, HttpSpanAttributes, UserAttributes, createChildSpan, createHttpServerSpan, endHttpSpan, extractTraceContext, getConstructsTracer, injectTraceContext, isTracingEnabled, toOtelAttributes, withChildSpan, withHttpSpan } from "./http.cjs";
5
+ import { EndpointAttributes, HttpRequestAttributes, HttpResponseAttributes, HttpSpanAttributes, IncomingTraceContext, UserAttributes, createChildSpan, createHttpServerSpan, endHttpSpan, extractTraceContext, getConstructsTracer, incomingTraceContext, injectTraceContext, isTracingEnabled, toOtelAttributes, withChildSpan, withHttpSpan } from "./http.cjs";
6
6
  import { TelemetryMiddlewareOptions, getContextFromEvent, getSpanFromEvent, telemetryMiddleware, withEventContext } from "./middleware.cjs";
7
7
  import { OTelTelemetry, OTelTelemetryOptions } from "./otel.cjs";
8
- import { TelemetryOptions, setupTelemetry, shutdownTelemetry } from "./setup.cjs";
9
- export { type EndpointAttributes, type HonoTelemetryMiddlewareOptions, type HttpRequestAttributes, type HttpResponseAttributes, type HttpSpanAttributes, NoopSpanProcessor, OTelTelemetry, type OTelTelemetryOptions, type SpanProcessorOptions, type SpanProcessorStrategy, type TelemetryMiddlewareOptions, type TelemetryOptions, type UserAttributes, addSpanEvent, createChildSpan, createHttpServerSpan, createSpan, createSpanProcessor, enableTelemetryDebug, endHttpSpan, extractTraceContext, flushTelemetry, getActiveSpan, getConstructsTracer, getContextFromEvent, getRecommendedStrategy, getSpanFromContext, getSpanFromEvent, getSpanId, getTraceContextFromHono, getTraceId, honoTelemetryMiddleware, injectTraceContext, isTelemetryInitialized, isTracingEnabled, recordException, setGlobalLogProcessor, setGlobalSpanProcessor, setSpanAttributes, setupTelemetry, shutdownTelemetry, telemetryMiddleware, toOtelAttributes, withChildSpan, withEventContext, withHonoSpanContext, withHttpSpan, withSpan, withSpanSync, withTelemetryFlush };
8
+ import { traceSampler, traceSamplerFromEnv } from "./sampler.cjs";
9
+ import { InvalidSampleRatio, TelemetryOptions, setupTelemetry, shutdownTelemetry } from "./setup.cjs";
10
+ import { IncomingRequestFacts, isInternalCaller, isPrivateAddress, isTrustedOrigin } from "./trust.cjs";
11
+ export { type EndpointAttributes, type HonoTelemetryMiddlewareOptions, type HttpRequestAttributes, type HttpResponseAttributes, type HttpSpanAttributes, type IncomingRequestFacts, type IncomingTraceContext, InvalidSampleRatio, NoopSpanProcessor, OTelTelemetry, type OTelTelemetryOptions, type SpanProcessorOptions, type SpanProcessorStrategy, type TelemetryMiddlewareOptions, type TelemetryOptions, type UserAttributes, addSpanEvent, createChildSpan, createHttpServerSpan, createSpan, createSpanProcessor, enableTelemetryDebug, endHttpSpan, extractTraceContext, flushTelemetry, getActiveSpan, getConstructsTracer, getContextFromEvent, getRecommendedStrategy, getSpanFromContext, getSpanFromEvent, getSpanId, getTraceContextFromHono, getTraceId, honoTelemetryMiddleware, incomingTraceContext, injectTraceContext, isInternalCaller, isPrivateAddress, isTelemetryInitialized, isTracingEnabled, isTrustedOrigin, recordException, setGlobalLogProcessor, setGlobalSpanProcessor, setSpanAttributes, setupTelemetry, shutdownTelemetry, telemetryMiddleware, toOtelAttributes, traceSampler, traceSamplerFromEnv, withChildSpan, withEventContext, withHonoSpanContext, withHttpSpan, withSpan, withSpanSync, withTelemetryFlush };
@@ -2,8 +2,10 @@ import { SpanProcessorOptions, SpanProcessorStrategy } from "../adapters/types.m
2
2
  import { NoopSpanProcessor, createSpanProcessor, enableTelemetryDebug, flushTelemetry, getRecommendedStrategy, isTelemetryInitialized, setGlobalLogProcessor, setGlobalSpanProcessor, withTelemetryFlush } from "./core.mjs";
3
3
  import { addSpanEvent, createSpan, getActiveSpan, getSpanId, getTraceId, recordException, setSpanAttributes, withSpan, withSpanSync } from "./tracing.mjs";
4
4
  import { HonoTelemetryMiddlewareOptions, getSpanFromContext, getTraceContextFromHono, honoTelemetryMiddleware, withHonoSpanContext } from "./hono.mjs";
5
- import { EndpointAttributes, HttpRequestAttributes, HttpResponseAttributes, HttpSpanAttributes, UserAttributes, createChildSpan, createHttpServerSpan, endHttpSpan, extractTraceContext, getConstructsTracer, injectTraceContext, isTracingEnabled, toOtelAttributes, withChildSpan, withHttpSpan } from "./http.mjs";
5
+ import { EndpointAttributes, HttpRequestAttributes, HttpResponseAttributes, HttpSpanAttributes, IncomingTraceContext, UserAttributes, createChildSpan, createHttpServerSpan, endHttpSpan, extractTraceContext, getConstructsTracer, incomingTraceContext, injectTraceContext, isTracingEnabled, toOtelAttributes, withChildSpan, withHttpSpan } from "./http.mjs";
6
6
  import { TelemetryMiddlewareOptions, getContextFromEvent, getSpanFromEvent, telemetryMiddleware, withEventContext } from "./middleware.mjs";
7
7
  import { OTelTelemetry, OTelTelemetryOptions } from "./otel.mjs";
8
- import { TelemetryOptions, setupTelemetry, shutdownTelemetry } from "./setup.mjs";
9
- export { type EndpointAttributes, type HonoTelemetryMiddlewareOptions, type HttpRequestAttributes, type HttpResponseAttributes, type HttpSpanAttributes, NoopSpanProcessor, OTelTelemetry, type OTelTelemetryOptions, type SpanProcessorOptions, type SpanProcessorStrategy, type TelemetryMiddlewareOptions, type TelemetryOptions, type UserAttributes, addSpanEvent, createChildSpan, createHttpServerSpan, createSpan, createSpanProcessor, enableTelemetryDebug, endHttpSpan, extractTraceContext, flushTelemetry, getActiveSpan, getConstructsTracer, getContextFromEvent, getRecommendedStrategy, getSpanFromContext, getSpanFromEvent, getSpanId, getTraceContextFromHono, getTraceId, honoTelemetryMiddleware, injectTraceContext, isTelemetryInitialized, isTracingEnabled, recordException, setGlobalLogProcessor, setGlobalSpanProcessor, setSpanAttributes, setupTelemetry, shutdownTelemetry, telemetryMiddleware, toOtelAttributes, withChildSpan, withEventContext, withHonoSpanContext, withHttpSpan, withSpan, withSpanSync, withTelemetryFlush };
8
+ import { traceSampler, traceSamplerFromEnv } from "./sampler.mjs";
9
+ import { InvalidSampleRatio, TelemetryOptions, setupTelemetry, shutdownTelemetry } from "./setup.mjs";
10
+ import { IncomingRequestFacts, isInternalCaller, isPrivateAddress, isTrustedOrigin } from "./trust.mjs";
11
+ export { type EndpointAttributes, type HonoTelemetryMiddlewareOptions, type HttpRequestAttributes, type HttpResponseAttributes, type HttpSpanAttributes, type IncomingRequestFacts, type IncomingTraceContext, InvalidSampleRatio, NoopSpanProcessor, OTelTelemetry, type OTelTelemetryOptions, type SpanProcessorOptions, type SpanProcessorStrategy, type TelemetryMiddlewareOptions, type TelemetryOptions, type UserAttributes, addSpanEvent, createChildSpan, createHttpServerSpan, createSpan, createSpanProcessor, enableTelemetryDebug, endHttpSpan, extractTraceContext, flushTelemetry, getActiveSpan, getConstructsTracer, getContextFromEvent, getRecommendedStrategy, getSpanFromContext, getSpanFromEvent, getSpanId, getTraceContextFromHono, getTraceId, honoTelemetryMiddleware, incomingTraceContext, injectTraceContext, isInternalCaller, isPrivateAddress, isTelemetryInitialized, isTracingEnabled, isTrustedOrigin, recordException, setGlobalLogProcessor, setGlobalSpanProcessor, setSpanAttributes, setupTelemetry, shutdownTelemetry, telemetryMiddleware, toOtelAttributes, traceSampler, traceSamplerFromEnv, withChildSpan, withEventContext, withHonoSpanContext, withHttpSpan, withSpan, withSpanSync, withTelemetryFlush };
@@ -1,8 +1,10 @@
1
1
  import { NoopSpanProcessor, createSpanProcessor, enableTelemetryDebug, flushTelemetry, getRecommendedStrategy, isTelemetryInitialized, setGlobalLogProcessor, setGlobalSpanProcessor, withTelemetryFlush } from "./core.mjs";
2
2
  import { addSpanEvent, createSpan, getActiveSpan, getSpanId, getTraceId, recordException, setSpanAttributes, withSpan, withSpanSync } from "./tracing.mjs";
3
- import { createChildSpan, createHttpServerSpan, endHttpSpan, extractTraceContext, getConstructsTracer, injectTraceContext, isTracingEnabled, toOtelAttributes, withChildSpan, withHttpSpan } from "./http.mjs";
3
+ import { createChildSpan, createHttpServerSpan, endHttpSpan, extractTraceContext, getConstructsTracer, incomingTraceContext, injectTraceContext, isTracingEnabled, toOtelAttributes, withChildSpan, withHttpSpan } from "./http.mjs";
4
+ import { isInternalCaller, isPrivateAddress, isTrustedOrigin } from "./trust.mjs";
4
5
  import { getSpanFromContext, getTraceContextFromHono, honoTelemetryMiddleware, withHonoSpanContext } from "./hono.mjs";
5
6
  import { getContextFromEvent, getSpanFromEvent, telemetryMiddleware, withEventContext } from "./middleware.mjs";
6
7
  import { OTelTelemetry } from "./otel.mjs";
7
- import { setupTelemetry, shutdownTelemetry } from "./setup.mjs";
8
- export { NoopSpanProcessor, OTelTelemetry, addSpanEvent, createChildSpan, createHttpServerSpan, createSpan, createSpanProcessor, enableTelemetryDebug, endHttpSpan, extractTraceContext, flushTelemetry, getActiveSpan, getConstructsTracer, getContextFromEvent, getRecommendedStrategy, getSpanFromContext, getSpanFromEvent, getSpanId, getTraceContextFromHono, getTraceId, honoTelemetryMiddleware, injectTraceContext, isTelemetryInitialized, isTracingEnabled, recordException, setGlobalLogProcessor, setGlobalSpanProcessor, setSpanAttributes, setupTelemetry, shutdownTelemetry, telemetryMiddleware, toOtelAttributes, withChildSpan, withEventContext, withHonoSpanContext, withHttpSpan, withSpan, withSpanSync, withTelemetryFlush };
8
+ import { traceSampler, traceSamplerFromEnv } from "./sampler.mjs";
9
+ import { InvalidSampleRatio, setupTelemetry, shutdownTelemetry } from "./setup.mjs";
10
+ export { InvalidSampleRatio, NoopSpanProcessor, OTelTelemetry, addSpanEvent, createChildSpan, createHttpServerSpan, createSpan, createSpanProcessor, enableTelemetryDebug, endHttpSpan, extractTraceContext, flushTelemetry, getActiveSpan, getConstructsTracer, getContextFromEvent, getRecommendedStrategy, getSpanFromContext, getSpanFromEvent, getSpanId, getTraceContextFromHono, getTraceId, honoTelemetryMiddleware, incomingTraceContext, injectTraceContext, isInternalCaller, isPrivateAddress, isTelemetryInitialized, isTracingEnabled, isTrustedOrigin, recordException, setGlobalLogProcessor, setGlobalSpanProcessor, setSpanAttributes, setupTelemetry, shutdownTelemetry, telemetryMiddleware, toOtelAttributes, traceSampler, traceSamplerFromEnv, withChildSpan, withEventContext, withHonoSpanContext, withHttpSpan, withSpan, withSpanSync, withTelemetryFlush };
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_instrumentation_http = require("./http.cjs");
3
+ const require_instrumentation_trust = require("./trust.cjs");
3
4
  let _opentelemetry_api = require("@opentelemetry/api");
4
5
  //#region src/instrumentation/middleware.ts
5
6
  const SPAN_SYMBOL = Symbol("telemetry.span");
@@ -35,9 +36,10 @@ function telemetryMiddleware(options = {}) {
35
36
  const event = request.event;
36
37
  const lambdaContext = request.context;
37
38
  const headers = normalizeHeaders(event.headers || {});
38
- const parentContext = require_instrumentation_http.extractTraceContext(headers);
39
+ const trusted = require_instrumentation_trust.isTrustedOrigin(typeof headers.origin === "string" ? headers.origin : void 0, options.trustedOrigins) || Boolean(options.trustRequest?.(event));
40
+ const { parent: parentContext, links } = require_instrumentation_http.incomingTraceContext(headers, trusted);
39
41
  const attrs = buildSpanAttributes(event, lambdaContext, options);
40
- const span = require_instrumentation_http.createHttpServerSpan(attrs, parentContext);
42
+ const span = require_instrumentation_http.createHttpServerSpan(attrs, parentContext, links);
41
43
  event[SPAN_SYMBOL] = span;
42
44
  event[CONTEXT_SYMBOL] = _opentelemetry_api.trace.setSpan(parentContext, span);
43
45
  span.setAttribute("faas.invocation_id", lambdaContext.awsRequestId);
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.cjs","names":["extractTraceContext","createHttpServerSpan","trace","context"],"sources":["../../src/instrumentation/middleware.ts"],"sourcesContent":["/**\n * OpenTelemetry instrumentation middleware for @geekmidas/constructs\n *\n * This middleware automatically creates spans for HTTP requests,\n * extracts trace context from incoming headers, and records\n * request/response metadata as span attributes.\n */\nimport type { MiddlewareObj } from '@middy/core';\nimport { context, type Span, trace } from '@opentelemetry/api';\nimport type { Context as LambdaContext } from 'aws-lambda';\nimport {\n\tcreateHttpServerSpan,\n\tendHttpSpan,\n\textractTraceContext,\n\ttype HttpSpanAttributes,\n} from './http';\n\n/**\n * Options for the telemetry middleware\n */\nexport interface TelemetryMiddlewareOptions {\n\t/**\n\t * Whether to record request body as span attribute\n\t * @default false\n\t */\n\trecordBody?: boolean;\n\n\t/**\n\t * Whether to record response body as span attribute\n\t * @default false\n\t */\n\trecordResponseBody?: boolean;\n\n\t/**\n\t * Custom function to extract endpoint name from event\n\t */\n\tgetEndpointName?: (event: any) => string | undefined;\n\n\t/**\n\t * Custom function to extract operation ID from event\n\t */\n\tgetOperationId?: (event: any) => string | undefined;\n\n\t/**\n\t * Custom function to extract user ID from event\n\t */\n\tgetUserId?: (event: any) => string | undefined;\n\n\t/**\n\t * Whether to skip tracing for this request\n\t */\n\tshouldSkip?: (event: any) => boolean;\n}\n\n// Symbol for storing span on event\nconst SPAN_SYMBOL = Symbol('telemetry.span');\nconst CONTEXT_SYMBOL = Symbol('telemetry.context');\n\n/**\n * Get the current span from the Lambda event\n */\nexport function getSpanFromEvent(event: any): Span | undefined {\n\treturn event?.[SPAN_SYMBOL];\n}\n\n/**\n * Get the current trace context from the Lambda event\n */\nexport function getContextFromEvent(event: any): any {\n\treturn event?.[CONTEXT_SYMBOL];\n}\n\n/**\n * Create a telemetry middleware for Lambda handlers\n *\n * @example\n * ```typescript\n * import { telemetryMiddleware } from '@geekmidas/telescope/instrumentation';\n *\n * const adaptor = new AmazonApiGatewayV2Endpoint(endpoint, {\n * telemetry: { middleware: telemetryMiddleware() },\n * });\n * ```\n */\nexport function telemetryMiddleware(\n\toptions: TelemetryMiddlewareOptions = {},\n): MiddlewareObj<any, any, Error, LambdaContext> {\n\treturn {\n\t\tbefore: async (request) => {\n\t\t\t// Skip if custom skip function returns true\n\t\t\tif (options.shouldSkip?.(request.event)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst event = request.event;\n\t\t\tconst lambdaContext = request.context;\n\n\t\t\t// Extract trace context from headers\n\t\t\tconst headers = normalizeHeaders(event.headers || {});\n\t\t\tconst parentContext = extractTraceContext(headers);\n\n\t\t\t// Build span attributes from event\n\t\t\tconst attrs = buildSpanAttributes(event, lambdaContext, options);\n\n\t\t\t// Create the span\n\t\t\tconst span = createHttpServerSpan(attrs, parentContext);\n\n\t\t\t// Store span and context on event for access in handler\n\t\t\tevent[SPAN_SYMBOL] = span;\n\t\t\tevent[CONTEXT_SYMBOL] = trace.setSpan(parentContext, span);\n\n\t\t\t// Add Lambda-specific attributes\n\t\t\tspan.setAttribute('faas.invocation_id', lambdaContext.awsRequestId);\n\t\t\tspan.setAttribute('faas.name', lambdaContext.functionName);\n\n\t\t\tif (options.recordBody && event.body) {\n\t\t\t\tconst bodyStr =\n\t\t\t\t\ttypeof event.body === 'string'\n\t\t\t\t\t\t? event.body\n\t\t\t\t\t\t: JSON.stringify(event.body);\n\t\t\t\t// Truncate large bodies\n\t\t\t\tspan.setAttribute(\n\t\t\t\t\t'http.request.body',\n\t\t\t\t\tbodyStr.length > 4096 ? `${bodyStr.slice(0, 4096)}...` : bodyStr,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\n\t\tafter: async (request) => {\n\t\t\tconst span = getSpanFromEvent(request.event);\n\t\t\tif (!span) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst response = request.response;\n\t\t\tconst statusCode =\n\t\t\t\ttypeof response?.statusCode === 'number' ? response.statusCode : 200;\n\n\t\t\tif (options.recordResponseBody && response?.body) {\n\t\t\t\tconst bodyStr =\n\t\t\t\t\ttypeof response.body === 'string'\n\t\t\t\t\t\t? response.body\n\t\t\t\t\t\t: JSON.stringify(response.body);\n\t\t\t\tspan.setAttribute(\n\t\t\t\t\t'http.response.body',\n\t\t\t\t\tbodyStr.length > 4096 ? `${bodyStr.slice(0, 4096)}...` : bodyStr,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tendHttpSpan(span, { statusCode });\n\t\t},\n\n\t\tonError: async (request) => {\n\t\t\tconst span = getSpanFromEvent(request.event);\n\t\t\tif (!span) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst error = request.error;\n\t\t\tconst response = request.response;\n\n\t\t\t// Determine status code from response or error\n\t\t\tlet statusCode = 500;\n\t\t\tif (response?.statusCode) {\n\t\t\t\tstatusCode = response.statusCode;\n\t\t\t} else if (error && 'statusCode' in error) {\n\t\t\t\tstatusCode = (error as any).statusCode;\n\t\t\t}\n\n\t\t\tendHttpSpan(\n\t\t\t\tspan,\n\t\t\t\t{ statusCode },\n\t\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Build span attributes from Lambda event\n */\nfunction buildSpanAttributes(\n\tevent: any,\n\tlambdaContext: LambdaContext,\n\toptions: TelemetryMiddlewareOptions,\n): HttpSpanAttributes {\n\t// Detect event type (API Gateway v1, v2, ALB, or direct invoke)\n\tconst isV2 =\n\t\t'requestContext' in event && 'http' in (event.requestContext || {});\n\tconst isV1 =\n\t\t'requestContext' in event &&\n\t\t'httpMethod' in event &&\n\t\t!('http' in (event.requestContext || {}));\n\n\tlet method = 'INVOKE';\n\tlet path = '/';\n\tlet route: string | undefined;\n\tlet host: string | undefined;\n\tlet scheme: 'http' | 'https' | undefined;\n\tlet userAgent: string | undefined;\n\tlet clientIp: string | undefined;\n\tlet requestId: string | undefined;\n\n\tif (isV2) {\n\t\t// API Gateway v2 (HTTP API)\n\t\tconst http = event.requestContext.http;\n\t\tmethod = http.method;\n\t\tpath = event.rawPath || http.path;\n\t\troute = event.routeKey?.replace(/^[A-Z]+\\s+/, ''); // Remove HTTP method prefix\n\t\thost = event.headers?.host;\n\t\tscheme = 'https';\n\t\tuserAgent = http.userAgent;\n\t\tclientIp = http.sourceIp;\n\t\trequestId = event.requestContext.requestId;\n\t} else if (isV1) {\n\t\t// API Gateway v1 (REST API)\n\t\tmethod = event.httpMethod;\n\t\tpath = event.path;\n\t\troute = event.resource;\n\t\thost = event.headers?.Host || event.headers?.host;\n\t\tscheme = 'https';\n\t\tuserAgent = event.headers?.['User-Agent'] || event.headers?.['user-agent'];\n\t\tclientIp = event.requestContext?.identity?.sourceIp;\n\t\trequestId = event.requestContext?.requestId;\n\t} else if ('httpMethod' in event) {\n\t\t// ALB event\n\t\tmethod = event.httpMethod;\n\t\tpath = event.path;\n\t\thost = event.headers?.host;\n\t\tuserAgent = event.headers?.['user-agent'] || event.headers?.['User-Agent'];\n\t\tclientIp = event.headers?.['x-forwarded-for']?.split(',')[0]?.trim();\n\t}\n\n\tconst attrs: HttpSpanAttributes = {\n\t\tmethod,\n\t\tpath,\n\t\troute,\n\t\thost,\n\t\tscheme,\n\t\tuserAgent,\n\t\tclientIp,\n\t\trequestId: requestId || lambdaContext.awsRequestId,\n\t};\n\n\t// Add endpoint metadata if extractors provided\n\tif (options.getEndpointName || options.getOperationId) {\n\t\tattrs.endpoint = {\n\t\t\tname: options.getEndpointName?.(event),\n\t\t\toperationId: options.getOperationId?.(event),\n\t\t};\n\t}\n\n\t// Add user metadata if extractor provided\n\tif (options.getUserId) {\n\t\tconst userId = options.getUserId(event);\n\t\tif (userId) {\n\t\t\tattrs.user = { userId };\n\t\t}\n\t}\n\n\treturn attrs;\n}\n\n/**\n * Normalize headers to lowercase keys\n */\nfunction normalizeHeaders(\n\theaders: Record<string, string | string[] | undefined>,\n): Record<string, string | string[] | undefined> {\n\tconst normalized: Record<string, string | string[] | undefined> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tnormalized[key.toLowerCase()] = value;\n\t}\n\treturn normalized;\n}\n\n/**\n * Run a function within the span context from a Lambda event\n *\n * @example\n * ```typescript\n * await withEventContext(event, async () => {\n * // Any spans created here will be children of the request span\n * await doSomething();\n * });\n * ```\n */\nexport async function withEventContext<T>(\n\tevent: any,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tconst ctx = getContextFromEvent(event);\n\tif (!ctx) {\n\t\treturn fn();\n\t}\n\treturn context.with(ctx, fn);\n}\n"],"mappings":";;;;AAuDA,MAAM,cAAc,OAAO,gBAAgB;AAC3C,MAAM,iBAAiB,OAAO,mBAAmB;;;;AAKjD,SAAgB,iBAAiB,OAA8B;CAC9D,OAAO,QAAQ;AAChB;;;;AAKA,SAAgB,oBAAoB,OAAiB;CACpD,OAAO,QAAQ;AAChB;;;;;;;;;;;;;AAcA,SAAgB,oBACf,UAAsC,CAAC,GACS;CAChD,OAAO;EACN,QAAQ,OAAO,YAAY;GAE1B,IAAI,QAAQ,aAAa,QAAQ,KAAK,GACrC;GAGD,MAAM,QAAQ,QAAQ;GACtB,MAAM,gBAAgB,QAAQ;GAG9B,MAAM,UAAU,iBAAiB,MAAM,WAAW,CAAC,CAAC;GACpD,MAAM,gBAAgBA,6BAAAA,oBAAoB,OAAO;GAGjD,MAAM,QAAQ,oBAAoB,OAAO,eAAe,OAAO;GAG/D,MAAM,OAAOC,6BAAAA,qBAAqB,OAAO,aAAa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O;AACR;;;;AAKA,SAAS,iBACR,SACgD;CAChD,MAAM,aAA4D,CAAC;CACnE,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAChD,WAAW,IAAI,YAAY,KAAK;CAEjC,OAAO;AACR;;;;;;;;;;;;AAaA,eAAsB,iBACrB,OACA,IACa;CACb,MAAM,MAAM,oBAAoB,KAAK;CACrC,IAAI,CAAC,KACJ,OAAO,GAAG;CAEX,OAAOC,mBAAAA,QAAQ,KAAK,KAAK,EAAE;AAC5B"}
1
+ {"version":3,"file":"middleware.cjs","names":["isTrustedOrigin","incomingTraceContext","createHttpServerSpan","trace","context"],"sources":["../../src/instrumentation/middleware.ts"],"sourcesContent":["/**\n * OpenTelemetry instrumentation middleware for @geekmidas/constructs\n *\n * This middleware automatically creates spans for HTTP requests,\n * extracts trace context from incoming headers, and records\n * request/response metadata as span attributes.\n */\nimport type { MiddlewareObj } from '@middy/core';\nimport { context, type Span, trace } from '@opentelemetry/api';\nimport type { Context as LambdaContext } from 'aws-lambda';\nimport {\n\tcreateHttpServerSpan,\n\tendHttpSpan,\n\ttype HttpSpanAttributes,\n\tincomingTraceContext,\n} from './http';\nimport { isTrustedOrigin } from './trust';\n\n/**\n * Options for the telemetry middleware\n */\nexport interface TelemetryMiddlewareOptions {\n\t/**\n\t * Whether to record request body as span attribute\n\t * @default false\n\t */\n\trecordBody?: boolean;\n\n\t/**\n\t * Whether to record response body as span attribute\n\t * @default false\n\t */\n\trecordResponseBody?: boolean;\n\n\t/**\n\t * Custom function to extract endpoint name from event\n\t */\n\tgetEndpointName?: (event: any) => string | undefined;\n\n\t/**\n\t * Custom function to extract operation ID from event\n\t */\n\tgetOperationId?: (event: any) => string | undefined;\n\n\t/**\n\t * Custom function to extract user ID from event\n\t */\n\tgetUserId?: (event: any) => string | undefined;\n\n\t/**\n\t * Whether to skip tracing for this request\n\t */\n\tshouldSkip?: (event: any) => boolean;\n\n\t/**\n\t * The origins whose `traceparent` is continued: the API's own sites, the\n\t * same list its CORS allows. Any other caller starts a new trace linked to\n\t * the one it claimed.\n\t */\n\ttrustedOrigins?: readonly string[];\n\n\t/**\n\t * Trust a request with no trusted origin anyway — a caller the function\n\t * can vouch for, such as one that passed IAM auth. A Lambda behind API\n\t * Gateway has no private network to tell an internal caller by, so none\n\t * is trusted unless this says so.\n\t */\n\ttrustRequest?: (event: any) => boolean;\n}\n\n// Symbol for storing span on event\nconst SPAN_SYMBOL = Symbol('telemetry.span');\nconst CONTEXT_SYMBOL = Symbol('telemetry.context');\n\n/**\n * Get the current span from the Lambda event\n */\nexport function getSpanFromEvent(event: any): Span | undefined {\n\treturn event?.[SPAN_SYMBOL];\n}\n\n/**\n * Get the current trace context from the Lambda event\n */\nexport function getContextFromEvent(event: any): any {\n\treturn event?.[CONTEXT_SYMBOL];\n}\n\n/**\n * Create a telemetry middleware for Lambda handlers\n *\n * @example\n * ```typescript\n * import { telemetryMiddleware } from '@geekmidas/telescope/instrumentation';\n *\n * const adaptor = new AmazonApiGatewayV2Endpoint(endpoint, {\n * telemetry: { middleware: telemetryMiddleware() },\n * });\n * ```\n */\nexport function telemetryMiddleware(\n\toptions: TelemetryMiddlewareOptions = {},\n): MiddlewareObj<any, any, Error, LambdaContext> {\n\treturn {\n\t\tbefore: async (request) => {\n\t\t\t// Skip if custom skip function returns true\n\t\t\tif (options.shouldSkip?.(request.event)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst event = request.event;\n\t\t\tconst lambdaContext = request.context;\n\n\t\t\t// Extract trace context from headers\n\t\t\tconst headers = normalizeHeaders(event.headers || {});\n\t\t\tconst trusted =\n\t\t\t\tisTrustedOrigin(\n\t\t\t\t\ttypeof headers.origin === 'string' ? headers.origin : undefined,\n\t\t\t\t\toptions.trustedOrigins,\n\t\t\t\t) || Boolean(options.trustRequest?.(event));\n\t\t\tconst { parent: parentContext, links } = incomingTraceContext(\n\t\t\t\theaders,\n\t\t\t\ttrusted,\n\t\t\t);\n\n\t\t\t// Build span attributes from event\n\t\t\tconst attrs = buildSpanAttributes(event, lambdaContext, options);\n\n\t\t\t// Create the span\n\t\t\tconst span = createHttpServerSpan(attrs, parentContext, links);\n\n\t\t\t// Store span and context on event for access in handler\n\t\t\tevent[SPAN_SYMBOL] = span;\n\t\t\tevent[CONTEXT_SYMBOL] = trace.setSpan(parentContext, span);\n\n\t\t\t// Add Lambda-specific attributes\n\t\t\tspan.setAttribute('faas.invocation_id', lambdaContext.awsRequestId);\n\t\t\tspan.setAttribute('faas.name', lambdaContext.functionName);\n\n\t\t\tif (options.recordBody && event.body) {\n\t\t\t\tconst bodyStr =\n\t\t\t\t\ttypeof event.body === 'string'\n\t\t\t\t\t\t? event.body\n\t\t\t\t\t\t: JSON.stringify(event.body);\n\t\t\t\t// Truncate large bodies\n\t\t\t\tspan.setAttribute(\n\t\t\t\t\t'http.request.body',\n\t\t\t\t\tbodyStr.length > 4096 ? `${bodyStr.slice(0, 4096)}...` : bodyStr,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\n\t\tafter: async (request) => {\n\t\t\tconst span = getSpanFromEvent(request.event);\n\t\t\tif (!span) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst response = request.response;\n\t\t\tconst statusCode =\n\t\t\t\ttypeof response?.statusCode === 'number' ? response.statusCode : 200;\n\n\t\t\tif (options.recordResponseBody && response?.body) {\n\t\t\t\tconst bodyStr =\n\t\t\t\t\ttypeof response.body === 'string'\n\t\t\t\t\t\t? response.body\n\t\t\t\t\t\t: JSON.stringify(response.body);\n\t\t\t\tspan.setAttribute(\n\t\t\t\t\t'http.response.body',\n\t\t\t\t\tbodyStr.length > 4096 ? `${bodyStr.slice(0, 4096)}...` : bodyStr,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tendHttpSpan(span, { statusCode });\n\t\t},\n\n\t\tonError: async (request) => {\n\t\t\tconst span = getSpanFromEvent(request.event);\n\t\t\tif (!span) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst error = request.error;\n\t\t\tconst response = request.response;\n\n\t\t\t// Determine status code from response or error\n\t\t\tlet statusCode = 500;\n\t\t\tif (response?.statusCode) {\n\t\t\t\tstatusCode = response.statusCode;\n\t\t\t} else if (error && 'statusCode' in error) {\n\t\t\t\tstatusCode = (error as any).statusCode;\n\t\t\t}\n\n\t\t\tendHttpSpan(\n\t\t\t\tspan,\n\t\t\t\t{ statusCode },\n\t\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Build span attributes from Lambda event\n */\nfunction buildSpanAttributes(\n\tevent: any,\n\tlambdaContext: LambdaContext,\n\toptions: TelemetryMiddlewareOptions,\n): HttpSpanAttributes {\n\t// Detect event type (API Gateway v1, v2, ALB, or direct invoke)\n\tconst isV2 =\n\t\t'requestContext' in event && 'http' in (event.requestContext || {});\n\tconst isV1 =\n\t\t'requestContext' in event &&\n\t\t'httpMethod' in event &&\n\t\t!('http' in (event.requestContext || {}));\n\n\tlet method = 'INVOKE';\n\tlet path = '/';\n\tlet route: string | undefined;\n\tlet host: string | undefined;\n\tlet scheme: 'http' | 'https' | undefined;\n\tlet userAgent: string | undefined;\n\tlet clientIp: string | undefined;\n\tlet requestId: string | undefined;\n\n\tif (isV2) {\n\t\t// API Gateway v2 (HTTP API)\n\t\tconst http = event.requestContext.http;\n\t\tmethod = http.method;\n\t\tpath = event.rawPath || http.path;\n\t\troute = event.routeKey?.replace(/^[A-Z]+\\s+/, ''); // Remove HTTP method prefix\n\t\thost = event.headers?.host;\n\t\tscheme = 'https';\n\t\tuserAgent = http.userAgent;\n\t\tclientIp = http.sourceIp;\n\t\trequestId = event.requestContext.requestId;\n\t} else if (isV1) {\n\t\t// API Gateway v1 (REST API)\n\t\tmethod = event.httpMethod;\n\t\tpath = event.path;\n\t\troute = event.resource;\n\t\thost = event.headers?.Host || event.headers?.host;\n\t\tscheme = 'https';\n\t\tuserAgent = event.headers?.['User-Agent'] || event.headers?.['user-agent'];\n\t\tclientIp = event.requestContext?.identity?.sourceIp;\n\t\trequestId = event.requestContext?.requestId;\n\t} else if ('httpMethod' in event) {\n\t\t// ALB event\n\t\tmethod = event.httpMethod;\n\t\tpath = event.path;\n\t\thost = event.headers?.host;\n\t\tuserAgent = event.headers?.['user-agent'] || event.headers?.['User-Agent'];\n\t\tclientIp = event.headers?.['x-forwarded-for']?.split(',')[0]?.trim();\n\t}\n\n\tconst attrs: HttpSpanAttributes = {\n\t\tmethod,\n\t\tpath,\n\t\troute,\n\t\thost,\n\t\tscheme,\n\t\tuserAgent,\n\t\tclientIp,\n\t\trequestId: requestId || lambdaContext.awsRequestId,\n\t};\n\n\t// Add endpoint metadata if extractors provided\n\tif (options.getEndpointName || options.getOperationId) {\n\t\tattrs.endpoint = {\n\t\t\tname: options.getEndpointName?.(event),\n\t\t\toperationId: options.getOperationId?.(event),\n\t\t};\n\t}\n\n\t// Add user metadata if extractor provided\n\tif (options.getUserId) {\n\t\tconst userId = options.getUserId(event);\n\t\tif (userId) {\n\t\t\tattrs.user = { userId };\n\t\t}\n\t}\n\n\treturn attrs;\n}\n\n/**\n * Normalize headers to lowercase keys\n */\nfunction normalizeHeaders(\n\theaders: Record<string, string | string[] | undefined>,\n): Record<string, string | string[] | undefined> {\n\tconst normalized: Record<string, string | string[] | undefined> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tnormalized[key.toLowerCase()] = value;\n\t}\n\treturn normalized;\n}\n\n/**\n * Run a function within the span context from a Lambda event\n *\n * @example\n * ```typescript\n * await withEventContext(event, async () => {\n * // Any spans created here will be children of the request span\n * await doSomething();\n * });\n * ```\n */\nexport async function withEventContext<T>(\n\tevent: any,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tconst ctx = getContextFromEvent(event);\n\tif (!ctx) {\n\t\treturn fn();\n\t}\n\treturn context.with(ctx, fn);\n}\n"],"mappings":";;;;;AAuEA,MAAM,cAAc,OAAO,gBAAgB;AAC3C,MAAM,iBAAiB,OAAO,mBAA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