@logbrew/next 0.1.5 → 0.1.7
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 +5 -5
- package/client.cjs +9 -32
- package/client.js +9 -32
- package/examples/client-route-spans.mjs +3 -4
- package/examples/readme-example.mjs +1 -1
- package/examples/real-user-smoke.mjs +1 -1
- package/index.cjs +35 -48
- package/index.d.cts +8 -6
- package/index.d.ts +8 -6
- package/index.js +5 -615
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -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
|
|
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
|
|
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.
|
|
235
|
+
sdkVersion: "0.1.7"
|
|
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>`
|
|
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.
|
|
272
|
+
sdkVersion: "0.1.7"
|
|
273
273
|
});
|
|
274
274
|
```
|
|
275
275
|
|
package/client.cjs
CHANGED
|
@@ -7,16 +7,13 @@ const {
|
|
|
7
7
|
parseTraceparent
|
|
8
8
|
} = require("@logbrew/sdk");
|
|
9
9
|
|
|
10
|
-
const DEFAULT_SDK_NAME = "logbrew-next-client";
|
|
11
|
-
const DEFAULT_SDK_VERSION = "0.1.3";
|
|
12
|
-
|
|
13
10
|
function createLogBrewNextBrowserClient({
|
|
14
11
|
apiKey,
|
|
15
12
|
clientKey,
|
|
16
13
|
context,
|
|
17
14
|
eventFilter,
|
|
18
|
-
sdkName =
|
|
19
|
-
sdkVersion =
|
|
15
|
+
sdkName = "logbrew-next-client",
|
|
16
|
+
sdkVersion = "0.1.7",
|
|
20
17
|
maxQueueSize,
|
|
21
18
|
maxRetries = 2,
|
|
22
19
|
onEventDropped
|
|
@@ -56,8 +53,7 @@ function createNextRouteTemplate({
|
|
|
56
53
|
.map((pattern) => normalizeRouteTemplate(pattern))
|
|
57
54
|
.filter((pattern) => pattern && routePatternMatchesPathname(pattern, safePathname));
|
|
58
55
|
|
|
59
|
-
|
|
60
|
-
return matched;
|
|
56
|
+
return matches.sort(compareRouteSpecificity)[0];
|
|
61
57
|
}
|
|
62
58
|
|
|
63
59
|
function createNextNavigationSpanEvent({
|
|
@@ -99,6 +95,7 @@ function createNextNavigationSpanEvent({
|
|
|
99
95
|
framework: "nextjs",
|
|
100
96
|
navigationIndex,
|
|
101
97
|
navigationType,
|
|
98
|
+
operation: "browser.navigation",
|
|
102
99
|
routeTemplate: safeRouteTemplate,
|
|
103
100
|
source: "next.client.route",
|
|
104
101
|
...metadata
|
|
@@ -132,7 +129,7 @@ function useLogBrewNextNavigation(options = {}) {
|
|
|
132
129
|
if (!routeTemplate) {
|
|
133
130
|
return;
|
|
134
131
|
}
|
|
135
|
-
const navigationKey =
|
|
132
|
+
const navigationKey = `${routeTemplate}|${pathnameOnly(options.pathname) ?? ""}`;
|
|
136
133
|
if (navigationKey === lastNavigationKey.current) {
|
|
137
134
|
return;
|
|
138
135
|
}
|
|
@@ -184,10 +181,6 @@ function traceContextFromInput({ parentSpanId, spanId, spanIdFactory, traceId, t
|
|
|
184
181
|
return { parentSpanId, spanId, traceId };
|
|
185
182
|
}
|
|
186
183
|
|
|
187
|
-
function nextNavigationKey(pathname, routeTemplate) {
|
|
188
|
-
return `${routeTemplate}|${pathnameOnly(pathname) ?? ""}`;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
184
|
function normalizeRouteTemplate(value) {
|
|
192
185
|
const pathname = pathnameOnly(value);
|
|
193
186
|
if (!pathname) {
|
|
@@ -195,18 +188,13 @@ function normalizeRouteTemplate(value) {
|
|
|
195
188
|
}
|
|
196
189
|
const segments = pathname
|
|
197
190
|
.split("/")
|
|
198
|
-
.filter(
|
|
199
|
-
.filter((segment) => !isRouteGroupSegment(segment) && !segment.startsWith("@"));
|
|
191
|
+
.filter((segment) => segment && !(segment.startsWith("(") && segment.endsWith(")")) && !segment.startsWith("@"));
|
|
200
192
|
if (segments.length === 0) {
|
|
201
193
|
return "/";
|
|
202
194
|
}
|
|
203
195
|
return `/${segments.join("/")}`;
|
|
204
196
|
}
|
|
205
197
|
|
|
206
|
-
function isRouteGroupSegment(segment) {
|
|
207
|
-
return segment.startsWith("(") && segment.endsWith(")");
|
|
208
|
-
}
|
|
209
|
-
|
|
210
198
|
function pathnameOnly(value) {
|
|
211
199
|
if (value === undefined || value === null) {
|
|
212
200
|
return undefined;
|
|
@@ -217,7 +205,7 @@ function pathnameOnly(value) {
|
|
|
217
205
|
}
|
|
218
206
|
const withoutQueryOrHash = trimmed.split(/[?#]/u, 1)[0];
|
|
219
207
|
let pathname = withoutQueryOrHash;
|
|
220
|
-
if (
|
|
208
|
+
if (/^[a-z][a-z0-9+.-]*:/iu.test(withoutQueryOrHash)) {
|
|
221
209
|
try {
|
|
222
210
|
pathname = new URL(withoutQueryOrHash).pathname;
|
|
223
211
|
} catch {
|
|
@@ -230,10 +218,6 @@ function pathnameOnly(value) {
|
|
|
230
218
|
return pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
|
|
231
219
|
}
|
|
232
220
|
|
|
233
|
-
function hasUrlScheme(url) {
|
|
234
|
-
return /^[a-z][a-z0-9+.-]*:/iu.test(url);
|
|
235
|
-
}
|
|
236
|
-
|
|
237
221
|
function routePatternMatchesPathname(routePattern, pathname) {
|
|
238
222
|
const patternSegments = routePattern.split("/").filter(Boolean);
|
|
239
223
|
const pathSegments = pathname.split("/").filter(Boolean);
|
|
@@ -303,15 +287,8 @@ function isOptionalCatchAllSegment(segment) {
|
|
|
303
287
|
return /^\[\[\.\.\.[^[\]]+\]\]$/u.test(segment);
|
|
304
288
|
}
|
|
305
289
|
|
|
306
|
-
function defaultNextNavigationSpanId(
|
|
307
|
-
return `evt_next_route_${
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
function slugify(value) {
|
|
311
|
-
return String(value)
|
|
312
|
-
.toLowerCase()
|
|
313
|
-
.replace(/[^a-z0-9]+/g, "_")
|
|
314
|
-
.replace(/^_+|_+$/g, "") || "event";
|
|
290
|
+
function defaultNextNavigationSpanId() {
|
|
291
|
+
return `evt_next_route_${randomHex(8)}`;
|
|
315
292
|
}
|
|
316
293
|
|
|
317
294
|
function defaultSpanIdFactory() {
|
package/client.js
CHANGED
|
@@ -7,16 +7,13 @@ import {
|
|
|
7
7
|
parseTraceparent
|
|
8
8
|
} from "@logbrew/sdk";
|
|
9
9
|
|
|
10
|
-
const DEFAULT_SDK_NAME = "logbrew-next-client";
|
|
11
|
-
const DEFAULT_SDK_VERSION = "0.1.3";
|
|
12
|
-
|
|
13
10
|
export function createLogBrewNextBrowserClient({
|
|
14
11
|
apiKey,
|
|
15
12
|
clientKey,
|
|
16
13
|
context,
|
|
17
14
|
eventFilter,
|
|
18
|
-
sdkName =
|
|
19
|
-
sdkVersion =
|
|
15
|
+
sdkName = "logbrew-next-client",
|
|
16
|
+
sdkVersion = "0.1.7",
|
|
20
17
|
maxQueueSize,
|
|
21
18
|
maxRetries = 2,
|
|
22
19
|
onEventDropped
|
|
@@ -56,8 +53,7 @@ export function createNextRouteTemplate({
|
|
|
56
53
|
.map((pattern) => normalizeRouteTemplate(pattern))
|
|
57
54
|
.filter((pattern) => pattern && routePatternMatchesPathname(pattern, safePathname));
|
|
58
55
|
|
|
59
|
-
|
|
60
|
-
return matched;
|
|
56
|
+
return matches.sort(compareRouteSpecificity)[0];
|
|
61
57
|
}
|
|
62
58
|
|
|
63
59
|
export function createNextNavigationSpanEvent({
|
|
@@ -99,6 +95,7 @@ export function createNextNavigationSpanEvent({
|
|
|
99
95
|
framework: "nextjs",
|
|
100
96
|
navigationIndex,
|
|
101
97
|
navigationType,
|
|
98
|
+
operation: "browser.navigation",
|
|
102
99
|
routeTemplate: safeRouteTemplate,
|
|
103
100
|
source: "next.client.route",
|
|
104
101
|
...metadata
|
|
@@ -132,7 +129,7 @@ export function useLogBrewNextNavigation(options = {}) {
|
|
|
132
129
|
if (!routeTemplate) {
|
|
133
130
|
return;
|
|
134
131
|
}
|
|
135
|
-
const navigationKey =
|
|
132
|
+
const navigationKey = `${routeTemplate}|${pathnameOnly(options.pathname) ?? ""}`;
|
|
136
133
|
if (navigationKey === lastNavigationKey.current) {
|
|
137
134
|
return;
|
|
138
135
|
}
|
|
@@ -184,10 +181,6 @@ function traceContextFromInput({ parentSpanId, spanId, spanIdFactory, traceId, t
|
|
|
184
181
|
return { parentSpanId, spanId, traceId };
|
|
185
182
|
}
|
|
186
183
|
|
|
187
|
-
function nextNavigationKey(pathname, routeTemplate) {
|
|
188
|
-
return `${routeTemplate}|${pathnameOnly(pathname) ?? ""}`;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
184
|
function normalizeRouteTemplate(value) {
|
|
192
185
|
const pathname = pathnameOnly(value);
|
|
193
186
|
if (!pathname) {
|
|
@@ -195,18 +188,13 @@ function normalizeRouteTemplate(value) {
|
|
|
195
188
|
}
|
|
196
189
|
const segments = pathname
|
|
197
190
|
.split("/")
|
|
198
|
-
.filter(
|
|
199
|
-
.filter((segment) => !isRouteGroupSegment(segment) && !segment.startsWith("@"));
|
|
191
|
+
.filter((segment) => segment && !(segment.startsWith("(") && segment.endsWith(")")) && !segment.startsWith("@"));
|
|
200
192
|
if (segments.length === 0) {
|
|
201
193
|
return "/";
|
|
202
194
|
}
|
|
203
195
|
return `/${segments.join("/")}`;
|
|
204
196
|
}
|
|
205
197
|
|
|
206
|
-
function isRouteGroupSegment(segment) {
|
|
207
|
-
return segment.startsWith("(") && segment.endsWith(")");
|
|
208
|
-
}
|
|
209
|
-
|
|
210
198
|
function pathnameOnly(value) {
|
|
211
199
|
if (value === undefined || value === null) {
|
|
212
200
|
return undefined;
|
|
@@ -217,7 +205,7 @@ function pathnameOnly(value) {
|
|
|
217
205
|
}
|
|
218
206
|
const withoutQueryOrHash = trimmed.split(/[?#]/u, 1)[0];
|
|
219
207
|
let pathname = withoutQueryOrHash;
|
|
220
|
-
if (
|
|
208
|
+
if (/^[a-z][a-z0-9+.-]*:/iu.test(withoutQueryOrHash)) {
|
|
221
209
|
try {
|
|
222
210
|
pathname = new URL(withoutQueryOrHash).pathname;
|
|
223
211
|
} catch {
|
|
@@ -230,10 +218,6 @@ function pathnameOnly(value) {
|
|
|
230
218
|
return pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
|
|
231
219
|
}
|
|
232
220
|
|
|
233
|
-
function hasUrlScheme(url) {
|
|
234
|
-
return /^[a-z][a-z0-9+.-]*:/iu.test(url);
|
|
235
|
-
}
|
|
236
|
-
|
|
237
221
|
function routePatternMatchesPathname(routePattern, pathname) {
|
|
238
222
|
const patternSegments = routePattern.split("/").filter(Boolean);
|
|
239
223
|
const pathSegments = pathname.split("/").filter(Boolean);
|
|
@@ -303,15 +287,8 @@ function isOptionalCatchAllSegment(segment) {
|
|
|
303
287
|
return /^\[\[\.\.\.[^[\]]+\]\]$/u.test(segment);
|
|
304
288
|
}
|
|
305
289
|
|
|
306
|
-
function defaultNextNavigationSpanId(
|
|
307
|
-
return `evt_next_route_${
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
function slugify(value) {
|
|
311
|
-
return String(value)
|
|
312
|
-
.toLowerCase()
|
|
313
|
-
.replace(/[^a-z0-9]+/g, "_")
|
|
314
|
-
.replace(/^_+|_+$/g, "") || "event";
|
|
290
|
+
function defaultNextNavigationSpanId() {
|
|
291
|
+
return `evt_next_route_${randomHex(8)}`;
|
|
315
292
|
}
|
|
316
293
|
|
|
317
294
|
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
|
-
|
|
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.7") {
|
|
29
28
|
throw new Error(`unexpected Next client route span: ${JSON.stringify(event)}`);
|
|
30
29
|
}
|
|
31
30
|
|
package/index.cjs
CHANGED
|
@@ -6,8 +6,6 @@ const {
|
|
|
6
6
|
} = require("@logbrew/sdk");
|
|
7
7
|
const { createNodeFetchTransport } = require("@logbrew/node");
|
|
8
8
|
|
|
9
|
-
const DEFAULT_SDK_NAME = "logbrew-next";
|
|
10
|
-
const DEFAULT_SDK_VERSION = "0.1.3";
|
|
11
9
|
const MAX_REQUEST_ERROR_MESSAGE_LENGTH = 2048;
|
|
12
10
|
const MAX_REQUEST_ROUTE_PATH_LENGTH = 512;
|
|
13
11
|
const NEXT_RENDER_SOURCES = new Set([
|
|
@@ -25,8 +23,8 @@ function createLogBrewNextClient({
|
|
|
25
23
|
apiKey,
|
|
26
24
|
serverApiKey,
|
|
27
25
|
context,
|
|
28
|
-
sdkName =
|
|
29
|
-
sdkVersion =
|
|
26
|
+
sdkName = "logbrew-next",
|
|
27
|
+
sdkVersion = "0.1.7",
|
|
30
28
|
maxRetries = 2
|
|
31
29
|
} = {}) {
|
|
32
30
|
const authKey = serverApiKey ?? apiKey ?? readEnvServerApiKey() ?? readEnvApiKey();
|
|
@@ -49,7 +47,7 @@ function createLogBrewNextRequestErrorHandler(options = {}) {
|
|
|
49
47
|
try {
|
|
50
48
|
const resolvedClient = resolveRequestErrorClient(options, runtime);
|
|
51
49
|
const client = resolvedClient.client;
|
|
52
|
-
const transport =
|
|
50
|
+
const transport = resolveTransport(options, { ...runtime, client }, defaultTransport);
|
|
53
51
|
runtime = { ...runtime, client, transport };
|
|
54
52
|
const event = typeof options.errorEvent === "function"
|
|
55
53
|
? options.errorEvent(error, runtime)
|
|
@@ -113,7 +111,7 @@ function withLogBrewRouteHandler(handler, options = {}) {
|
|
|
113
111
|
|
|
114
112
|
return async function logBrewRouteHandler(request, context = {}) {
|
|
115
113
|
const client = resolveClient(options, request, context);
|
|
116
|
-
const transport = resolveTransport(options, request, context, client, defaultTransport);
|
|
114
|
+
const transport = resolveTransport(options, { request, context, client }, defaultTransport);
|
|
117
115
|
const trace = createRouteTraceContext(request, undefined, options);
|
|
118
116
|
const helpers = createRouteHelpers(client, transport, trace);
|
|
119
117
|
const startedAt = nowMs(options);
|
|
@@ -140,13 +138,14 @@ function createRouteRequestEvent(request, response, {
|
|
|
140
138
|
now = () => new Date().toISOString(),
|
|
141
139
|
durationMs = 0,
|
|
142
140
|
idFactory = defaultRouteRequestId,
|
|
141
|
+
routeTemplate,
|
|
143
142
|
spanIdFactory = defaultSpanIdFactory,
|
|
144
143
|
trace
|
|
145
144
|
} = {}) {
|
|
146
|
-
const
|
|
145
|
+
const routePath = routeTemplateOnly(routeTemplate ?? safeUrl(request).pathname);
|
|
147
146
|
const method = request?.method ?? "GET";
|
|
148
147
|
const statusCode = Number(response?.status ?? 0);
|
|
149
|
-
const id = idFactory(request, response);
|
|
148
|
+
const id = idFactory(request, response, routePath);
|
|
150
149
|
const routeTrace = trace ?? getActiveLogBrewTrace() ?? createRouteTraceContext(request, response, { spanIdFactory });
|
|
151
150
|
const spanEvent = routeTrace
|
|
152
151
|
? createTraceparentRouteSpan(routeTrace, {
|
|
@@ -154,7 +153,7 @@ function createRouteRequestEvent(request, response, {
|
|
|
154
153
|
id,
|
|
155
154
|
method,
|
|
156
155
|
now,
|
|
157
|
-
|
|
156
|
+
routeTemplate: routePath,
|
|
158
157
|
statusCode
|
|
159
158
|
})
|
|
160
159
|
: undefined;
|
|
@@ -166,13 +165,13 @@ function createRouteRequestEvent(request, response, {
|
|
|
166
165
|
id,
|
|
167
166
|
timestamp: now(),
|
|
168
167
|
attributes: {
|
|
169
|
-
message: `${method} ${
|
|
168
|
+
message: `${method} ${routePath} ${statusCode}`,
|
|
170
169
|
level: statusCode >= 500 ? "error" : "info",
|
|
171
170
|
logger: "next",
|
|
172
171
|
metadata: {
|
|
173
172
|
framework: "nextjs",
|
|
174
173
|
method,
|
|
175
|
-
|
|
174
|
+
routeTemplate: routePath,
|
|
176
175
|
statusCode,
|
|
177
176
|
durationMs
|
|
178
177
|
}
|
|
@@ -184,22 +183,26 @@ function createRouteErrorEvent(error, request, {
|
|
|
184
183
|
includeSearchParams = false,
|
|
185
184
|
now = () => new Date().toISOString(),
|
|
186
185
|
idFactory = defaultRouteErrorId,
|
|
186
|
+
routeTemplate,
|
|
187
187
|
trace
|
|
188
188
|
} = {}) {
|
|
189
189
|
const url = safeUrl(request);
|
|
190
|
+
const routePath = routeTemplateOnly(routeTemplate ?? url.pathname);
|
|
190
191
|
const method = request?.method ?? "GET";
|
|
191
192
|
const message = error instanceof Error ? error.message : String(error);
|
|
192
193
|
const routeTrace = trace ?? getActiveLogBrewTrace();
|
|
193
194
|
return {
|
|
194
|
-
id: idFactory(request),
|
|
195
|
+
id: idFactory(request, routePath),
|
|
195
196
|
timestamp: now(),
|
|
196
197
|
attributes: {
|
|
197
|
-
title: `${method} ${
|
|
198
|
+
title: `${method} ${routePath} failed`,
|
|
198
199
|
level: "error",
|
|
199
200
|
message,
|
|
200
201
|
metadata: {
|
|
202
|
+
framework: "nextjs",
|
|
201
203
|
method,
|
|
202
|
-
|
|
204
|
+
operation: "http.server",
|
|
205
|
+
routeTemplate: routePath,
|
|
203
206
|
...(includeSearchParams ? { search: url.search || null } : {}),
|
|
204
207
|
...traceMetadata(routeTrace)
|
|
205
208
|
}
|
|
@@ -248,9 +251,9 @@ function resolveClient(options, request, context) {
|
|
|
248
251
|
return createLogBrewNextClient(options);
|
|
249
252
|
}
|
|
250
253
|
|
|
251
|
-
function resolveTransport(options,
|
|
254
|
+
function resolveTransport(options, runtime, defaultTransport) {
|
|
252
255
|
if (typeof options.transport === "function") {
|
|
253
|
-
return options.transport(
|
|
256
|
+
return options.transport(runtime);
|
|
254
257
|
}
|
|
255
258
|
return options.transport ?? defaultTransport;
|
|
256
259
|
}
|
|
@@ -265,13 +268,6 @@ function resolveRequestErrorClient(options, runtime) {
|
|
|
265
268
|
return { client: createLogBrewNextClient(options), owned: true };
|
|
266
269
|
}
|
|
267
270
|
|
|
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
271
|
function createRouteHelpers(client, transport, trace) {
|
|
276
272
|
return {
|
|
277
273
|
client,
|
|
@@ -326,6 +322,7 @@ function recordRouteRequest(options, { request, response, context, client, durat
|
|
|
326
322
|
...options,
|
|
327
323
|
durationMs,
|
|
328
324
|
idFactory: options.requestIdFactory,
|
|
325
|
+
routeTemplate: resolveRouteTemplate(options, request, context),
|
|
329
326
|
trace
|
|
330
327
|
});
|
|
331
328
|
captureRouteRequestEvent(client, event);
|
|
@@ -351,7 +348,11 @@ async function recordRouteError(options, error, { request, context, client, tran
|
|
|
351
348
|
const routeTrace = trace ?? getActiveLogBrewTrace();
|
|
352
349
|
const event = typeof options.errorEvent === "function"
|
|
353
350
|
? options.errorEvent(error, { request, context, client, trace: routeTrace })
|
|
354
|
-
: createRouteErrorEvent(error, request, {
|
|
351
|
+
: createRouteErrorEvent(error, request, {
|
|
352
|
+
...options,
|
|
353
|
+
routeTemplate: resolveRouteTemplate(options, request, context),
|
|
354
|
+
trace: routeTrace
|
|
355
|
+
});
|
|
355
356
|
try {
|
|
356
357
|
client.issue(event.id, event.timestamp, event.attributes);
|
|
357
358
|
const flushResponse = await client.shutdown(transport);
|
|
@@ -373,39 +374,24 @@ function captureRouteMetricEvent(client, event) {
|
|
|
373
374
|
client.metric(event.id, event.timestamp, event.attributes);
|
|
374
375
|
}
|
|
375
376
|
|
|
376
|
-
function defaultRouteRequestId(
|
|
377
|
-
|
|
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"}`;
|
|
377
|
+
function defaultRouteRequestId() {
|
|
378
|
+
return `evt_next_request_${randomHex(8)}`;
|
|
383
379
|
}
|
|
384
380
|
|
|
385
381
|
function defaultSpanIdFactory() {
|
|
386
382
|
return randomHex(8);
|
|
387
383
|
}
|
|
388
384
|
|
|
389
|
-
function defaultRouteErrorId(
|
|
390
|
-
|
|
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"}`;
|
|
385
|
+
function defaultRouteErrorId() {
|
|
386
|
+
return `evt_next_error_${randomHex(8)}`;
|
|
396
387
|
}
|
|
397
388
|
|
|
398
389
|
function defaultNextRequestErrorId() {
|
|
399
390
|
return `evt_next_request_error_${randomHex(8)}`;
|
|
400
391
|
}
|
|
401
392
|
|
|
402
|
-
function defaultRouteMetricId(
|
|
403
|
-
|
|
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"}`;
|
|
393
|
+
function defaultRouteMetricId() {
|
|
394
|
+
return `evt_next_metric_${randomHex(8)}`;
|
|
409
395
|
}
|
|
410
396
|
|
|
411
397
|
function safeUrl(request) {
|
|
@@ -551,7 +537,7 @@ function createTraceparentRouteSpan(traceContext, {
|
|
|
551
537
|
id,
|
|
552
538
|
method,
|
|
553
539
|
now,
|
|
554
|
-
|
|
540
|
+
routeTemplate,
|
|
555
541
|
statusCode
|
|
556
542
|
}) {
|
|
557
543
|
if (!traceContext) {
|
|
@@ -563,7 +549,7 @@ function createTraceparentRouteSpan(traceContext, {
|
|
|
563
549
|
timestamp: now(),
|
|
564
550
|
type: "span",
|
|
565
551
|
attributes: {
|
|
566
|
-
name: `${method} ${
|
|
552
|
+
name: `${method} ${routeTemplate}`,
|
|
567
553
|
traceId: traceContext.traceId,
|
|
568
554
|
spanId: traceContext.spanId,
|
|
569
555
|
parentSpanId: traceContext.parentSpanId,
|
|
@@ -572,7 +558,8 @@ function createTraceparentRouteSpan(traceContext, {
|
|
|
572
558
|
metadata: {
|
|
573
559
|
framework: "nextjs",
|
|
574
560
|
method,
|
|
575
|
-
|
|
561
|
+
operation: "http.server",
|
|
562
|
+
routeTemplate,
|
|
576
563
|
sampled: traceContext.sampled,
|
|
577
564
|
statusCode
|
|
578
565
|
}
|
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
|
|
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
|
|
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;
|