@logbrew/next 0.1.4 → 0.1.6

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/README.md CHANGED
@@ -93,7 +93,7 @@ export default withLogBrewNextReleaseArtifacts(
93
93
  service: "checkout-next-web",
94
94
  projectId: "550e8400-e29b-41d4-a716-446655440000",
95
95
  upload: {
96
- endpoint: "https://api.logbrew.com/api/release-artifacts",
96
+ endpoint: "https://api.logbrew.co/api/release-artifacts",
97
97
  allowHostedUpload: true,
98
98
  maxRetries: 2
99
99
  }
@@ -196,11 +196,11 @@ export const POST = withLogBrewRouteHandler(handler, {
196
196
  });
197
197
  ```
198
198
 
199
- By default, successful Route Handler responses are captured after your handler returns. When the incoming `Request` has a valid W3C `traceparent` header, the wrapper exposes a normalized trace object through `helpers.trace` and `getActiveLogBrewTrace()`, then records the request as a LogBrew `span` that continues the incoming trace. Use that same `traceId` and `spanId` in app-owned logs, product actions, or custom event callbacks when you want route-level debugging correlation. Requests without `traceparent`, or with a malformed header, fall back to a request `log` event so bad client headers do not break your route. Use `captureRequests: false` when a route should only flush manual events, use `spanIdFactory` when your runtime needs app-provided child span IDs, and use `onCaptureError` to observe telemetry delivery failures without letting observability own the route response.
199
+ By default, successful Route Handler responses are captured after your handler returns. When the incoming `Request` has a valid W3C `traceparent` header, the wrapper exposes a normalized trace object through `helpers.trace` and `getActiveLogBrewTrace()`, then records an `http.server` span that continues the incoming trace. Stable `routeTemplate` input controls both request names and metadata so concrete identifiers are not retained. Use that same `traceId` and `spanId` in app-owned logs, product actions, or custom event callbacks when you want route-level debugging correlation. Requests without `traceparent`, or with a malformed header, fall back to a request `log` event so bad client headers do not break your route. Use `captureRequests: false` when a route should only flush manual events, use `spanIdFactory` when your runtime needs app-provided child span IDs, and use `onCaptureError` to observe telemetry delivery failures without letting observability own the route response.
200
200
 
201
201
  The public trace helper only includes normalized W3C IDs plus sampled state: `traceId`, `spanId`, `parentSpanId`, and `sampled`. It does not expose the raw `traceparent` header, request headers, request bodies, cookies, or query strings.
202
202
 
203
- Automatic route error events record the method and pathname, but omit query strings by default. Pass `includeSearchParams: true` only when query capture is intentional and safe for the route.
203
+ Automatic route error events use the same stable `routeTemplate` for their title and `http.server` metadata. Generated event IDs are random so repeated requests remain separate occurrences. Query strings stay absent by default. Pass `includeSearchParams: true` only when query capture is intentional and safe for the route.
204
204
 
205
205
  Request metrics are opt-in. Enable `captureRequestMetrics` when you want the route wrapper to emit an explicit `http.server.duration` histogram for completed App Router requests:
206
206
 
@@ -232,7 +232,7 @@ import {
232
232
  const client = createLogBrewNextBrowserClient({
233
233
  clientKey: "LOGBREW_CLIENT_KEY",
234
234
  sdkName: "my-next-app",
235
- sdkVersion: "0.1.3"
235
+ sdkVersion: "0.1.6"
236
236
  });
237
237
 
238
238
  const routePatterns = [
@@ -255,7 +255,7 @@ export function LogBrewNextNavigationSpans({ traceparent }) {
255
255
  }
256
256
  ```
257
257
 
258
- `useLogBrewNextNavigation` records one `next.route <routeTemplate>` span when `pathname` changes to a route that matches one of your stable `routePatterns`. Use `createNextRouteTemplate` directly when you want to preview how a concrete `pathname` maps to `/projects/[projectId]/settings`, `[...catchAll]`, `[[...optionalCatchAll]]`, or a route-group pattern such as `/(app)/dashboard/[teamId]`.
258
+ `useLogBrewNextNavigation` records one `browser.navigation` span named `next.route <routeTemplate>` when `pathname` changes to a route that matches one of your stable `routePatterns`. Use `createNextRouteTemplate` directly when you want to preview how a concrete `pathname` maps to `/projects/[projectId]/settings`, `[...catchAll]`, `[[...optionalCatchAll]]`, or a route-group pattern such as `/(app)/dashboard/[teamId]`.
259
259
 
260
260
  The client helper requires explicit W3C trace context through `traceparent` or `traceId` plus `spanId`. It does not patch `fetch`, `XMLHttpRequest`, browser history, or the Next router. It never records the concrete pathname, query string, hash, headers, cookies, request body, or raw `traceparent` value. If a pathname cannot be matched to a stable route template, it skips the span instead of emitting a high-cardinality URL. Metadata is primitive-only.
261
261
 
@@ -269,7 +269,7 @@ import { createLogBrewNextClient } from "@logbrew/next";
269
269
  const client = createLogBrewNextClient({
270
270
  serverApiKey: "LOGBREW_SERVER_API_KEY",
271
271
  sdkName: "my-next-app",
272
- sdkVersion: "0.1.3"
272
+ sdkVersion: "0.1.6"
273
273
  });
274
274
  ```
275
275
 
package/client.cjs CHANGED
@@ -8,7 +8,7 @@ const {
8
8
  } = require("@logbrew/sdk");
9
9
 
10
10
  const DEFAULT_SDK_NAME = "logbrew-next-client";
11
- const DEFAULT_SDK_VERSION = "0.1.3";
11
+ const DEFAULT_SDK_VERSION = "0.1.6";
12
12
 
13
13
  function createLogBrewNextBrowserClient({
14
14
  apiKey,
@@ -56,8 +56,7 @@ function createNextRouteTemplate({
56
56
  .map((pattern) => normalizeRouteTemplate(pattern))
57
57
  .filter((pattern) => pattern && routePatternMatchesPathname(pattern, safePathname));
58
58
 
59
- const matched = matches.sort(compareRouteSpecificity)[0];
60
- return matched;
59
+ return matches.sort(compareRouteSpecificity)[0];
61
60
  }
62
61
 
63
62
  function createNextNavigationSpanEvent({
@@ -99,6 +98,7 @@ function createNextNavigationSpanEvent({
99
98
  framework: "nextjs",
100
99
  navigationIndex,
101
100
  navigationType,
101
+ operation: "browser.navigation",
102
102
  routeTemplate: safeRouteTemplate,
103
103
  source: "next.client.route",
104
104
  ...metadata
@@ -132,7 +132,7 @@ function useLogBrewNextNavigation(options = {}) {
132
132
  if (!routeTemplate) {
133
133
  return;
134
134
  }
135
- const navigationKey = nextNavigationKey(options.pathname, routeTemplate);
135
+ const navigationKey = `${routeTemplate}|${pathnameOnly(options.pathname) ?? ""}`;
136
136
  if (navigationKey === lastNavigationKey.current) {
137
137
  return;
138
138
  }
@@ -184,10 +184,6 @@ function traceContextFromInput({ parentSpanId, spanId, spanIdFactory, traceId, t
184
184
  return { parentSpanId, spanId, traceId };
185
185
  }
186
186
 
187
- function nextNavigationKey(pathname, routeTemplate) {
188
- return `${routeTemplate}|${pathnameOnly(pathname) ?? ""}`;
189
- }
190
-
191
187
  function normalizeRouteTemplate(value) {
192
188
  const pathname = pathnameOnly(value);
193
189
  if (!pathname) {
@@ -195,18 +191,13 @@ function normalizeRouteTemplate(value) {
195
191
  }
196
192
  const segments = pathname
197
193
  .split("/")
198
- .filter(Boolean)
199
- .filter((segment) => !isRouteGroupSegment(segment) && !segment.startsWith("@"));
194
+ .filter((segment) => segment && !(segment.startsWith("(") && segment.endsWith(")")) && !segment.startsWith("@"));
200
195
  if (segments.length === 0) {
201
196
  return "/";
202
197
  }
203
198
  return `/${segments.join("/")}`;
204
199
  }
205
200
 
206
- function isRouteGroupSegment(segment) {
207
- return segment.startsWith("(") && segment.endsWith(")");
208
- }
209
-
210
201
  function pathnameOnly(value) {
211
202
  if (value === undefined || value === null) {
212
203
  return undefined;
@@ -217,7 +208,7 @@ function pathnameOnly(value) {
217
208
  }
218
209
  const withoutQueryOrHash = trimmed.split(/[?#]/u, 1)[0];
219
210
  let pathname = withoutQueryOrHash;
220
- if (hasUrlScheme(withoutQueryOrHash)) {
211
+ if (/^[a-z][a-z0-9+.-]*:/iu.test(withoutQueryOrHash)) {
221
212
  try {
222
213
  pathname = new URL(withoutQueryOrHash).pathname;
223
214
  } catch {
@@ -230,10 +221,6 @@ function pathnameOnly(value) {
230
221
  return pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
231
222
  }
232
223
 
233
- function hasUrlScheme(url) {
234
- return /^[a-z][a-z0-9+.-]*:/iu.test(url);
235
- }
236
-
237
224
  function routePatternMatchesPathname(routePattern, pathname) {
238
225
  const patternSegments = routePattern.split("/").filter(Boolean);
239
226
  const pathSegments = pathname.split("/").filter(Boolean);
@@ -303,15 +290,8 @@ function isOptionalCatchAllSegment(segment) {
303
290
  return /^\[\[\.\.\.[^[\]]+\]\]$/u.test(segment);
304
291
  }
305
292
 
306
- function defaultNextNavigationSpanId({ routeTemplate }) {
307
- return `evt_next_route_${slugify(routeTemplate ?? "route")}`;
308
- }
309
-
310
- function slugify(value) {
311
- return String(value)
312
- .toLowerCase()
313
- .replace(/[^a-z0-9]+/g, "_")
314
- .replace(/^_+|_+$/g, "") || "event";
293
+ function defaultNextNavigationSpanId() {
294
+ return `evt_next_route_${randomHex(8)}`;
315
295
  }
316
296
 
317
297
  function defaultSpanIdFactory() {
package/client.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  } from "@logbrew/sdk";
9
9
 
10
10
  const DEFAULT_SDK_NAME = "logbrew-next-client";
11
- const DEFAULT_SDK_VERSION = "0.1.3";
11
+ const DEFAULT_SDK_VERSION = "0.1.6";
12
12
 
13
13
  export function createLogBrewNextBrowserClient({
14
14
  apiKey,
@@ -56,8 +56,7 @@ export function createNextRouteTemplate({
56
56
  .map((pattern) => normalizeRouteTemplate(pattern))
57
57
  .filter((pattern) => pattern && routePatternMatchesPathname(pattern, safePathname));
58
58
 
59
- const matched = matches.sort(compareRouteSpecificity)[0];
60
- return matched;
59
+ return matches.sort(compareRouteSpecificity)[0];
61
60
  }
62
61
 
63
62
  export function createNextNavigationSpanEvent({
@@ -99,6 +98,7 @@ export function createNextNavigationSpanEvent({
99
98
  framework: "nextjs",
100
99
  navigationIndex,
101
100
  navigationType,
101
+ operation: "browser.navigation",
102
102
  routeTemplate: safeRouteTemplate,
103
103
  source: "next.client.route",
104
104
  ...metadata
@@ -132,7 +132,7 @@ export function useLogBrewNextNavigation(options = {}) {
132
132
  if (!routeTemplate) {
133
133
  return;
134
134
  }
135
- const navigationKey = nextNavigationKey(options.pathname, routeTemplate);
135
+ const navigationKey = `${routeTemplate}|${pathnameOnly(options.pathname) ?? ""}`;
136
136
  if (navigationKey === lastNavigationKey.current) {
137
137
  return;
138
138
  }
@@ -184,10 +184,6 @@ function traceContextFromInput({ parentSpanId, spanId, spanIdFactory, traceId, t
184
184
  return { parentSpanId, spanId, traceId };
185
185
  }
186
186
 
187
- function nextNavigationKey(pathname, routeTemplate) {
188
- return `${routeTemplate}|${pathnameOnly(pathname) ?? ""}`;
189
- }
190
-
191
187
  function normalizeRouteTemplate(value) {
192
188
  const pathname = pathnameOnly(value);
193
189
  if (!pathname) {
@@ -195,18 +191,13 @@ function normalizeRouteTemplate(value) {
195
191
  }
196
192
  const segments = pathname
197
193
  .split("/")
198
- .filter(Boolean)
199
- .filter((segment) => !isRouteGroupSegment(segment) && !segment.startsWith("@"));
194
+ .filter((segment) => segment && !(segment.startsWith("(") && segment.endsWith(")")) && !segment.startsWith("@"));
200
195
  if (segments.length === 0) {
201
196
  return "/";
202
197
  }
203
198
  return `/${segments.join("/")}`;
204
199
  }
205
200
 
206
- function isRouteGroupSegment(segment) {
207
- return segment.startsWith("(") && segment.endsWith(")");
208
- }
209
-
210
201
  function pathnameOnly(value) {
211
202
  if (value === undefined || value === null) {
212
203
  return undefined;
@@ -217,7 +208,7 @@ function pathnameOnly(value) {
217
208
  }
218
209
  const withoutQueryOrHash = trimmed.split(/[?#]/u, 1)[0];
219
210
  let pathname = withoutQueryOrHash;
220
- if (hasUrlScheme(withoutQueryOrHash)) {
211
+ if (/^[a-z][a-z0-9+.-]*:/iu.test(withoutQueryOrHash)) {
221
212
  try {
222
213
  pathname = new URL(withoutQueryOrHash).pathname;
223
214
  } catch {
@@ -230,10 +221,6 @@ function pathnameOnly(value) {
230
221
  return pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
231
222
  }
232
223
 
233
- function hasUrlScheme(url) {
234
- return /^[a-z][a-z0-9+.-]*:/iu.test(url);
235
- }
236
-
237
224
  function routePatternMatchesPathname(routePattern, pathname) {
238
225
  const patternSegments = routePattern.split("/").filter(Boolean);
239
226
  const pathSegments = pathname.split("/").filter(Boolean);
@@ -303,15 +290,8 @@ function isOptionalCatchAllSegment(segment) {
303
290
  return /^\[\[\.\.\.[^[\]]+\]\]$/u.test(segment);
304
291
  }
305
292
 
306
- function defaultNextNavigationSpanId({ routeTemplate }) {
307
- return `evt_next_route_${slugify(routeTemplate ?? "route")}`;
308
- }
309
-
310
- function slugify(value) {
311
- return String(value)
312
- .toLowerCase()
313
- .replace(/[^a-z0-9]+/g, "_")
314
- .replace(/^_+|_+$/g, "") || "event";
293
+ function defaultNextNavigationSpanId() {
294
+ return `evt_next_route_${randomHex(8)}`;
315
295
  }
316
296
 
317
297
  function defaultSpanIdFactory() {
@@ -11,9 +11,7 @@ const routeTemplate = createNextRouteTemplate({
11
11
  });
12
12
 
13
13
  const client = createLogBrewNextBrowserClient({
14
- clientKey: "LOGBREW_CLIENT_KEY",
15
- sdkName: "logbrew-next-client-route-example",
16
- sdkVersion: "0.1.3"
14
+ clientKey: "LOGBREW_CLIENT_KEY"
17
15
  });
18
16
 
19
17
  const event = captureNextNavigation(client, {
@@ -25,7 +23,8 @@ const event = captureNextNavigation(client, {
25
23
  durationMs: 19
26
24
  });
27
25
 
28
- if (!event || event.attributes.metadata.routeTemplate !== "/projects/[projectId]/settings") {
26
+ const payload = JSON.parse(client.previewJson());
27
+ if (!event || event.attributes.metadata.routeTemplate !== "/projects/[projectId]/settings" || event.attributes.metadata.operation !== "browser.navigation" || payload.sdk.version !== "0.1.6") {
29
28
  throw new Error(`unexpected Next client route span: ${JSON.stringify(event)}`);
30
29
  }
31
30
 
@@ -12,7 +12,7 @@ const POST = withLogBrewRouteHandler(
12
12
  serverApiKey: "LOGBREW_SERVER_API_KEY",
13
13
  captureRequests: false,
14
14
  sdkName: "logbrew-next-readme-example",
15
- sdkVersion: "0.1.3",
15
+ sdkVersion: "0.1.6",
16
16
  transport
17
17
  }
18
18
  );
@@ -12,7 +12,7 @@ const POST = withLogBrewRouteHandler(
12
12
  serverApiKey: "LOGBREW_SERVER_API_KEY",
13
13
  captureRequests: false,
14
14
  sdkName: "logbrew-next-real-user-smoke",
15
- sdkVersion: "0.1.3",
15
+ sdkVersion: "0.1.6",
16
16
  maxRetries: 1,
17
17
  transport
18
18
  }
package/index.cjs CHANGED
@@ -7,7 +7,7 @@ const {
7
7
  const { createNodeFetchTransport } = require("@logbrew/node");
8
8
 
9
9
  const DEFAULT_SDK_NAME = "logbrew-next";
10
- const DEFAULT_SDK_VERSION = "0.1.3";
10
+ const DEFAULT_SDK_VERSION = "0.1.6";
11
11
  const MAX_REQUEST_ERROR_MESSAGE_LENGTH = 2048;
12
12
  const MAX_REQUEST_ROUTE_PATH_LENGTH = 512;
13
13
  const NEXT_RENDER_SOURCES = new Set([
@@ -49,7 +49,7 @@ function createLogBrewNextRequestErrorHandler(options = {}) {
49
49
  try {
50
50
  const resolvedClient = resolveRequestErrorClient(options, runtime);
51
51
  const client = resolvedClient.client;
52
- const transport = resolveRequestErrorTransport(options, { ...runtime, client }, defaultTransport);
52
+ const transport = resolveTransport(options, { ...runtime, client }, defaultTransport);
53
53
  runtime = { ...runtime, client, transport };
54
54
  const event = typeof options.errorEvent === "function"
55
55
  ? options.errorEvent(error, runtime)
@@ -113,7 +113,7 @@ function withLogBrewRouteHandler(handler, options = {}) {
113
113
 
114
114
  return async function logBrewRouteHandler(request, context = {}) {
115
115
  const client = resolveClient(options, request, context);
116
- const transport = resolveTransport(options, request, context, client, defaultTransport);
116
+ const transport = resolveTransport(options, { request, context, client }, defaultTransport);
117
117
  const trace = createRouteTraceContext(request, undefined, options);
118
118
  const helpers = createRouteHelpers(client, transport, trace);
119
119
  const startedAt = nowMs(options);
@@ -140,13 +140,14 @@ function createRouteRequestEvent(request, response, {
140
140
  now = () => new Date().toISOString(),
141
141
  durationMs = 0,
142
142
  idFactory = defaultRouteRequestId,
143
+ routeTemplate,
143
144
  spanIdFactory = defaultSpanIdFactory,
144
145
  trace
145
146
  } = {}) {
146
- const url = safeUrl(request);
147
+ const routePath = routeTemplateOnly(routeTemplate ?? safeUrl(request).pathname);
147
148
  const method = request?.method ?? "GET";
148
149
  const statusCode = Number(response?.status ?? 0);
149
- const id = idFactory(request, response);
150
+ const id = idFactory(request, response, routePath);
150
151
  const routeTrace = trace ?? getActiveLogBrewTrace() ?? createRouteTraceContext(request, response, { spanIdFactory });
151
152
  const spanEvent = routeTrace
152
153
  ? createTraceparentRouteSpan(routeTrace, {
@@ -154,7 +155,7 @@ function createRouteRequestEvent(request, response, {
154
155
  id,
155
156
  method,
156
157
  now,
157
- pathname: url.pathname,
158
+ routeTemplate: routePath,
158
159
  statusCode
159
160
  })
160
161
  : undefined;
@@ -166,13 +167,13 @@ function createRouteRequestEvent(request, response, {
166
167
  id,
167
168
  timestamp: now(),
168
169
  attributes: {
169
- message: `${method} ${url.pathname} ${statusCode}`,
170
+ message: `${method} ${routePath} ${statusCode}`,
170
171
  level: statusCode >= 500 ? "error" : "info",
171
172
  logger: "next",
172
173
  metadata: {
173
174
  framework: "nextjs",
174
175
  method,
175
- pathname: url.pathname,
176
+ routeTemplate: routePath,
176
177
  statusCode,
177
178
  durationMs
178
179
  }
@@ -184,22 +185,26 @@ function createRouteErrorEvent(error, request, {
184
185
  includeSearchParams = false,
185
186
  now = () => new Date().toISOString(),
186
187
  idFactory = defaultRouteErrorId,
188
+ routeTemplate,
187
189
  trace
188
190
  } = {}) {
189
191
  const url = safeUrl(request);
192
+ const routePath = routeTemplateOnly(routeTemplate ?? url.pathname);
190
193
  const method = request?.method ?? "GET";
191
194
  const message = error instanceof Error ? error.message : String(error);
192
195
  const routeTrace = trace ?? getActiveLogBrewTrace();
193
196
  return {
194
- id: idFactory(request),
197
+ id: idFactory(request, routePath),
195
198
  timestamp: now(),
196
199
  attributes: {
197
- title: `${method} ${url.pathname} failed`,
200
+ title: `${method} ${routePath} failed`,
198
201
  level: "error",
199
202
  message,
200
203
  metadata: {
204
+ framework: "nextjs",
201
205
  method,
202
- pathname: url.pathname,
206
+ operation: "http.server",
207
+ routeTemplate: routePath,
203
208
  ...(includeSearchParams ? { search: url.search || null } : {}),
204
209
  ...traceMetadata(routeTrace)
205
210
  }
@@ -248,9 +253,9 @@ function resolveClient(options, request, context) {
248
253
  return createLogBrewNextClient(options);
249
254
  }
250
255
 
251
- function resolveTransport(options, request, context, client, defaultTransport) {
256
+ function resolveTransport(options, runtime, defaultTransport) {
252
257
  if (typeof options.transport === "function") {
253
- return options.transport({ request, context, client });
258
+ return options.transport(runtime);
254
259
  }
255
260
  return options.transport ?? defaultTransport;
256
261
  }
@@ -265,13 +270,6 @@ function resolveRequestErrorClient(options, runtime) {
265
270
  return { client: createLogBrewNextClient(options), owned: true };
266
271
  }
267
272
 
268
- function resolveRequestErrorTransport(options, runtime, defaultTransport) {
269
- if (typeof options.transport === "function") {
270
- return options.transport(runtime);
271
- }
272
- return options.transport ?? defaultTransport;
273
- }
274
-
275
273
  function createRouteHelpers(client, transport, trace) {
276
274
  return {
277
275
  client,
@@ -326,6 +324,7 @@ function recordRouteRequest(options, { request, response, context, client, durat
326
324
  ...options,
327
325
  durationMs,
328
326
  idFactory: options.requestIdFactory,
327
+ routeTemplate: resolveRouteTemplate(options, request, context),
329
328
  trace
330
329
  });
331
330
  captureRouteRequestEvent(client, event);
@@ -351,7 +350,11 @@ async function recordRouteError(options, error, { request, context, client, tran
351
350
  const routeTrace = trace ?? getActiveLogBrewTrace();
352
351
  const event = typeof options.errorEvent === "function"
353
352
  ? options.errorEvent(error, { request, context, client, trace: routeTrace })
354
- : createRouteErrorEvent(error, request, { ...options, trace: routeTrace });
353
+ : createRouteErrorEvent(error, request, {
354
+ ...options,
355
+ routeTemplate: resolveRouteTemplate(options, request, context),
356
+ trace: routeTrace
357
+ });
355
358
  try {
356
359
  client.issue(event.id, event.timestamp, event.attributes);
357
360
  const flushResponse = await client.shutdown(transport);
@@ -373,39 +376,24 @@ function captureRouteMetricEvent(client, event) {
373
376
  client.metric(event.id, event.timestamp, event.attributes);
374
377
  }
375
378
 
376
- function defaultRouteRequestId(request, response) {
377
- const url = safeUrl(request);
378
- const slug = `${request?.method ?? "GET"}-${url.pathname}-${response?.status ?? 0}`
379
- .toLowerCase()
380
- .replace(/[^a-z0-9]+/g, "_")
381
- .replace(/^_+|_+$/g, "");
382
- return `evt_next_request_${slug || "route"}`;
379
+ function defaultRouteRequestId() {
380
+ return `evt_next_request_${randomHex(8)}`;
383
381
  }
384
382
 
385
383
  function defaultSpanIdFactory() {
386
384
  return randomHex(8);
387
385
  }
388
386
 
389
- function defaultRouteErrorId(request) {
390
- const url = safeUrl(request);
391
- const slug = `${request?.method ?? "GET"}-${url.pathname}`
392
- .toLowerCase()
393
- .replace(/[^a-z0-9]+/g, "_")
394
- .replace(/^_+|_+$/g, "");
395
- return `evt_next_error_${slug || "route"}`;
387
+ function defaultRouteErrorId() {
388
+ return `evt_next_error_${randomHex(8)}`;
396
389
  }
397
390
 
398
391
  function defaultNextRequestErrorId() {
399
392
  return `evt_next_request_error_${randomHex(8)}`;
400
393
  }
401
394
 
402
- function defaultRouteMetricId(request, response, routeTemplate = safeUrl(request).pathname) {
403
- const sanitizedRouteTemplate = routeTemplateOnly(routeTemplate);
404
- const slug = `${request?.method ?? "GET"}-${sanitizedRouteTemplate}-${response?.status ?? 0}`
405
- .toLowerCase()
406
- .replace(/[^a-z0-9]+/g, "_")
407
- .replace(/^_+|_+$/g, "");
408
- return `evt_next_metric_${slug || "route"}`;
395
+ function defaultRouteMetricId() {
396
+ return `evt_next_metric_${randomHex(8)}`;
409
397
  }
410
398
 
411
399
  function safeUrl(request) {
@@ -551,7 +539,7 @@ function createTraceparentRouteSpan(traceContext, {
551
539
  id,
552
540
  method,
553
541
  now,
554
- pathname,
542
+ routeTemplate,
555
543
  statusCode
556
544
  }) {
557
545
  if (!traceContext) {
@@ -563,7 +551,7 @@ function createTraceparentRouteSpan(traceContext, {
563
551
  timestamp: now(),
564
552
  type: "span",
565
553
  attributes: {
566
- name: `${method} ${pathname}`,
554
+ name: `${method} ${routeTemplate}`,
567
555
  traceId: traceContext.traceId,
568
556
  spanId: traceContext.spanId,
569
557
  parentSpanId: traceContext.parentSpanId,
@@ -572,7 +560,8 @@ function createTraceparentRouteSpan(traceContext, {
572
560
  metadata: {
573
561
  framework: "nextjs",
574
562
  method,
575
- pathname,
563
+ operation: "http.server",
564
+ routeTemplate,
576
565
  sampled: traceContext.sampled,
577
566
  statusCode
578
567
  }
package/index.d.cts CHANGED
@@ -181,9 +181,9 @@ export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewN
181
181
  routeTemplate?: string | ((request: Request, context: TContext) => string | null | undefined);
182
182
  now?: () => string;
183
183
  nowMs?: () => number;
184
- idFactory?: (request: Request) => string;
185
- requestIdFactory?: (request: Request, response: Response) => string;
186
- metricIdFactory?: (request: Request, response: Response) => string;
184
+ idFactory?: (request: Request, routeTemplate?: string) => string;
185
+ requestIdFactory?: (request: Request, response: Response, routeTemplate?: string) => string;
186
+ metricIdFactory?: (request: Request, response: Response, routeTemplate?: string) => string;
187
187
  spanIdFactory?: (request: Request, response?: Response) => string;
188
188
  requestEvent?: (
189
189
  request: Request,
@@ -245,7 +245,8 @@ export declare function createRouteRequestEvent(
245
245
  options?: {
246
246
  now?: () => string;
247
247
  durationMs?: number;
248
- idFactory?: (request: Request, response: Response) => string;
248
+ idFactory?: (request: Request, response: Response, routeTemplate?: string) => string;
249
+ routeTemplate?: string;
249
250
  spanIdFactory?: (request: Request, response?: Response) => string;
250
251
  trace?: LogBrewTraceContext;
251
252
  }
@@ -257,7 +258,7 @@ export declare function createRequestMetricEvent(
257
258
  options?: {
258
259
  now?: () => string;
259
260
  durationMs?: number;
260
- idFactory?: (request: Request, response: Response) => string;
261
+ idFactory?: (request: Request, response: Response, routeTemplate?: string) => string;
261
262
  metricName?: string;
262
263
  routeTemplate?: string;
263
264
  }
@@ -269,7 +270,8 @@ export declare function createRouteErrorEvent(
269
270
  options?: {
270
271
  includeSearchParams?: boolean;
271
272
  now?: () => string;
272
- idFactory?: (request: Request) => string;
273
+ idFactory?: (request: Request, routeTemplate?: string) => string;
274
+ routeTemplate?: string;
273
275
  trace?: LogBrewTraceContext;
274
276
  }
275
277
  ): LogBrewRouteErrorEvent;
package/index.d.ts CHANGED
@@ -181,9 +181,9 @@ export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewN
181
181
  routeTemplate?: string | ((request: Request, context: TContext) => string | null | undefined);
182
182
  now?: () => string;
183
183
  nowMs?: () => number;
184
- idFactory?: (request: Request) => string;
185
- requestIdFactory?: (request: Request, response: Response) => string;
186
- metricIdFactory?: (request: Request, response: Response) => string;
184
+ idFactory?: (request: Request, routeTemplate?: string) => string;
185
+ requestIdFactory?: (request: Request, response: Response, routeTemplate?: string) => string;
186
+ metricIdFactory?: (request: Request, response: Response, routeTemplate?: string) => string;
187
187
  spanIdFactory?: (request: Request, response?: Response) => string;
188
188
  requestEvent?: (
189
189
  request: Request,
@@ -245,7 +245,8 @@ export declare function createRouteRequestEvent(
245
245
  options?: {
246
246
  now?: () => string;
247
247
  durationMs?: number;
248
- idFactory?: (request: Request, response: Response) => string;
248
+ idFactory?: (request: Request, response: Response, routeTemplate?: string) => string;
249
+ routeTemplate?: string;
249
250
  spanIdFactory?: (request: Request, response?: Response) => string;
250
251
  trace?: LogBrewTraceContext;
251
252
  }
@@ -257,7 +258,7 @@ export declare function createRequestMetricEvent(
257
258
  options?: {
258
259
  now?: () => string;
259
260
  durationMs?: number;
260
- idFactory?: (request: Request, response: Response) => string;
261
+ idFactory?: (request: Request, response: Response, routeTemplate?: string) => string;
261
262
  metricName?: string;
262
263
  routeTemplate?: string;
263
264
  }
@@ -269,7 +270,8 @@ export declare function createRouteErrorEvent(
269
270
  options?: {
270
271
  includeSearchParams?: boolean;
271
272
  now?: () => string;
272
- idFactory?: (request: Request) => string;
273
+ idFactory?: (request: Request, routeTemplate?: string) => string;
274
+ routeTemplate?: string;
273
275
  trace?: LogBrewTraceContext;
274
276
  }
275
277
  ): LogBrewRouteErrorEvent;
package/index.js CHANGED
@@ -1,618 +1,6 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
- import {
3
- LogBrewClient,
4
- SdkError,
5
- parseTraceparent
6
- } from "@logbrew/sdk";
7
- import { createNodeFetchTransport } from "@logbrew/node";
1
+ import next from "./index.cjs";
8
2
 
9
- const DEFAULT_SDK_NAME = "logbrew-next";
10
- const DEFAULT_SDK_VERSION = "0.1.3";
11
- const MAX_REQUEST_ERROR_MESSAGE_LENGTH = 2048;
12
- const MAX_REQUEST_ROUTE_PATH_LENGTH = 512;
13
- const NEXT_RENDER_SOURCES = new Set([
14
- "react-server-components",
15
- "react-server-components-payload",
16
- "server-rendering"
17
- ]);
18
- const NEXT_RENDER_TYPES = new Set(["dynamic", "dynamic-resume"]);
19
- const NEXT_REVALIDATE_REASONS = new Set(["on-demand", "stale"]);
20
- const NEXT_ROUTE_TYPES = new Set(["action", "middleware", "proxy", "render", "route"]);
21
- const NEXT_ROUTER_KINDS = new Set(["App Router", "Pages Router"]);
22
- const activeTraceContext = new AsyncLocalStorage();
23
-
24
- export function createLogBrewNextClient({
25
- apiKey,
26
- serverApiKey,
27
- context,
28
- sdkName = DEFAULT_SDK_NAME,
29
- sdkVersion = DEFAULT_SDK_VERSION,
30
- maxRetries = 2
31
- } = {}) {
32
- const authKey = serverApiKey ?? apiKey ?? readEnvServerApiKey() ?? readEnvApiKey();
33
- if (!authKey) {
34
- throw new SdkError(
35
- "configuration_error",
36
- "createLogBrewNextClient requires serverApiKey, apiKey, LOGBREW_SERVER_API_KEY, or LOGBREW_API_KEY"
37
- );
38
- }
39
- return LogBrewClient.create({ apiKey: authKey, context, sdkName, sdkVersion, maxRetries });
40
- }
41
-
42
- export function createLogBrewNextRequestErrorHandler(options = {}) {
43
- const defaultTransport = options.transport === undefined
44
- ? createNodeFetchTransport(options)
45
- : undefined;
46
-
47
- return async function logBrewNextRequestErrorHandler(error, request = {}, context = {}) {
48
- let runtime = { error, request, context };
49
- try {
50
- const resolvedClient = resolveRequestErrorClient(options, runtime);
51
- const client = resolvedClient.client;
52
- const transport = resolveRequestErrorTransport(options, { ...runtime, client }, defaultTransport);
53
- runtime = { ...runtime, client, transport };
54
- const event = typeof options.errorEvent === "function"
55
- ? options.errorEvent(error, runtime)
56
- : createNextRequestErrorEvent(error, request, context, options);
57
-
58
- client.issue(event.id, event.timestamp, event.attributes);
59
- const response = resolvedClient.owned
60
- ? await client.shutdown(transport)
61
- : await client.flush(transport);
62
- await notifyFlush(options, response, runtime);
63
- } catch (captureError) {
64
- try {
65
- await notifyFailure(options, captureError, runtime);
66
- } catch {
67
- // Observability callbacks must not replace the application error Next.js is handling.
68
- }
69
- }
70
- };
71
- }
72
-
73
- export function createNextRequestErrorEvent(error, request = {}, context = {}, {
74
- includePathname = false,
75
- now = () => new Date().toISOString(),
76
- idFactory = defaultNextRequestErrorId
77
- } = {}) {
78
- const method = nextRequestMethod(request);
79
- const routePath = nextRoutePath(context?.routePath);
80
- const pathname = includePathname ? nextRoutePath(request?.path) : undefined;
81
- const errorDigest = nextErrorDigest(error);
82
- return {
83
- id: idFactory(error, request, context),
84
- timestamp: now(),
85
- attributes: {
86
- title: `${method} ${routePath} failed`,
87
- level: "error",
88
- message: nextErrorMessage(error),
89
- metadata: {
90
- framework: "nextjs",
91
- method,
92
- routePath,
93
- ...nextCategoricalMetadata("routerKind", context?.routerKind, NEXT_ROUTER_KINDS),
94
- ...nextCategoricalMetadata("routeType", context?.routeType, NEXT_ROUTE_TYPES),
95
- ...nextCategoricalMetadata("renderSource", context?.renderSource, NEXT_RENDER_SOURCES),
96
- ...nextCategoricalMetadata("revalidateReason", context?.revalidateReason, NEXT_REVALIDATE_REASONS),
97
- ...nextCategoricalMetadata("renderType", context?.renderType, NEXT_RENDER_TYPES),
98
- ...(errorDigest ? { errorDigest } : {}),
99
- ...(pathname ? { pathname } : {})
100
- }
101
- }
102
- };
103
- }
104
-
105
- export function withLogBrewRouteHandler(handler, options = {}) {
106
- if (typeof handler !== "function") {
107
- throw new SdkError("configuration_error", "withLogBrewRouteHandler requires a handler function");
108
- }
109
-
110
- const defaultTransport = options.transport === undefined
111
- ? createNodeFetchTransport(options)
112
- : undefined;
113
-
114
- return async function logBrewRouteHandler(request, context = {}) {
115
- const client = resolveClient(options, request, context);
116
- const transport = resolveTransport(options, request, context, client, defaultTransport);
117
- const trace = createRouteTraceContext(request, undefined, options);
118
- const helpers = createRouteHelpers(client, transport, trace);
119
- const startedAt = nowMs(options);
120
-
121
- return activeTraceContext.run(trace, async () => {
122
- try {
123
- const response = await handler(request, context, helpers);
124
- ensureResponse(response);
125
- await captureRouteSuccess(options, { request, response, context, client, transport, startedAt, trace });
126
- return response;
127
- } catch (error) {
128
- await recordRouteError(options, error, { request, context, client, transport, trace });
129
- throw error;
130
- }
131
- });
132
- };
133
- }
134
-
135
- export function getActiveLogBrewTrace() {
136
- return activeTraceContext.getStore();
137
- }
138
-
139
- export function createRouteRequestEvent(request, response, {
140
- now = () => new Date().toISOString(),
141
- durationMs = 0,
142
- idFactory = defaultRouteRequestId,
143
- spanIdFactory = defaultSpanIdFactory,
144
- trace
145
- } = {}) {
146
- const url = safeUrl(request);
147
- const method = request?.method ?? "GET";
148
- const statusCode = Number(response?.status ?? 0);
149
- const id = idFactory(request, response);
150
- const routeTrace = trace ?? getActiveLogBrewTrace() ?? createRouteTraceContext(request, response, { spanIdFactory });
151
- const spanEvent = routeTrace
152
- ? createTraceparentRouteSpan(routeTrace, {
153
- durationMs,
154
- id,
155
- method,
156
- now,
157
- pathname: url.pathname,
158
- statusCode
159
- })
160
- : undefined;
161
- if (spanEvent) {
162
- return spanEvent;
163
- }
164
-
165
- return {
166
- id,
167
- timestamp: now(),
168
- attributes: {
169
- message: `${method} ${url.pathname} ${statusCode}`,
170
- level: statusCode >= 500 ? "error" : "info",
171
- logger: "next",
172
- metadata: {
173
- framework: "nextjs",
174
- method,
175
- pathname: url.pathname,
176
- statusCode,
177
- durationMs
178
- }
179
- }
180
- };
181
- }
182
-
183
- export function createRouteErrorEvent(error, request, {
184
- includeSearchParams = false,
185
- now = () => new Date().toISOString(),
186
- idFactory = defaultRouteErrorId,
187
- trace
188
- } = {}) {
189
- const url = safeUrl(request);
190
- const method = request?.method ?? "GET";
191
- const message = error instanceof Error ? error.message : String(error);
192
- const routeTrace = trace ?? getActiveLogBrewTrace();
193
- return {
194
- id: idFactory(request),
195
- timestamp: now(),
196
- attributes: {
197
- title: `${method} ${url.pathname} failed`,
198
- level: "error",
199
- message,
200
- metadata: {
201
- method,
202
- pathname: url.pathname,
203
- ...(includeSearchParams ? { search: url.search || null } : {}),
204
- ...traceMetadata(routeTrace)
205
- }
206
- }
207
- };
208
- }
209
-
210
- export function createRequestMetricEvent(request, response, {
211
- now = () => new Date().toISOString(),
212
- durationMs = 0,
213
- idFactory = defaultRouteMetricId,
214
- metricName = "http.server.duration",
215
- routeTemplate
216
- } = {}) {
217
- const method = request?.method ?? "GET";
218
- const resolvedRouteTemplate = routeTemplateOnly(routeTemplate ?? safeUrl(request).pathname);
219
- const statusCode = Number(response?.status ?? 0);
220
- return {
221
- id: idFactory(request, response, resolvedRouteTemplate),
222
- timestamp: now(),
223
- attributes: {
224
- name: metricName,
225
- description: "Duration of one completed server request.",
226
- kind: "histogram",
227
- value: Math.max(0, Number(durationMs)),
228
- unit: "ms",
229
- temporality: "delta",
230
- metadata: {
231
- framework: "nextjs",
232
- method,
233
- routeTemplate: resolvedRouteTemplate,
234
- statusCode,
235
- statusCodeClass: statusCodeClass(statusCode)
236
- }
237
- }
238
- };
239
- }
240
-
241
- function resolveClient(options, request, context) {
242
- if (typeof options.client === "function") {
243
- return options.client({ request, context });
244
- }
245
- if (options.client) {
246
- return options.client;
247
- }
248
- return createLogBrewNextClient(options);
249
- }
250
-
251
- function resolveTransport(options, request, context, client, defaultTransport) {
252
- if (typeof options.transport === "function") {
253
- return options.transport({ request, context, client });
254
- }
255
- return options.transport ?? defaultTransport;
256
- }
257
-
258
- function resolveRequestErrorClient(options, runtime) {
259
- if (typeof options.client === "function") {
260
- return { client: options.client(runtime), owned: true };
261
- }
262
- if (options.client) {
263
- return { client: options.client, owned: false };
264
- }
265
- return { client: createLogBrewNextClient(options), owned: true };
266
- }
267
-
268
- function resolveRequestErrorTransport(options, runtime, defaultTransport) {
269
- if (typeof options.transport === "function") {
270
- return options.transport(runtime);
271
- }
272
- return options.transport ?? defaultTransport;
273
- }
274
-
275
- function createRouteHelpers(client, transport, trace) {
276
- return {
277
- client,
278
- logbrew: client,
279
- trace,
280
- previewJson: () => client.previewJson(),
281
- flush: () => client.flush(transport),
282
- shutdown: () => client.shutdown(transport)
283
- };
284
- }
285
-
286
- function ensureResponse(response) {
287
- if (!(response instanceof Response)) {
288
- throw new SdkError("route_handler_error", "Next.js route handler must return a Response");
289
- }
290
- }
291
-
292
- async function notifyFlush(options, flushResponse, context) {
293
- if (typeof options.onFlush === "function") {
294
- await options.onFlush(flushResponse, context);
295
- }
296
- }
297
-
298
- async function notifyFailure(options, error, context) {
299
- if (typeof options.onCaptureError === "function") {
300
- await options.onCaptureError(error, context);
301
- }
302
- }
303
-
304
- async function captureRouteSuccess(options, { request, response, context, client, transport, startedAt, trace }) {
305
- try {
306
- const durationMs = (options.captureRequests !== false || options.captureRequestMetrics === true)
307
- ? routeDurationMs(options, startedAt)
308
- : 0;
309
- if (options.captureRequests !== false) {
310
- recordRouteRequest(options, { request, response, context, client, durationMs, trace });
311
- }
312
- if (options.captureRequestMetrics === true) {
313
- recordRouteMetric(options, { request, response, context, client, durationMs, trace });
314
- }
315
- const flushResponse = await client.shutdown(transport);
316
- await notifyFlush(options, flushResponse, { request, context, client, trace });
317
- } catch (error) {
318
- await notifyFailure(options, error, { request, context, client, trace });
319
- }
320
- }
321
-
322
- function recordRouteRequest(options, { request, response, context, client, durationMs, trace }) {
323
- const event = typeof options.requestEvent === "function"
324
- ? options.requestEvent(request, response, { client, context, durationMs, request, response, trace })
325
- : createRouteRequestEvent(request, response, {
326
- ...options,
327
- durationMs,
328
- idFactory: options.requestIdFactory,
329
- trace
330
- });
331
- captureRouteRequestEvent(client, event);
332
- }
333
-
334
- function recordRouteMetric(options, { request, response, context, client, durationMs, trace }) {
335
- const routeTemplate = resolveRouteTemplate(options, request, context);
336
- const event = typeof options.requestMetricEvent === "function"
337
- ? options.requestMetricEvent(request, response, { client, context, durationMs, request, response, trace })
338
- : createRequestMetricEvent(request, response, {
339
- ...options,
340
- durationMs,
341
- idFactory: options.metricIdFactory,
342
- routeTemplate
343
- });
344
- captureRouteMetricEvent(client, event);
345
- }
346
-
347
- async function recordRouteError(options, error, { request, context, client, transport, trace }) {
348
- if (options.captureErrors === false) {
349
- return;
350
- }
351
- const routeTrace = trace ?? getActiveLogBrewTrace();
352
- const event = typeof options.errorEvent === "function"
353
- ? options.errorEvent(error, { request, context, client, trace: routeTrace })
354
- : createRouteErrorEvent(error, request, { ...options, trace: routeTrace });
355
- try {
356
- client.issue(event.id, event.timestamp, event.attributes);
357
- const flushResponse = await client.shutdown(transport);
358
- await notifyFlush(options, flushResponse, { request, context, client, trace: routeTrace });
359
- } catch (captureError) {
360
- await notifyFailure(options, captureError, { request, context, client, trace: routeTrace });
361
- }
362
- }
363
-
364
- function captureRouteRequestEvent(client, event) {
365
- if (event.type === "span") {
366
- client.span(event.id, event.timestamp, event.attributes);
367
- return;
368
- }
369
- client.log(event.id, event.timestamp, event.attributes);
370
- }
371
-
372
- function captureRouteMetricEvent(client, event) {
373
- client.metric(event.id, event.timestamp, event.attributes);
374
- }
375
-
376
- function defaultRouteRequestId(request, response) {
377
- const url = safeUrl(request);
378
- const slug = `${request?.method ?? "GET"}-${url.pathname}-${response?.status ?? 0}`
379
- .toLowerCase()
380
- .replace(/[^a-z0-9]+/g, "_")
381
- .replace(/^_+|_+$/g, "");
382
- return `evt_next_request_${slug || "route"}`;
383
- }
384
-
385
- function defaultSpanIdFactory() {
386
- return randomHex(8);
387
- }
388
-
389
- function defaultRouteErrorId(request) {
390
- const url = safeUrl(request);
391
- const slug = `${request?.method ?? "GET"}-${url.pathname}`
392
- .toLowerCase()
393
- .replace(/[^a-z0-9]+/g, "_")
394
- .replace(/^_+|_+$/g, "");
395
- return `evt_next_error_${slug || "route"}`;
396
- }
397
-
398
- function defaultNextRequestErrorId() {
399
- return `evt_next_request_error_${randomHex(8)}`;
400
- }
401
-
402
- function defaultRouteMetricId(request, response, routeTemplate = safeUrl(request).pathname) {
403
- const sanitizedRouteTemplate = routeTemplateOnly(routeTemplate);
404
- const slug = `${request?.method ?? "GET"}-${sanitizedRouteTemplate}-${response?.status ?? 0}`
405
- .toLowerCase()
406
- .replace(/[^a-z0-9]+/g, "_")
407
- .replace(/^_+|_+$/g, "");
408
- return `evt_next_metric_${slug || "route"}`;
409
- }
410
-
411
- function safeUrl(request) {
412
- try {
413
- return new URL(request?.url ?? "http://localhost/");
414
- } catch {
415
- return new URL("http://localhost/");
416
- }
417
- }
418
-
419
- function nextRequestMethod(request) {
420
- const method = typeof request?.method === "string" ? request.method.trim().toUpperCase() : "";
421
- return /^[A-Z]{1,16}$/u.test(method) ? method : "UNKNOWN";
422
- }
423
-
424
- function nextRoutePath(value) {
425
- if (typeof value !== "string" || value.trim() === "") {
426
- return "/";
427
- }
428
- let pathname;
429
- try {
430
- pathname = new URL(value, "http://localhost").pathname;
431
- } catch {
432
- pathname = value.split(/[?#]/u)[0];
433
- }
434
- if (typeof pathname !== "string" || pathname === "") {
435
- return "/";
436
- }
437
- const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
438
- return normalized.length <= MAX_REQUEST_ROUTE_PATH_LENGTH ? normalized : "/";
439
- }
440
-
441
- function nextCategoricalMetadata(key, value, allowed) {
442
- return typeof value === "string" && allowed.has(value) ? { [key]: value } : {};
443
- }
444
-
445
- function nextErrorDigest(error) {
446
- const digest = error && typeof error === "object" ? error.digest : undefined;
447
- if (typeof digest !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/u.test(digest)) {
448
- return undefined;
449
- }
450
- return digest;
451
- }
452
-
453
- function nextErrorMessage(error) {
454
- let message;
455
- try {
456
- message = error instanceof Error ? error.message : String(error);
457
- } catch {
458
- message = "Next.js request failed";
459
- }
460
- const normalized = typeof message === "string" && message.trim() !== ""
461
- ? message
462
- : "Next.js request failed";
463
- return normalized.length <= MAX_REQUEST_ERROR_MESSAGE_LENGTH
464
- ? normalized
465
- : `${normalized.slice(0, MAX_REQUEST_ERROR_MESSAGE_LENGTH - 1)}…`;
466
- }
467
-
468
- function getTraceparentHeader(request) {
469
- if (!request?.headers || typeof request.headers.get !== "function") {
470
- return undefined;
471
- }
472
- const value = request.headers.get("traceparent");
473
- return typeof value === "string" ? value : undefined;
474
- }
475
-
476
- function resolveRouteTemplate(options, request, context) {
477
- const value = typeof options.routeTemplate === "function"
478
- ? options.routeTemplate(request, context)
479
- : options.routeTemplate;
480
- return routeTemplateOnly(value ?? safeUrl(request).pathname);
481
- }
482
-
483
- function routeTemplateOnly(value) {
484
- if (typeof value !== "string" || value.trim() === "") {
485
- return "/";
486
- }
487
- try {
488
- return new URL(value, "http://localhost").pathname || "/";
489
- } catch {
490
- return value.split(/[?#]/)[0] || "/";
491
- }
492
- }
493
-
494
- function statusCodeClass(statusCode) {
495
- if (!Number.isFinite(statusCode) || statusCode <= 0) {
496
- return "unknown";
497
- }
498
- return `${Math.floor(statusCode / 100)}xx`;
499
- }
500
-
501
- function createRouteTraceContext(request, response, {
502
- spanIdFactory = defaultSpanIdFactory
503
- } = {}) {
504
- const traceparent = getTraceparentHeader(request);
505
- if (!traceparent) {
506
- return undefined;
507
- }
508
-
509
- try {
510
- const context = parseTraceparent(traceparent);
511
- const spanId = normalizeSpanId(spanIdFactory(request, response));
512
- if (!spanId) {
513
- return undefined;
514
- }
515
- return {
516
- traceId: context.traceId,
517
- spanId,
518
- parentSpanId: context.parentSpanId,
519
- sampled: context.sampled
520
- };
521
- } catch {
522
- return undefined;
523
- }
524
- }
525
-
526
- function normalizeSpanId(value) {
527
- if (typeof value !== "string") {
528
- return undefined;
529
- }
530
- const spanId = value.toLowerCase();
531
- if (!/^[0-9a-f]{16}$/u.test(spanId) || spanId === "0000000000000000") {
532
- return undefined;
533
- }
534
- return spanId;
535
- }
536
-
537
- function traceMetadata(trace) {
538
- if (!trace) {
539
- return {};
540
- }
541
- return {
542
- parentSpanId: trace.parentSpanId,
543
- sampled: trace.sampled,
544
- spanId: trace.spanId,
545
- traceId: trace.traceId
546
- };
547
- }
548
-
549
- function createTraceparentRouteSpan(traceContext, {
550
- durationMs,
551
- id,
552
- method,
553
- now,
554
- pathname,
555
- statusCode
556
- }) {
557
- if (!traceContext) {
558
- return undefined;
559
- }
560
-
561
- return {
562
- id,
563
- timestamp: now(),
564
- type: "span",
565
- attributes: {
566
- name: `${method} ${pathname}`,
567
- traceId: traceContext.traceId,
568
- spanId: traceContext.spanId,
569
- parentSpanId: traceContext.parentSpanId,
570
- status: statusCode >= 500 ? "error" : "ok",
571
- durationMs,
572
- metadata: {
573
- framework: "nextjs",
574
- method,
575
- pathname,
576
- sampled: traceContext.sampled,
577
- statusCode
578
- }
579
- }
580
- };
581
- }
582
-
583
- function routeDurationMs(options, startedAt) {
584
- return Math.max(0, Math.round(nowMs(options) - startedAt));
585
- }
586
-
587
- function nowMs(options) {
588
- if (typeof options.nowMs === "function") {
589
- return options.nowMs();
590
- }
591
- return performance.now();
592
- }
593
-
594
- function randomHex(byteLength) {
595
- const bytes = new Uint8Array(byteLength);
596
- if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
597
- globalThis.crypto.getRandomValues(bytes);
598
- } else {
599
- for (let index = 0; index < bytes.length; index += 1) {
600
- bytes[index] = Math.floor(Math.random() * 256);
601
- }
602
- }
603
- const value = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
604
- return /^0+$/.test(value) ? "0000000000000001" : value;
605
- }
606
-
607
- function readEnvApiKey() {
608
- return globalThis.process?.env?.LOGBREW_API_KEY;
609
- }
610
-
611
- function readEnvServerApiKey() {
612
- return globalThis.process?.env?.LOGBREW_SERVER_API_KEY;
613
- }
614
-
615
- export default {
3
+ export const {
616
4
  createLogBrewNextClient,
617
5
  createLogBrewNextRequestErrorHandler,
618
6
  createNextRequestErrorEvent,
@@ -621,4 +9,6 @@ export default {
621
9
  createRouteRequestEvent,
622
10
  getActiveLogBrewTrace,
623
11
  withLogBrewRouteHandler
624
- };
12
+ } = next;
13
+
14
+ export default next;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logbrew/next",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Next.js App Router helpers for the public LogBrew JavaScript SDK.",
5
5
  "type": "module",
6
6
  "main": "./index.cjs",
@@ -91,7 +91,7 @@
91
91
  },
92
92
  "peerDependencies": {
93
93
  "@logbrew/node": "^0.1.2",
94
- "@logbrew/sdk": "^0.1.3",
94
+ "@logbrew/sdk": "^0.1.12",
95
95
  "next": ">=15",
96
96
  "react": ">=18",
97
97
  "react-dom": ">=18"