@honeybadger-io/nextjs 5.11.6 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +5 -42
  2. package/dist/capture-request-error.d.ts +35 -0
  3. package/dist/capture-request-error.test.d.ts +2 -0
  4. package/dist/capture-router-transition-start.d.ts +21 -0
  5. package/dist/capture-router-transition-start.test.d.ts +2 -0
  6. package/dist/client.d.ts +2 -0
  7. package/dist/copy-config-files.js +106 -34
  8. package/dist/copy-config-files.js.map +1 -1
  9. package/dist/edge.d.ts +2 -1
  10. package/dist/flush.d.ts +24 -0
  11. package/dist/honeybadger-nextjs-client.cjs.js +39 -0
  12. package/dist/honeybadger-nextjs-client.cjs.js.map +1 -0
  13. package/dist/honeybadger-nextjs-client.esm.js +31 -0
  14. package/dist/honeybadger-nextjs-client.esm.js.map +1 -0
  15. package/dist/honeybadger-nextjs-edge.cjs.js +333 -239
  16. package/dist/honeybadger-nextjs-edge.cjs.js.map +1 -1
  17. package/dist/honeybadger-nextjs-edge.esm.js +330 -239
  18. package/dist/honeybadger-nextjs-edge.esm.js.map +1 -1
  19. package/dist/honeybadger-nextjs.cjs.js +852 -386
  20. package/dist/honeybadger-nextjs.cjs.js.map +1 -1
  21. package/dist/honeybadger-nextjs.esm.js +846 -385
  22. package/dist/honeybadger-nextjs.esm.js.map +1 -1
  23. package/dist/index.d.ts +5 -2
  24. package/dist/insights-instrumentation.d.ts +30 -2
  25. package/dist/insights.d.ts +72 -0
  26. package/dist/insights.test.d.ts +2 -0
  27. package/dist/query-filters.test.d.ts +2 -0
  28. package/dist/setup.d.ts +11 -0
  29. package/dist/setup.test.d.ts +2 -0
  30. package/dist/source-maps.d.ts +55 -0
  31. package/dist/source-maps.test.d.ts +2 -0
  32. package/dist/types.d.ts +20 -8
  33. package/package.json +34 -12
  34. package/src/capture-request-error.test.ts +261 -0
  35. package/src/capture-request-error.ts +107 -0
  36. package/src/capture-router-transition-start.test.ts +44 -0
  37. package/src/capture-router-transition-start.ts +37 -0
  38. package/src/client.ts +4 -0
  39. package/src/copy-config-files.test.ts +250 -16
  40. package/src/copy-config-files.ts +117 -34
  41. package/src/edge.ts +12 -1
  42. package/src/flush.ts +58 -0
  43. package/src/index.ts +7 -2
  44. package/src/insights-instrumentation.ts +104 -11
  45. package/src/insights.test.ts +192 -0
  46. package/src/insights.ts +225 -0
  47. package/src/query-filters.test.ts +67 -0
  48. package/src/setup.test.ts +214 -0
  49. package/src/setup.ts +172 -0
  50. package/src/source-maps.test.ts +803 -0
  51. package/src/source-maps.ts +515 -0
  52. package/src/types.ts +38 -21
  53. package/templates/_error.js +14 -10
  54. package/templates/_error_app_router.js +1 -1
  55. package/templates/_error_app_router.tsx +1 -1
  56. package/templates/honeybadger.server.config.js +5 -16
  57. package/templates/instrumentation-client.js +21 -0
  58. package/templates/instrumentation.js +29 -0
  59. package/dist/webpack.d.ts +0 -3
  60. package/dist/with-honeybadger.d.ts +0 -32
  61. package/dist/with-honeybadger.test.d.ts +0 -2
  62. package/src/webpack.ts +0 -228
  63. package/src/with-honeybadger.test.ts +0 -527
  64. package/src/with-honeybadger.ts +0 -286
  65. package/templates/honeybadger.browser.config.js +0 -13
  66. package/templates/honeybadger.edge.config.js +0 -13
@@ -28,10 +28,60 @@ function _interopNamespace(e) {
28
28
  var Honeybadger__default = /*#__PURE__*/_interopDefaultLegacy(Honeybadger);
29
29
  var nextServer__namespace = /*#__PURE__*/_interopNamespace(nextServer);
30
30
 
31
+ /**
32
+ * The `waitUntil` primitive the hosting platform injects per request. Next.js
33
+ * resolves `after()` through this same accessor, and it is the only channel
34
+ * available in Pages Router API routes, which are invoked as `(req, res)` with
35
+ * no context argument to read it from.
36
+ */
37
+ function requestContextWaitUntil() {
38
+ var _a, _b;
39
+ const context = globalThis[Symbol.for('@next/request-context')];
40
+ const waitUntil = (_b = (_a = context === null || context === void 0 ? void 0 : context.get) === null || _a === void 0 ? void 0 : _a.call(context)) === null || _b === void 0 ? void 0 : _b.waitUntil;
41
+ return typeof waitUntil === 'function' ? waitUntil : undefined;
42
+ }
43
+ /**
44
+ * Ensure events are delivered before a serverless runtime freezes, without
45
+ * delaying the response where the runtime lets us avoid it.
46
+ *
47
+ * In order of preference: Next.js `after()` (App Router only — it needs App Router
48
+ * request context, so Pages Router must not call it), then a `waitUntil` from the
49
+ * platform request context, then a blocking `flushAsync()` when the runtime offers
50
+ * neither.
51
+ *
52
+ * Delivery failures are logged by the events worker and must not break the handler.
53
+ */
54
+ function scheduleFlush(options = {}) {
55
+ var _a;
56
+ const flush = () => Honeybadger__default["default"].flushAsync().catch(() => { });
57
+ if (options.useAfter) {
58
+ const after = nextServer__namespace.after;
59
+ if (typeof after === 'function') {
60
+ // Exported but still refusable: `after()` throws outside a supported
61
+ // context. Fall through to the remaining strategies rather than failing
62
+ // the request.
63
+ try {
64
+ after(flush);
65
+ return;
66
+ }
67
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
68
+ catch (error) {
69
+ // try waitUntil / blocking flush below
70
+ }
71
+ }
72
+ }
73
+ const waitUntil = (_a = options.waitUntil) !== null && _a !== void 0 ? _a : requestContextWaitUntil();
74
+ if (waitUntil) {
75
+ waitUntil(flush());
76
+ return;
77
+ }
78
+ return flush();
79
+ }
80
+
31
81
  /**
32
82
  * Edge-safe equivalents of the inbound instrumentation helpers in
33
83
  * `@honeybadger-io/js` (src/server/instrumentation/http_event.ts). They are
34
- * duplicated here because this module must also load on the edge runtime where
84
+ * duplicated here because this module must load in every runtime where
35
85
  * Node builtins (the `crypto` module, `process.hrtime`) are unavailable. Keep
36
86
  * the header names and the `request_id` / `correlation_id` contract in sync
37
87
  * with that file.
@@ -60,14 +110,6 @@ function generateId() {
60
110
  return v.toString(16);
61
111
  });
62
112
  }
63
- function readHeader(headers, name) {
64
- const value = headers.get(name);
65
- if (typeof value !== 'string') {
66
- return undefined;
67
- }
68
- const trimmed = value.trim();
69
- return trimmed.length ? trimmed : undefined;
70
- }
71
113
  function readNodeHeader(headers, name) {
72
114
  if (!headers) {
73
115
  return undefined;
@@ -91,168 +133,102 @@ function readNodeHeader(headers, name) {
91
133
  const trimmed = value.trim();
92
134
  return trimmed.length ? trimmed : undefined;
93
135
  }
94
- // Shared id precedence. Kept in one place (rather than once per request shape)
95
- // so the header-name contract documented above is only spelled out once.
96
- function seedIds(read) {
97
- var _a, _b, _c, _d;
98
- const requestId = (_b = (_a = read('x-request-id')) !== null && _a !== void 0 ? _a : read('request-id')) !== null && _b !== void 0 ? _b : generateId();
99
- const correlationId = (_d = (_c = read('x-correlation-id')) !== null && _c !== void 0 ? _c : read('x-amzn-trace-id')) !== null && _d !== void 0 ? _d : requestId;
100
- return { request_id: requestId, correlation_id: correlationId };
101
- }
102
- // App Router / middleware: headers are a web `Headers` instance.
103
- function seedRequestEventContext(headers) {
104
- return seedIds((name) => readHeader(headers, name));
105
- }
106
- // Pages Router: headers are a Node bag (Pages routes are Node-only, never edge).
107
- function seedNodeRequestEventContext(headers) {
108
- return seedIds((name) => readNodeHeader(headers, name));
109
- }
110
- function now() {
111
- return typeof performance !== 'undefined' ? performance.now() : Date.now();
112
- }
113
- // Mirrors Util.resolveInsights from @honeybadger-io/core: the master gate and
114
- // the per-source flag must both be on.
115
- function insightsHttpEnabled() {
116
- const insights = Honeybadger__default["default"].config.insights;
117
- return (insights === null || insights === void 0 ? void 0 : insights.enabled) === true && (insights === null || insights === void 0 ? void 0 : insights.http) === true;
118
- }
119
- // The ids are embedded directly in the payload (instead of relying on the
120
- // store's eventContext merge) so the event carries them even on the edge
121
- // runtime, where there is no per-request store isolation. On the Node.js
122
- // runtime they match the seeded event context, so embedding is a no-op.
123
- function emitHandledEvent(method, path, status, start, ids) {
124
- const payload = {
125
- method,
126
- duration: Math.round(now() - start),
127
- ...ids,
128
- };
129
- if (typeof path === 'string') {
130
- payload.path = path;
136
+ /**
137
+ * Shared id precedence. Kept in one place (rather than once per request shape)
138
+ * so the header-name contract documented above is only spelled out once.
139
+ *
140
+ * The span ids do double duty. They are emitted as `trace_id` / `span_id`, and they also
141
+ * back-fill `request_id` / `correlation_id` when no header supplied them — a trace id
142
+ * already has exactly the semantics we want for a correlation id, since W3C trace context
143
+ * reuses an inbound `traceparent` and mints a new one when there is none.
144
+ *
145
+ * That double duty is what makes a fault joinable to its request's events: both paths seed
146
+ * from the same span, so with no id headers present a fault and its `request.handled` event
147
+ * carry identical values for all four.
148
+ */
149
+ function seedIds(read, span = {}) {
150
+ var _a, _b, _c, _d, _e, _f;
151
+ const requestId = (_c = (_b = (_a = read('x-request-id')) !== null && _a !== void 0 ? _a : read('request-id')) !== null && _b !== void 0 ? _b : span.spanId) !== null && _c !== void 0 ? _c : generateId();
152
+ const correlationId = (_f = (_e = (_d = read('x-correlation-id')) !== null && _d !== void 0 ? _d : read('x-amzn-trace-id')) !== null && _e !== void 0 ? _e : span.traceId) !== null && _f !== void 0 ? _f : requestId;
153
+ const ids = { request_id: requestId, correlation_id: correlationId };
154
+ if (span.traceId) {
155
+ ids.trace_id = span.traceId;
131
156
  }
132
- if (typeof status === 'number') {
133
- payload.status = status;
157
+ if (span.spanId) {
158
+ ids.span_id = span.spanId;
134
159
  }
135
- Honeybadger__default["default"].event('request.handled', payload);
160
+ return ids;
136
161
  }
137
- // App Router / middleware: `req.url` is absolute, so parse out the pathname.
138
- function emitRequestEvent(req, status, start, ids) {
139
- let path;
162
+ /**
163
+ * The active span's ids, or an empty object when OpenTelemetry is not in play.
164
+ *
165
+ * `@opentelemetry/api` is an optional peer dependency, and this module is reachable from
166
+ * every runtime entry point, so it is loaded on demand and any failure to resolve it is
167
+ * treated as "no tracing configured" rather than an error.
168
+ */
169
+ async function activeSpanIds() {
170
+ var _a;
140
171
  try {
141
- path = new URL(req.url).pathname;
172
+ const { trace } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('@opentelemetry/api')); });
173
+ const spanContext = (_a = trace.getActiveSpan()) === null || _a === void 0 ? void 0 : _a.spanContext();
174
+ if (!spanContext) {
175
+ return {};
176
+ }
177
+ return { traceId: spanContext.traceId, spanId: spanContext.spanId };
142
178
  }
143
179
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
144
180
  catch (error) {
145
- // relative or malformed URL — leave path unset
181
+ return {};
146
182
  }
147
- emitHandledEvent(req.method, path, status, start, ids);
148
- }
149
- // Pages Router: `req.url` is a relative path that may carry a query string.
150
- function emitNodeRequestEvent(req, status, start, ids) {
151
- const path = typeof req.url === 'string' ? req.url.split('?')[0] : undefined;
152
- emitHandledEvent(req.method, path, status, start, ids);
153
183
  }
154
-
155
- /**
156
- * The `waitUntil` primitive the hosting platform injects per request. Next.js
157
- * resolves `after()` through this same accessor, and it is the only channel
158
- * available in Pages Router API routes, which are invoked as `(req, res)` with
159
- * no context argument to read it from.
160
- */
161
- function requestContextWaitUntil() {
162
- var _a, _b;
163
- const context = globalThis[Symbol.for('@next/request-context')];
164
- const waitUntil = (_b = (_a = context === null || context === void 0 ? void 0 : context.get) === null || _a === void 0 ? void 0 : _a.call(context)) === null || _b === void 0 ? void 0 : _b.waitUntil;
165
- return typeof waitUntil === 'function' ? waitUntil : undefined;
184
+ // Pages Router: headers are a Node bag (Pages routes are Node-only, never edge).
185
+ function seedNodeRequestEventContext(headers, span = {}) {
186
+ return seedIds((name) => readNodeHeader(headers, name), span);
166
187
  }
167
- /**
168
- * Middleware receives a `NextFetchEvent` as its second argument. Duck-typed
169
- * rather than `instanceof` so the edge bundle needs no runtime import, and
170
- * bound because `waitUntil` is a class method that collects into the event.
171
- */
172
- function eventWaitUntil(event) {
173
- const waitUntil = event === null || event === void 0 ? void 0 : event.waitUntil;
174
- return typeof waitUntil === 'function' ? waitUntil.bind(event) : undefined;
188
+ // Mirrors Util.resolveInsights from @honeybadger-io/core: the master gate and
189
+ // the per-source flag must both be on.
190
+ function insightsHttpEnabled() {
191
+ const insights = Honeybadger__default["default"].config.insights;
192
+ return (insights === null || insights === void 0 ? void 0 : insights.enabled) === true && (insights === null || insights === void 0 ? void 0 : insights.http) === true;
175
193
  }
176
194
  /**
177
- * Ensure Insights events are delivered before the serverless/edge runtime
178
- * freezes, without delaying the response where the runtime lets us avoid it.
179
- *
180
- * In order of preference: Next.js `after()` (stable in 15.1, App Router only —
181
- * it needs App Router request context, so Pages Router must not call it), then
182
- * a `waitUntil` from the middleware event or the platform request context,
183
- * then a blocking `flushAsync()` when the runtime offers neither. Blocking is
184
- * correct in that last case: no `waitUntil` means nothing is going to freeze
185
- * the invocation out from under us.
195
+ * OpenTelemetry path. Header values are not on the span by default; they arrive as
196
+ * `http.request.header.*` attributes when the HTTP instrumentation is configured with
197
+ * `headersToSpanAttributes`. Hyphens become underscores under the older semantic
198
+ * conventions and are preserved under the stable ones, so both spellings are read.
186
199
  *
187
- * Delivery failures are logged by the events worker and must not break the handler.
200
+ * When no header is present the span and trace ids are used, so the ids stay
201
+ * meaningful — and joinable to a trace — on platforms where the HTTP layer is not
202
+ * visible, such as serverless platforms.
188
203
  */
189
- function scheduleFlush(options = {}) {
190
- var _a;
191
- const flush = () => Honeybadger__default["default"].flushAsync().catch(() => { });
192
- if (options.useAfter) {
193
- const after = nextServer__namespace.after;
194
- if (typeof after === 'function') {
195
- // Exported but still refusable: `after()` throws outside a supported
196
- // context. Fall through to the remaining strategies rather than failing
197
- // the request.
198
- try {
199
- after(flush);
200
- return;
201
- }
202
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
203
- catch (error) {
204
- // try waitUntil / blocking flush below
204
+ function seedSpanEventContext(attributes, spanContext) {
205
+ const read = (name) => {
206
+ const lower = name.toLowerCase();
207
+ for (const key of [
208
+ `http.request.header.${lower}`,
209
+ `http.request.header.${lower.replace(/-/g, '_')}`,
210
+ ]) {
211
+ const value = attributes[key];
212
+ const first = Array.isArray(value) ? value[0] : value;
213
+ if (typeof first === 'string' && first.trim().length) {
214
+ return first.trim();
205
215
  }
206
216
  }
207
- }
208
- const waitUntil = (_a = options.waitUntil) !== null && _a !== void 0 ? _a : requestContextWaitUntil();
209
- if (waitUntil) {
210
- waitUntil(flush());
211
- return;
212
- }
213
- return flush();
214
- }
215
- function configure(overrides) {
216
- var _a;
217
- if (((_a = Honeybadger__default["default"].config.apiKey) === null || _a === void 0 ? void 0 : _a.length) > 0) {
218
- return;
219
- }
220
- let projectRoot = undefined;
221
- try {
222
- // not available on edge runtime
223
- projectRoot = process.cwd();
224
- }
225
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
226
- catch (error) {
227
- // do nothing
228
- }
229
- Honeybadger__default["default"]
230
- .configure({
231
- apiKey: process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY,
232
- environment: process.env.NEXT_PUBLIC_VERCEL_ENV || process.env.VERCEL_ENV || process.env.NODE_ENV,
233
- revision: process.env.NEXT_PUBLIC_HONEYBADGER_REVISION,
234
- projectRoot: 'webpack://_N_E/./',
235
- ...overrides,
236
- })
237
- .beforeNotify((notice) => {
238
- if (!projectRoot) {
239
- return;
240
- }
241
- notice === null || notice === void 0 ? void 0 : notice.backtrace.forEach((line) => {
242
- if (line.file) {
243
- line.file = line.file.replace(`${projectRoot}/.next/server`, `${process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL}/..`);
244
- }
245
- return line;
246
- });
217
+ return undefined;
218
+ };
219
+ return seedIds(read, {
220
+ traceId: spanContext.traceId || undefined,
221
+ spanId: spanContext.spanId || undefined,
247
222
  });
248
223
  }
224
+
249
225
  /**
250
226
  * Next.js uses thrown errors for control flow: `redirect()`, `notFound()`,
251
227
  * `forbidden()` and `unauthorized()` all throw an error carrying a `digest`
252
228
  * string (`NEXT_REDIRECT;...`, `NEXT_NOT_FOUND`, `NEXT_HTTP_ERROR_FALLBACK;...`).
253
229
  * These are not real failures — the framework catches them upstream to produce
254
- * the redirect/404/etc. — so we must let them propagate without reporting them,
255
- * otherwise every redirect shows up as an error in Honeybadger.
230
+ * the redirect/404/etc. — so we must let them pass without reporting, otherwise
231
+ * every redirect shows up as an error in Honeybadger.
256
232
  *
257
233
  * We match on the `NEXT_` prefix rather than an exhaustive list so that any
258
234
  * present or future framework control-flow digest is covered. This is safe:
@@ -265,120 +241,238 @@ function isNextControlFlowError(error) {
265
241
  return typeof digest === 'string' && digest.startsWith('NEXT_');
266
242
  }
267
243
  /**
268
- * Detects a Pages Router API invocation: `(req, res)` where `res` is a Node
269
- * `ServerResponse`. We branch on this structurally because — unlike an App
270
- * Router route handler — there is no returned `Response` to read the status
271
- * from; it lives on `res.statusCode`.
244
+ * The path with any query string removed.
245
+ *
246
+ * Next.js reports `path` with the query attached (`/blog?name=foo`), and this value is
247
+ * written to the user's context, which `filters` never touch.
272
248
  */
273
- function isPagesApiInvocation(args) {
274
- const req = args[0];
275
- const res = args[1];
276
- return (!!req && typeof req.headers === 'object' && req.headers !== null &&
277
- !!res && typeof res.statusCode === 'number' && typeof res.end === 'function');
249
+ function requestPath(path) {
250
+ return typeof path === 'string' ? path.split('?')[0] : path;
278
251
  }
279
252
  /**
280
- * App Router route handlers and middleware: a web `Request`/`NextRequest` in, a
281
- * `Response`/`NextResponse` out. The status comes from the returned response.
253
+ * Reports errors passed to Next.js's `onRequestError` instrumentation hook.
254
+ *
255
+ * Wire it up in `instrumentation.ts`:
282
256
  *
283
- * `waitUntil` is present for middleware (from its `NextFetchEvent`); route
284
- * handlers get `{ params }` as their second argument and rely on `after()`.
257
+ * ```ts
258
+ * export const onRequestError = captureRequestError
259
+ * ```
260
+ *
261
+ * Reaches Server Components, Route Handlers, Server Actions and middleware, and receives
262
+ * the real error rather than the generic message Next.js hands to an error component.
285
263
  */
286
- async function handleAppRouterRequest(call, req, canIsolate, waitUntil) {
287
- const ids = seedRequestEventContext(req.headers);
288
- if (canIsolate) {
289
- Honeybadger__default["default"].setEventContext(ids);
290
- }
291
- const start = insightsHttpEnabled() ? now() : null;
292
- try {
293
- const response = await call();
294
- if (start !== null) {
295
- emitRequestEvent(req, response === null || response === void 0 ? void 0 : response.status, start, ids);
296
- await scheduleFlush({ useAfter: true, waitUntil });
297
- }
298
- return response;
299
- }
300
- catch (error) {
301
- if (isNextControlFlowError(error)) {
302
- throw error;
303
- }
304
- if (start !== null) {
305
- emitRequestEvent(req, 500, start, ids);
306
- await scheduleFlush({ useAfter: true, waitUntil });
307
- }
308
- await Honeybadger__default["default"].notifyAsync(error);
309
- throw error;
264
+ async function captureRequestError(error, request, context) {
265
+ if (isNextControlFlowError(error)) {
266
+ return;
310
267
  }
268
+ // Same header precedence *and* the same span as the Insights path, so a fault and the
269
+ // events from the request it failed in carry matching ids. Next.js still has the request
270
+ // span active when it calls this hook, and it is the very span the Insights processor
271
+ // maps to `request.handled` — so with no id headers present all four ids are identical on
272
+ // both, and the fault joins its request's events and trace.
273
+ //
274
+ // Deliberately not written to the event context: outside a `Honeybadger.run()` that
275
+ // lands on a store shared by the whole process or isolate, so the ids would leak into
276
+ // later requests' events. `onRequestError` also fires after the request has already
277
+ // failed, so it is too late to decorate that request's own events anyway.
278
+ const ids = seedNodeRequestEventContext(request.headers, await activeSpanIds());
279
+ await Honeybadger__default["default"].notifyAsync(error, {
280
+ // The full path, query string included, goes on `url` so the configured `filters` are
281
+ // applied to it -- `filterUrl` runs over this field when the payload is built. Context
282
+ // is deliberately never filtered, since it is the user's own bag, so the copy below is
283
+ // reduced to the bare path rather than repeating an unfiltered query string there.
284
+ url: request.path,
285
+ context: {
286
+ ...ids,
287
+ path: requestPath(request.path),
288
+ method: request.method,
289
+ router_kind: context.routerKind,
290
+ route_path: context.routePath,
291
+ route_type: context.routeType,
292
+ },
293
+ });
294
+ await scheduleFlush({ useAfter: true });
311
295
  }
296
+
312
297
  /**
313
- * Pages Router API routes: a Node `req`/`res` pair. The handler writes to `res`
314
- * and returns nothing meaningful, so the final status is read from
315
- * `res.statusCode` once it resolves.
298
+ * Next.js instruments itself with OpenTelemetry and emits one root span per request,
299
+ * `[http.method] [next.route]`, tagged `next.span_type: BaseServer.handleRequest`. Its
300
+ * attributes carry the method, route, target and status, so mapping that span to a
301
+ * `request.handled` event reports every request without wrapping any handler.
302
+ *
303
+ * Next instruments but does not export: spans only reach us once a tracer provider with
304
+ * this processor is registered. See `registerHoneybadgerInsights`.
316
305
  */
317
- async function handlePagesApiRequest(call, req, res, canIsolate) {
318
- const ids = seedNodeRequestEventContext(req.headers);
319
- if (canIsolate) {
320
- Honeybadger__default["default"].setEventContext(ids);
321
- }
322
- const start = insightsHttpEnabled() ? now() : null;
323
- try {
324
- const result = await call();
325
- if (start !== null) {
326
- emitNodeRequestEvent(req, res.statusCode, start, ids);
327
- // No after() here: Pages Router lacks the App Router request context it
328
- // needs. scheduleFlush falls through to the platform waitUntil instead.
329
- await scheduleFlush({ useAfter: false });
306
+ const NEXT_REQUEST_SPAN_TYPE = 'BaseServer.handleRequest';
307
+ /**
308
+ * Request headers to copy onto the root span, so `request_id` and `correlation_id` can be
309
+ * reused from an inbound request instead of falling back to the span and trace ids.
310
+ *
311
+ * Header values are not span attributes by default. `@vercel/otel` applies this map when
312
+ * it creates the root span, which is the span this processor reads — and, unlike Node's
313
+ * HTTP instrumentation, it works on serverless platforms too.
314
+ *
315
+ * Spread it into your own `registerOTel` call if you register OpenTelemetry yourself:
316
+ *
317
+ * ```ts
318
+ * registerOTel({
319
+ * attributesFromHeaders: { ...HONEYBADGER_HEADER_ATTRIBUTES },
320
+ * spanProcessors: [honeybadgerSpanProcessor()],
321
+ * })
322
+ * ```
323
+ *
324
+ * Keep the header names in sync with `seedIds` in ./insights-instrumentation.
325
+ */
326
+ const HONEYBADGER_HEADER_ATTRIBUTES = {
327
+ 'http.request.header.x-request-id': 'x-request-id',
328
+ 'http.request.header.request-id': 'request-id',
329
+ 'http.request.header.x-correlation-id': 'x-correlation-id',
330
+ 'http.request.header.x-amzn-trace-id': 'x-amzn-trace-id',
331
+ };
332
+ function readString(attributes, ...names) {
333
+ for (const name of names) {
334
+ const value = attributes[name];
335
+ if (typeof value === 'string' && value.length) {
336
+ return value;
330
337
  }
331
- return result;
332
338
  }
333
- catch (error) {
334
- if (isNextControlFlowError(error)) {
335
- throw error;
339
+ return undefined;
340
+ }
341
+ function readNumber(attributes, ...names) {
342
+ for (const name of names) {
343
+ const value = attributes[name];
344
+ if (typeof value === 'number') {
345
+ return value;
336
346
  }
337
- if (start !== null) {
338
- emitNodeRequestEvent(req, 500, start, ids);
339
- await scheduleFlush({ useAfter: false });
347
+ if (typeof value === 'string' && value.trim().length && Number.isFinite(Number(value))) {
348
+ return Number(value);
340
349
  }
341
- await Honeybadger__default["default"].notifyAsync(error);
342
- throw error;
343
350
  }
351
+ return undefined;
352
+ }
353
+ function durationMs(duration) {
354
+ if (!Array.isArray(duration) || duration.length !== 2) {
355
+ return 0;
356
+ }
357
+ const [seconds, nanos] = duration;
358
+ return Math.round(seconds * 1000 + nanos / 1e6);
359
+ }
360
+ /**
361
+ * Path without the query string. `http.target` includes the query under the older
362
+ * semantic conventions; `url.path` is already bare under the stable ones.
363
+ */
364
+ function readPath(attributes) {
365
+ const target = readString(attributes, 'url.path', 'http.target');
366
+ return typeof target === 'string' ? target.split('?')[0] : undefined;
344
367
  }
345
368
  /**
346
- * Unrecognised invocation shape: still report errors, but emit no insights
347
- * event since we can't reliably read the request.
369
+ * Maps Next.js's per-request span to a Honeybadger `request.handled` Insights event.
370
+ *
371
+ * Pass it to whatever registers OpenTelemetry in your `instrumentation.ts`:
372
+ *
373
+ * ```ts
374
+ * import { registerOTel } from '@vercel/otel'
375
+ * import { honeybadgerSpanProcessor } from '@honeybadger-io/nextjs'
376
+ *
377
+ * export function register() {
378
+ * registerOTel({ serviceName: 'my-app', spanProcessors: [honeybadgerSpanProcessor()] })
379
+ * }
380
+ * ```
381
+ *
382
+ * `registerHoneybadgerInsights()` is the one-line equivalent when you have no other
383
+ * OpenTelemetry setup of your own.
348
384
  */
349
- async function handleUninstrumented(call) {
385
+ function honeybadgerSpanProcessor() {
386
+ return {
387
+ onStart() {
388
+ // Nothing to do: the event is emitted once the request span is complete, which is
389
+ // when the status and duration are known.
390
+ },
391
+ onEnd(span) {
392
+ var _a;
393
+ const attributes = (_a = span.attributes) !== null && _a !== void 0 ? _a : {};
394
+ if (attributes['next.span_type'] !== NEXT_REQUEST_SPAN_TYPE) {
395
+ return;
396
+ }
397
+ // Checked per event rather than at registration: configuration is loaded by
398
+ // `register()` importing the honeybadger config files, which may happen after the
399
+ // processor is constructed.
400
+ if (!insightsHttpEnabled()) {
401
+ return;
402
+ }
403
+ const spanContext = typeof span.spanContext === 'function' ? span.spanContext() : {};
404
+ const ids = seedSpanEventContext(attributes, spanContext !== null && spanContext !== void 0 ? spanContext : {});
405
+ const payload = {
406
+ method: readString(attributes, 'http.request.method', 'http.method'),
407
+ duration: durationMs(span.duration),
408
+ ...ids,
409
+ };
410
+ const path = readPath(attributes);
411
+ if (path) {
412
+ payload.path = path;
413
+ }
414
+ const status = readNumber(attributes, 'http.response.status_code', 'http.status_code');
415
+ if (typeof status === 'number') {
416
+ payload.status = status;
417
+ }
418
+ // Emitted alongside the ids rather than replacing them, so an event can be joined
419
+ // to a trace in another tool without changing what existing consumers read.
420
+ if (spanContext === null || spanContext === void 0 ? void 0 : spanContext.traceId) {
421
+ payload.trace_id = spanContext.traceId;
422
+ }
423
+ if (spanContext === null || spanContext === void 0 ? void 0 : spanContext.spanId) {
424
+ payload.span_id = spanContext.spanId;
425
+ }
426
+ Honeybadger__default["default"].event('request.handled', payload);
427
+ // A span processor batches on its own lifecycle, which is not enough on a platform
428
+ // that can freeze the invocation as soon as the response is sent.
429
+ scheduleFlush({ useAfter: true });
430
+ },
431
+ async forceFlush() {
432
+ await Honeybadger__default["default"].flushAsync().catch(() => { });
433
+ },
434
+ async shutdown() {
435
+ await Honeybadger__default["default"].flushAsync().catch(() => { });
436
+ },
437
+ };
438
+ }
439
+ /**
440
+ * Registers OpenTelemetry with only Honeybadger's span processor attached, for apps that
441
+ * have no OpenTelemetry setup of their own. Call it from `register()` in
442
+ * `instrumentation.ts`.
443
+ *
444
+ * `@vercel/otel` is an optional peer dependency: it is only needed for Insights, and it
445
+ * loads where the full Node SDK cannot, such as serverless platforms. If you
446
+ * already call `registerOTel` yourself, add `honeybadgerSpanProcessor()` to your
447
+ * `spanProcessors` instead of calling this — registering twice would compete for the
448
+ * global provider.
449
+ */
450
+ async function registerHoneybadgerInsights(options = {}) {
451
+ var _a, _b;
452
+ let registerOTel;
350
453
  try {
351
- return await call();
454
+ ({ registerOTel } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('@vercel/otel')); }));
352
455
  }
456
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
353
457
  catch (error) {
354
- if (isNextControlFlowError(error)) {
355
- throw error;
356
- }
357
- await Honeybadger__default["default"].notifyAsync(error);
358
- throw error;
458
+ Honeybadger__default["default"].logger.error('[Honeybadger] Insights request events need @vercel/otel. Install it, or drop the ' +
459
+ 'registerHoneybadgerInsights() call — error reporting works without it.');
460
+ return;
359
461
  }
360
- }
361
- function withHoneybadger(handler, config) {
362
- configure(config);
363
- return new Proxy(handler, {
364
- apply: (target, thisArg, args) => {
365
- const canIsolate = typeof Honeybadger__default["default"].run === 'function';
366
- const call = () => Reflect.apply(target, thisArg, args);
367
- const invoke = () => {
368
- // App Router / middleware first: a web Request as the first argument.
369
- if (typeof Request !== 'undefined' && args[0] instanceof Request) {
370
- return handleAppRouterRequest(call, args[0], canIsolate, eventWaitUntil(args[1]));
371
- }
372
- // Pages Router API route: a Node req/res pair.
373
- if (isPagesApiInvocation(args)) {
374
- return handlePagesApiRequest(call, args[0], args[1], canIsolate);
375
- }
376
- return handleUninstrumented(call);
377
- };
378
- return canIsolate ? Honeybadger__default["default"].run(invoke) : invoke();
462
+ registerOTel({
463
+ serviceName: (_b = (_a = options.serviceName) !== null && _a !== void 0 ? _a : process.env.NEXT_PUBLIC_HONEYBADGER_SERVICE_NAME) !== null && _b !== void 0 ? _b : 'nextjs-app',
464
+ // Without this the id headers never reach the span, so request_id and
465
+ // correlation_id would always fall back to the span and trace ids.
466
+ attributesFromHeaders: {
467
+ ...HONEYBADGER_HEADER_ATTRIBUTES,
468
+ ...options.attributesFromHeaders,
379
469
  },
470
+ spanProcessors: [honeybadgerSpanProcessor()],
380
471
  });
381
472
  }
382
473
 
383
- exports.withHoneybadger = withHoneybadger;
474
+ exports.HONEYBADGER_HEADER_ATTRIBUTES = HONEYBADGER_HEADER_ATTRIBUTES;
475
+ exports.captureRequestError = captureRequestError;
476
+ exports.honeybadgerSpanProcessor = honeybadgerSpanProcessor;
477
+ exports.registerHoneybadgerInsights = registerHoneybadgerInsights;
384
478
  //# sourceMappingURL=honeybadger-nextjs-edge.cjs.js.map