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