@logbrew/next 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -2,21 +2,20 @@ const { AsyncLocalStorage } = require("node:async_hooks");
2
2
  const {
3
3
  LogBrewClient,
4
4
  SdkError,
5
+ createIssueAttributesFromError,
5
6
  parseTraceparent
6
7
  } = require("@logbrew/sdk");
7
8
  const { createNodeFetchTransport } = require("@logbrew/node");
9
+ const {
10
+ createNextRequestErrorEvent,
11
+ getTraceparentHeader,
12
+ nextDeploymentContext,
13
+ nextRoutePath,
14
+ randomHex,
15
+ readEnvApiKey,
16
+ readEnvServerApiKey
17
+ } = require("./request-error-event.cjs");
8
18
 
9
- const MAX_REQUEST_ERROR_MESSAGE_LENGTH = 2048;
10
- const MAX_REQUEST_ROUTE_PATH_LENGTH = 512;
11
- const NEXT_RENDER_SOURCES = new Set([
12
- "react-server-components",
13
- "react-server-components-payload",
14
- "server-rendering"
15
- ]);
16
- const NEXT_RENDER_TYPES = new Set(["dynamic", "dynamic-resume"]);
17
- const NEXT_REVALIDATE_REASONS = new Set(["on-demand", "stale"]);
18
- const NEXT_ROUTE_TYPES = new Set(["action", "middleware", "proxy", "render", "route"]);
19
- const NEXT_ROUTER_KINDS = new Set(["App Router", "Pages Router"]);
20
19
  const activeTraceContext = new AsyncLocalStorage();
21
20
 
22
21
  function createLogBrewNextClient({
@@ -24,7 +23,7 @@ function createLogBrewNextClient({
24
23
  serverApiKey,
25
24
  context,
26
25
  sdkName = "logbrew-next",
27
- sdkVersion = "0.1.8",
26
+ sdkVersion = "0.1.10",
28
27
  maxRetries = 2
29
28
  } = {}) {
30
29
  const authKey = serverApiKey ?? apiKey ?? readEnvServerApiKey() ?? readEnvApiKey();
@@ -34,7 +33,8 @@ function createLogBrewNextClient({
34
33
  "createLogBrewNextClient requires serverApiKey, apiKey, LOGBREW_SERVER_API_KEY, or LOGBREW_API_KEY"
35
34
  );
36
35
  }
37
- return LogBrewClient.create({ apiKey: authKey, context, sdkName, sdkVersion, maxRetries });
36
+ const deploymentContext = nextDeploymentContext(context);
37
+ return LogBrewClient.create({ apiKey: authKey, context: deploymentContext, sdkName, sdkVersion, maxRetries });
38
38
  }
39
39
 
40
40
  function createLogBrewNextRequestErrorHandler(options = {}) {
@@ -71,39 +71,6 @@ function createLogBrewNextRequestErrorHandler(options = {}) {
71
71
  };
72
72
  }
73
73
 
74
- function createNextRequestErrorEvent(error, request = {}, context = {}, {
75
- includePathname = false,
76
- now = () => new Date().toISOString(),
77
- idFactory = defaultNextRequestErrorId
78
- } = {}) {
79
- const method = nextRequestMethod(request);
80
- const routePath = nextRoutePath(context?.routePath);
81
- const pathname = includePathname ? nextRoutePath(request?.path) : undefined;
82
- const errorDigest = nextErrorDigest(error);
83
- return {
84
- id: idFactory(error, request, context),
85
- timestamp: now(),
86
- attributes: {
87
- title: `${method} ${routePath} failed`,
88
- level: "error",
89
- message: nextErrorMessage(error),
90
- metadata: {
91
- framework: "nextjs",
92
- method,
93
- routePath,
94
- ...nextCategoricalMetadata("routerKind", context?.routerKind, NEXT_ROUTER_KINDS),
95
- ...nextCategoricalMetadata("routeType", context?.routeType, NEXT_ROUTE_TYPES),
96
- ...nextCategoricalMetadata("renderSource", context?.renderSource, NEXT_RENDER_SOURCES),
97
- ...nextCategoricalMetadata("revalidateReason", context?.revalidateReason, NEXT_REVALIDATE_REASONS),
98
- ...nextCategoricalMetadata("renderType", context?.renderType, NEXT_RENDER_TYPES),
99
- ...nextRequestTraceMetadata(request),
100
- ...(errorDigest ? { errorDigest } : {}),
101
- ...(pathname ? { pathname } : {})
102
- }
103
- }
104
- };
105
- }
106
-
107
74
  function withLogBrewRouteHandler(handler, options = {}) {
108
75
  if (typeof handler !== "function") {
109
76
  throw new SdkError("configuration_error", "withLogBrewRouteHandler requires a handler function");
@@ -117,7 +84,7 @@ function withLogBrewRouteHandler(handler, options = {}) {
117
84
  const { client, owned } = resolveClient(options, request, context);
118
85
  const transport = resolveTransport(options, { request, context, client }, defaultTransport);
119
86
  const trace = createRouteTraceContext(request, undefined, options);
120
- const helpers = createRouteHelpers(client, transport, trace);
87
+ const helpers = createRouteHelpers(client, transport, trace, request);
121
88
  const startedAt = nowMs(options);
122
89
 
123
90
  return activeTraceContext.run(trace, async () => {
@@ -184,6 +151,7 @@ function createRouteRequestEvent(request, response, {
184
151
  }
185
152
 
186
153
  function createRouteErrorEvent(error, request, {
154
+ includeErrorStack = false,
187
155
  includeSearchParams = false,
188
156
  now = () => new Date().toISOString(),
189
157
  idFactory = defaultRouteErrorId,
@@ -193,15 +161,16 @@ function createRouteErrorEvent(error, request, {
193
161
  const url = safeUrl(request);
194
162
  const routePath = routeTemplateOnly(routeTemplate);
195
163
  const method = request?.method ?? "GET";
196
- const message = error instanceof Error ? error.message : String(error);
197
164
  const routeTrace = trace ?? getActiveLogBrewTrace();
198
165
  return {
199
166
  id: idFactory(request, routePath),
200
167
  timestamp: now(),
201
- attributes: {
168
+ attributes: createIssueAttributesFromError(error, {
202
169
  title: `${method} ${routePath} failed`,
203
- level: "error",
204
- message,
170
+ mechanism: "nextjs.route_handler",
171
+ handled: false,
172
+ source: "nextjs.route_handler",
173
+ includeErrorStack,
205
174
  metadata: {
206
175
  framework: "nextjs",
207
176
  method,
@@ -210,7 +179,7 @@ function createRouteErrorEvent(error, request, {
210
179
  ...(includeSearchParams ? { search: url.search || null } : {}),
211
180
  ...traceMetadata(routeTrace)
212
181
  }
213
- }
182
+ })
214
183
  };
215
184
  }
216
185
 
@@ -272,10 +241,43 @@ function resolveRequestErrorClient(options, runtime) {
272
241
  return { client: createLogBrewNextClient(options), owned: true };
273
242
  }
274
243
 
275
- function createRouteHelpers(client, transport, trace) {
244
+ // Users belong to one route request, so one request's user never reaches another request.
245
+ const routeSubjects = new WeakMap();
246
+ const MAX_USER_ID_LENGTH = 200;
247
+
248
+ function setRouteUser(request, id, { kind = "user" } = {}) {
249
+ const normalized = typeof id === "string" ? id.trim() : "";
250
+ const characters = Array.from(normalized);
251
+ if (characters.length === 0 || characters.length > MAX_USER_ID_LENGTH || characters.some((character) => {
252
+ const code = character.codePointAt(0);
253
+ return code <= 31 || (code >= 127 && code <= 159);
254
+ })) {
255
+ throw new SdkError("configuration_error", `LogBrew user id must be 1-${MAX_USER_ID_LENGTH} characters without control characters`);
256
+ }
257
+ if (kind !== "user" && kind !== "anonymous") {
258
+ throw new SdkError("configuration_error", "LogBrew user kind must be user or anonymous");
259
+ }
260
+ if (!request || typeof request !== "object") {
261
+ return false;
262
+ }
263
+ routeSubjects.set(request, { id: normalized, kind });
264
+ return true;
265
+ }
266
+
267
+ function withRouteSubject(attributes, request) {
268
+ const subject = request && typeof request === "object" ? routeSubjects.get(request) : undefined;
269
+ if (!subject || attributes?.context?.subject) {
270
+ return attributes;
271
+ }
272
+ return { ...attributes, context: { ...(attributes.context ?? { schemaVersion: 1 }), subject } };
273
+ }
274
+
275
+ function createRouteHelpers(client, transport, trace, request) {
276
276
  return {
277
277
  client,
278
278
  logbrew: client,
279
+ // Tags this request's route span and route error issue with an opaque app-owned user ID.
280
+ setUser: (id, options) => setRouteUser(request, id, options),
279
281
  trace,
280
282
  previewJson: () => client.previewJson(),
281
283
  flush: () => client.flush(transport),
@@ -344,7 +346,7 @@ function recordRouteRequest(options, { request, response, context, client, durat
344
346
  routeTemplate: resolveRouteTemplate(options, request, context),
345
347
  trace
346
348
  });
347
- captureRouteRequestEvent(client, event);
349
+ captureRouteRequestEvent(client, { ...event, attributes: withRouteSubject(event.attributes, request) });
348
350
  }
349
351
 
350
352
  function recordRouteMetric(options, { request, response, context, client, durationMs, trace }) {
@@ -372,7 +374,7 @@ async function recordRouteError(options, error, runtime) {
372
374
  routeTemplate: resolveRouteTemplate(options, request, context),
373
375
  trace: routeTrace
374
376
  });
375
- client.issue(event.id, event.timestamp, event.attributes);
377
+ client.issue(event.id, event.timestamp, withRouteSubject(event.attributes, request));
376
378
  }
377
379
  } catch (captureError) {
378
380
  await notifyFailure(options, captureError, { request, context, client, trace: routeTrace });
@@ -404,10 +406,6 @@ function defaultRouteErrorId() {
404
406
  return `evt_next_error_${randomHex(8)}`;
405
407
  }
406
408
 
407
- function defaultNextRequestErrorId() {
408
- return `evt_next_request_error_${randomHex(8)}`;
409
- }
410
-
411
409
  function defaultRouteMetricId() {
412
410
  return `evt_next_metric_${randomHex(8)}`;
413
411
  }
@@ -420,87 +418,6 @@ function safeUrl(request) {
420
418
  }
421
419
  }
422
420
 
423
- function nextRequestMethod(request) {
424
- const method = typeof request?.method === "string" ? request.method.trim().toUpperCase() : "";
425
- return /^[A-Z]{1,16}$/u.test(method) ? method : "UNKNOWN";
426
- }
427
-
428
- function nextRoutePath(value) {
429
- if (typeof value !== "string" || value.trim() === "") {
430
- return "/";
431
- }
432
- let pathname;
433
- try {
434
- pathname = new URL(value, "http://localhost").pathname;
435
- } catch {
436
- return "/";
437
- }
438
- if (typeof pathname !== "string" || pathname === "") {
439
- return "/";
440
- }
441
- const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
442
- return normalized.length <= MAX_REQUEST_ROUTE_PATH_LENGTH ? normalized : "/";
443
- }
444
-
445
- function nextCategoricalMetadata(key, value, allowed) {
446
- return typeof value === "string" && allowed.has(value) ? { [key]: value } : {};
447
- }
448
-
449
- function nextErrorDigest(error) {
450
- const digest = error && typeof error === "object" ? error.digest : undefined;
451
- if (typeof digest !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/u.test(digest)) {
452
- return undefined;
453
- }
454
- return digest;
455
- }
456
-
457
- function nextErrorMessage(error) {
458
- let message;
459
- try {
460
- message = error instanceof Error ? error.message : String(error);
461
- } catch {
462
- message = "Next.js request failed";
463
- }
464
- const normalized = typeof message === "string" && message.trim() !== ""
465
- ? message
466
- : "Next.js request failed";
467
- return normalized.length <= MAX_REQUEST_ERROR_MESSAGE_LENGTH
468
- ? normalized
469
- : `${normalized.slice(0, MAX_REQUEST_ERROR_MESSAGE_LENGTH - 1)}…`;
470
- }
471
-
472
- function nextRequestTraceMetadata(request) {
473
- try {
474
- const traceparent = getTraceparentHeader(request);
475
- if (!traceparent) {
476
- return {};
477
- }
478
- const trace = parseTraceparent(traceparent);
479
- return {
480
- traceId: trace.traceId,
481
- parentSpanId: trace.parentSpanId,
482
- sampled: trace.sampled
483
- };
484
- } catch {
485
- return {};
486
- }
487
- }
488
-
489
- function getTraceparentHeader(request) {
490
- const headers = request?.headers;
491
- if (!headers) {
492
- return undefined;
493
- }
494
- let value;
495
- if (typeof headers.get === "function") {
496
- value = headers.get("traceparent");
497
- } else {
498
- const names = Object.keys(headers).filter(name => name.toLowerCase() === "traceparent");
499
- value = names.length === 1 ? headers[names[0]] : undefined;
500
- }
501
- return typeof value === "string" ? value : undefined;
502
- }
503
-
504
421
  function resolveRouteTemplate(options, request, context) {
505
422
  const value = typeof options.routeTemplate === "function"
506
423
  ? options.routeTemplate(request, context)
@@ -613,27 +530,6 @@ function nowMs(options) {
613
530
  return performance.now();
614
531
  }
615
532
 
616
- function randomHex(byteLength) {
617
- const bytes = new Uint8Array(byteLength);
618
- if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
619
- globalThis.crypto.getRandomValues(bytes);
620
- } else {
621
- for (let index = 0; index < bytes.length; index += 1) {
622
- bytes[index] = Math.floor(Math.random() * 256);
623
- }
624
- }
625
- const value = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
626
- return /^0+$/.test(value) ? "0000000000000001" : value;
627
- }
628
-
629
- function readEnvApiKey() {
630
- return globalThis.process?.env?.LOGBREW_API_KEY;
631
- }
632
-
633
- function readEnvServerApiKey() {
634
- return globalThis.process?.env?.LOGBREW_SERVER_API_KEY;
635
- }
636
-
637
533
  module.exports = {
638
534
  createLogBrewNextClient,
639
535
  createLogBrewNextRequestErrorHandler,
package/index.d.cts CHANGED
@@ -75,6 +75,7 @@ export type LogBrewNextRequestErrorOptions = CreateLogBrewNextClientConfig & Nod
75
75
  transport?: Transport | ((context: LogBrewNextRequestErrorInput & { client: LogBrewClient }) => Transport);
76
76
  /** Opt into a query-free concrete pathname. Stable routePath metadata remains the default. */
77
77
  includePathname?: boolean;
78
+ /** Include raw stack text in issue metadata. Structured frames are always captured. Defaults to false. */
78
79
  now?: () => string;
79
80
  idFactory?: (
80
81
  error: LogBrewNextRequestError,
@@ -105,6 +106,8 @@ export type LogBrewTraceContext = {
105
106
  };
106
107
 
107
108
  export type LogBrewRouteHelpers = {
109
+ /** Tag this request's route span and route error issue with an opaque app-owned user ID. */
110
+ setUser(id: string, options?: { kind?: "user" | "anonymous" }): boolean;
108
111
  client: LogBrewClient;
109
112
  logbrew: LogBrewClient;
110
113
  trace?: LogBrewTraceContext;
@@ -177,6 +180,8 @@ export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewN
177
180
  captureRequests?: boolean;
178
181
  captureRequestMetrics?: boolean;
179
182
  captureErrors?: boolean;
183
+ /** Include raw stack text in issue metadata. Structured frames are always captured. Defaults to false. */
184
+ includeErrorStack?: boolean;
180
185
  includeSearchParams?: boolean;
181
186
  metricName?: string;
182
187
  /** Supply a stable route template. Missing or invalid templates use "/" without reading the request pathname. */
@@ -224,6 +229,7 @@ export declare function createNextRequestErrorEvent(
224
229
  request: LogBrewNextRequestErrorRequest,
225
230
  context: LogBrewNextRequestErrorContext,
226
231
  options?: {
232
+ includeErrorStack?: boolean;
227
233
  includePathname?: boolean;
228
234
  now?: () => string;
229
235
  idFactory?: (
@@ -270,6 +276,7 @@ export declare function createRouteErrorEvent(
270
276
  error: unknown,
271
277
  request: Request,
272
278
  options?: {
279
+ includeErrorStack?: boolean;
273
280
  includeSearchParams?: boolean;
274
281
  now?: () => string;
275
282
  idFactory?: (request: Request, routeTemplate?: string) => string;
package/index.d.ts CHANGED
@@ -75,6 +75,7 @@ export type LogBrewNextRequestErrorOptions = CreateLogBrewNextClientConfig & Nod
75
75
  transport?: Transport | ((context: LogBrewNextRequestErrorInput & { client: LogBrewClient }) => Transport);
76
76
  /** Opt into a query-free concrete pathname. Stable routePath metadata remains the default. */
77
77
  includePathname?: boolean;
78
+ /** Include raw stack text in issue metadata. Structured frames are always captured. Defaults to false. */
78
79
  now?: () => string;
79
80
  idFactory?: (
80
81
  error: LogBrewNextRequestError,
@@ -105,6 +106,8 @@ export type LogBrewTraceContext = {
105
106
  };
106
107
 
107
108
  export type LogBrewRouteHelpers = {
109
+ /** Tag this request's route span and route error issue with an opaque app-owned user ID. */
110
+ setUser(id: string, options?: { kind?: "user" | "anonymous" }): boolean;
108
111
  client: LogBrewClient;
109
112
  logbrew: LogBrewClient;
110
113
  trace?: LogBrewTraceContext;
@@ -177,6 +180,8 @@ export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewN
177
180
  captureRequests?: boolean;
178
181
  captureRequestMetrics?: boolean;
179
182
  captureErrors?: boolean;
183
+ /** Include raw stack text in issue metadata. Structured frames are always captured. Defaults to false. */
184
+ includeErrorStack?: boolean;
180
185
  includeSearchParams?: boolean;
181
186
  metricName?: string;
182
187
  /** Supply a stable route template. Missing or invalid templates use "/" without reading the request pathname. */
@@ -224,6 +229,7 @@ export declare function createNextRequestErrorEvent(
224
229
  request: LogBrewNextRequestErrorRequest,
225
230
  context: LogBrewNextRequestErrorContext,
226
231
  options?: {
232
+ includeErrorStack?: boolean;
227
233
  includePathname?: boolean;
228
234
  now?: () => string;
229
235
  idFactory?: (
@@ -270,6 +276,7 @@ export declare function createRouteErrorEvent(
270
276
  error: unknown,
271
277
  request: Request,
272
278
  options?: {
279
+ includeErrorStack?: boolean;
273
280
  includeSearchParams?: boolean;
274
281
  now?: () => string;
275
282
  idFactory?: (request: Request, routeTemplate?: string) => string;
@@ -1,10 +1,18 @@
1
1
  let nodeHandlerPromise;
2
+ let edgeHandlerPromise;
2
3
 
3
4
  function createLogBrewNextRequestErrorHandler(options = {}) {
4
5
  let handler;
6
+ let edgeHandler;
5
7
  return async function logBrewNextRequestErrorHandler(error, request, context) {
6
8
  try {
7
- if (process.env.NEXT_RUNTIME !== "edge") {
9
+ if (process.env.NEXT_RUNTIME === "edge") {
10
+ // The Edge runtime has no Node.js modules; this path sends with fetch only.
11
+ edgeHandlerPromise ??= Promise.resolve().then(() => require("./edge.cjs"));
12
+ const edgeModule = await edgeHandlerPromise;
13
+ edgeHandler ??= edgeModule.createLogBrewNextEdgeRequestErrorHandler(options);
14
+ await edgeHandler(error, request, context);
15
+ } else {
8
16
  nodeHandlerPromise ??= Promise.resolve().then(() => require("./index.cjs"));
9
17
  const nodeModule = await nodeHandlerPromise;
10
18
  handler ??= nodeModule.createLogBrewNextRequestErrorHandler(options);
@@ -1,10 +1,18 @@
1
1
  let nodeHandlerPromise;
2
+ let edgeHandlerPromise;
2
3
 
3
4
  export function createLogBrewNextRequestErrorHandler(options = {}) {
4
5
  let handler;
6
+ let edgeHandler;
5
7
  return async function logBrewNextRequestErrorHandler(error, request, context) {
6
8
  try {
7
- if (process.env.NEXT_RUNTIME !== "edge") {
9
+ if (process.env.NEXT_RUNTIME === "edge") {
10
+ // The Edge runtime has no Node.js modules; this path sends with fetch only.
11
+ edgeHandlerPromise ??= import("./edge.js");
12
+ const edgeModule = await edgeHandlerPromise;
13
+ edgeHandler ??= edgeModule.createLogBrewNextEdgeRequestErrorHandler(options);
14
+ await edgeHandler(error, request, context);
15
+ } else {
8
16
  nodeHandlerPromise ??= import("./index.js");
9
17
  const module = await nodeHandlerPromise;
10
18
  handler ??= module.createLogBrewNextRequestErrorHandler(options);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logbrew/next",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "description": "Next.js App Router helpers for the public LogBrew JavaScript SDK.",
5
5
  "type": "module",
6
6
  "main": "./index.cjs",
@@ -57,6 +57,9 @@
57
57
  "index.d.ts",
58
58
  "index.d.cts",
59
59
  "client.cjs",
60
+ "edge.cjs",
61
+ "edge.js",
62
+ "request-error-event.cjs",
60
63
  "client.js",
61
64
  "client.d.ts",
62
65
  "client.d.cts",
@@ -97,6 +100,6 @@
97
100
  "react-dom": ">=18"
98
101
  },
99
102
  "scripts": {
100
- "test": "node --check index.js && node --check index.cjs && node --check client.js && node --check client.cjs && node --check instrumentation.js && node --check instrumentation.cjs && node --check release-artifacts.js && node --check release-artifacts.cjs && node --check examples/index.mjs && node --check examples/client-route-spans.mjs && node --check examples/readme-example.mjs && node --check examples/request-errors.mjs && node --check examples/real-user-smoke.mjs && node --test"
103
+ "test": "node --check index.js && node --check index.cjs && node --check client.js && node --check client.cjs && node --check instrumentation.js && node --check instrumentation.cjs && node --check edge.js && node --check edge.cjs && node --check request-error-event.cjs && node --check release-artifacts.js && node --check release-artifacts.cjs && node --check examples/index.mjs && node --check examples/client-route-spans.mjs && node --check examples/readme-example.mjs && node --check examples/request-errors.mjs && node --check examples/real-user-smoke.mjs && node --test"
101
104
  }
102
105
  }
@@ -0,0 +1,216 @@
1
+ "use strict";
2
+
3
+ // Request-error event building and deployment detection without Node-only imports, so the Edge runtime can use them.
4
+ const { createIssueAttributesFromError, parseTraceparent } = require("@logbrew/sdk");
5
+
6
+ const MAX_REQUEST_ERROR_MESSAGE_LENGTH = 2048;
7
+ const MAX_REQUEST_ROUTE_PATH_LENGTH = 512;
8
+ const NEXT_RENDER_SOURCES = new Set([
9
+ "react-server-components",
10
+ "react-server-components-payload",
11
+ "server-rendering"
12
+ ]);
13
+ const NEXT_RENDER_TYPES = new Set(["dynamic", "dynamic-resume"]);
14
+ const NEXT_REVALIDATE_REASONS = new Set(["on-demand", "stale"]);
15
+ const NEXT_ROUTE_TYPES = new Set(["action", "middleware", "proxy", "render", "route"]);
16
+ const NEXT_ROUTER_KINDS = new Set(["App Router", "Pages Router"]);
17
+
18
+ function createNextRequestErrorEvent(error, request = {}, context = {}, {
19
+ includeErrorStack = false,
20
+ includePathname = false,
21
+ now = () => new Date().toISOString(),
22
+ idFactory = defaultNextRequestErrorId
23
+ } = {}) {
24
+ const method = nextRequestMethod(request);
25
+ const routePath = nextRoutePath(context?.routePath);
26
+ const pathname = includePathname ? nextRoutePath(request?.path) : undefined;
27
+ const errorDigest = nextErrorDigest(error);
28
+ return {
29
+ id: idFactory(error, request, context),
30
+ timestamp: now(),
31
+ attributes: createIssueAttributesFromError(error, {
32
+ title: `${method} ${routePath} failed`,
33
+ message: nextErrorMessage(error),
34
+ mechanism: "nextjs.on_request_error",
35
+ handled: false,
36
+ source: "nextjs.on_request_error",
37
+ includeErrorStack,
38
+ metadata: {
39
+ framework: "nextjs",
40
+ method,
41
+ routePath,
42
+ ...nextCategoricalMetadata("routerKind", context?.routerKind, NEXT_ROUTER_KINDS),
43
+ ...nextCategoricalMetadata("routeType", context?.routeType, NEXT_ROUTE_TYPES),
44
+ ...nextCategoricalMetadata("renderSource", context?.renderSource, NEXT_RENDER_SOURCES),
45
+ ...nextCategoricalMetadata("revalidateReason", context?.revalidateReason, NEXT_REVALIDATE_REASONS),
46
+ ...nextCategoricalMetadata("renderType", context?.renderType, NEXT_RENDER_TYPES),
47
+ ...nextRequestTraceMetadata(request),
48
+ ...(errorDigest ? { errorDigest } : {}),
49
+ ...(pathname ? { pathname } : {})
50
+ }
51
+ })
52
+ };
53
+ }
54
+
55
+ function defaultNextRequestErrorId() {
56
+ return `evt_next_request_error_${randomHex(8)}`;
57
+ }
58
+
59
+ function nextRequestMethod(request) {
60
+ const method = typeof request?.method === "string" ? request.method.trim().toUpperCase() : "";
61
+ return /^[A-Z]{1,16}$/u.test(method) ? method : "UNKNOWN";
62
+ }
63
+
64
+ function nextRoutePath(value) {
65
+ if (typeof value !== "string" || value.trim() === "") {
66
+ return "/";
67
+ }
68
+ let pathname;
69
+ try {
70
+ pathname = new URL(value, "http://localhost").pathname;
71
+ } catch {
72
+ return "/";
73
+ }
74
+ if (typeof pathname !== "string" || pathname === "") {
75
+ return "/";
76
+ }
77
+ const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
78
+ return normalized.length <= MAX_REQUEST_ROUTE_PATH_LENGTH ? normalized : "/";
79
+ }
80
+
81
+ function nextCategoricalMetadata(key, value, allowed) {
82
+ return typeof value === "string" && allowed.has(value) ? { [key]: value } : {};
83
+ }
84
+
85
+ function nextErrorDigest(error) {
86
+ const digest = error && typeof error === "object" ? error.digest : undefined;
87
+ if (typeof digest !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/u.test(digest)) {
88
+ return undefined;
89
+ }
90
+ return digest;
91
+ }
92
+
93
+ function nextErrorMessage(error) {
94
+ let message;
95
+ try {
96
+ message = error instanceof Error ? error.message : String(error);
97
+ } catch {
98
+ message = "Next.js request failed";
99
+ }
100
+ const normalized = typeof message === "string" && message.trim() !== ""
101
+ ? message
102
+ : "Next.js request failed";
103
+ return normalized.length <= MAX_REQUEST_ERROR_MESSAGE_LENGTH
104
+ ? normalized
105
+ : `${normalized.slice(0, MAX_REQUEST_ERROR_MESSAGE_LENGTH - 1)}…`;
106
+ }
107
+
108
+ function nextRequestTraceMetadata(request) {
109
+ try {
110
+ const traceparent = getTraceparentHeader(request);
111
+ if (!traceparent) {
112
+ return {};
113
+ }
114
+ const trace = parseTraceparent(traceparent);
115
+ return {
116
+ traceId: trace.traceId,
117
+ parentSpanId: trace.parentSpanId,
118
+ sampled: trace.sampled
119
+ };
120
+ } catch {
121
+ return {};
122
+ }
123
+ }
124
+
125
+ function getTraceparentHeader(request) {
126
+ const headers = request?.headers;
127
+ if (!headers) {
128
+ return undefined;
129
+ }
130
+ let value;
131
+ if (typeof headers.get === "function") {
132
+ value = headers.get("traceparent");
133
+ } else {
134
+ const names = Object.keys(headers).filter(name => name.toLowerCase() === "traceparent");
135
+ value = names.length === 1 ? headers[names[0]] : undefined;
136
+ }
137
+ return typeof value === "string" ? value : undefined;
138
+ }
139
+
140
+ function randomHex(byteLength) {
141
+ const bytes = new Uint8Array(byteLength);
142
+ if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
143
+ globalThis.crypto.getRandomValues(bytes);
144
+ } else {
145
+ for (let index = 0; index < bytes.length; index += 1) {
146
+ bytes[index] = Math.floor(Math.random() * 256);
147
+ }
148
+ }
149
+ const value = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
150
+ return /^0+$/.test(value) ? "0000000000000001" : value;
151
+ }
152
+
153
+ function readEnvApiKey() {
154
+ return globalThis.process?.env?.LOGBREW_API_KEY;
155
+ }
156
+
157
+ function readEnvServerApiKey() {
158
+ return globalThis.process?.env?.LOGBREW_SERVER_API_KEY;
159
+ }
160
+
161
+ // Release, environment, and service from LOGBREW_* variables, then Vercel's system variables.
162
+ function nextDeploymentContext(context, env = globalThis.process?.env ?? {}) {
163
+ const release = boundedEnv(env.LOGBREW_RELEASE) ?? boundedEnv(env.VERCEL_GIT_COMMIT_SHA);
164
+ const environment = boundedEnv(env.LOGBREW_ENVIRONMENT) ?? boundedEnv(env.VERCEL_ENV);
165
+ const service = boundedEnv(env.LOGBREW_SERVICE_NAME);
166
+ return mergeDeployment(context, { release, environment, service });
167
+ }
168
+
169
+ function mergeDeployment(context, { release, environment, service }) {
170
+ if (release === undefined && environment === undefined && service === undefined) {
171
+ return context;
172
+ }
173
+ if (context !== undefined && (context === null || typeof context !== "object" || context.schemaVersion !== 1)) {
174
+ return context;
175
+ }
176
+ const resource = context?.resource ?? {};
177
+ const deployment = {
178
+ ...(environment === undefined ? {} : { environment }),
179
+ ...(release === undefined ? {} : { release }),
180
+ ...resource.deployment
181
+ };
182
+ return {
183
+ ...(context ?? { schemaVersion: 1 }),
184
+ resource: {
185
+ ...resource,
186
+ ...(Object.keys(deployment).length === 0 ? {} : { deployment }),
187
+ ...(service === undefined || resource.service ? {} : { service: { name: service } })
188
+ }
189
+ };
190
+ }
191
+
192
+ function boundedEnv(value) {
193
+ if (typeof value !== "string") {
194
+ return undefined;
195
+ }
196
+ const normalized = value.trim();
197
+ const characters = Array.from(normalized);
198
+ if (characters.length === 0 || characters.length > 256 || characters.some((character) => {
199
+ const code = character.codePointAt(0);
200
+ return code <= 31 || (code >= 127 && code <= 159);
201
+ })) {
202
+ return undefined;
203
+ }
204
+ return normalized;
205
+ }
206
+
207
+ module.exports = {
208
+ createNextRequestErrorEvent,
209
+ getTraceparentHeader,
210
+ mergeDeployment,
211
+ nextDeploymentContext,
212
+ nextRoutePath,
213
+ randomHex,
214
+ readEnvApiKey,
215
+ readEnvServerApiKey
216
+ };