@logbrew/next 0.1.1 → 0.1.3
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 +133 -9
- package/client.cjs +1 -1
- package/client.js +1 -1
- package/examples/client-route-spans.mjs +1 -1
- package/examples/index.mjs +4 -0
- package/examples/package.json +1 -0
- package/examples/readme-example.mjs +1 -1
- package/examples/real-user-smoke.mjs +1 -1
- package/examples/request-errors.mjs +32 -0
- package/index.cjs +155 -5
- package/index.d.cts +100 -1
- package/index.d.ts +100 -1
- package/index.js +155 -5
- package/instrumentation.cjs +29 -0
- package/instrumentation.d.cts +26 -0
- package/instrumentation.d.ts +26 -0
- package/instrumentation.js +29 -0
- package/package.json +19 -3
package/README.md
CHANGED
|
@@ -6,13 +6,73 @@
|
|
|
6
6
|
|
|
7
7
|
Next.js App Router helpers for the public LogBrew JavaScript SDK.
|
|
8
8
|
|
|
9
|
-
This package is intentionally thin. It creates server-side LogBrew clients,
|
|
9
|
+
This package is intentionally thin. It creates server-side LogBrew clients, observes App Router request errors through Next.js instrumentation, wraps Route Handlers, captures successful route requests and thrown route errors, and still keeps manual event creation available through the route helpers.
|
|
10
10
|
|
|
11
11
|
## Install
|
|
12
12
|
|
|
13
13
|
```bash
|
|
14
|
-
npm install @logbrew/sdk @logbrew/next next react react-dom
|
|
15
|
-
pnpm add @logbrew/sdk @logbrew/next next react react-dom
|
|
14
|
+
npm install @logbrew/sdk @logbrew/node @logbrew/next next react react-dom
|
|
15
|
+
pnpm add @logbrew/sdk @logbrew/node @logbrew/next next react react-dom
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Set `LOGBREW_SERVER_API_KEY` to a project-scoped server ingest key before starting
|
|
19
|
+
the app.
|
|
20
|
+
|
|
21
|
+
If you are automating setup, follow the same safe path as a person.
|
|
22
|
+
Do not ask a person to paste an ingest key.
|
|
23
|
+
Do not treat a missing environment variable as a reason to stop setup.
|
|
24
|
+
First run `logbrew status --json`. When it reports approved authentication,
|
|
25
|
+
create a temporary project and key with the commands below.
|
|
26
|
+
Continue without a browser handoff. Confirm authenticated readback, and then
|
|
27
|
+
archive the project.
|
|
28
|
+
Only stop for account authentication when the status command reports that no
|
|
29
|
+
approved authentication is available.
|
|
30
|
+
|
|
31
|
+
## Create a Project and Confirm Hosted Delivery
|
|
32
|
+
|
|
33
|
+
Use LogBrew CLI 0.1.32 or newer with approved account authentication to create
|
|
34
|
+
the project. This requires no dashboard sign-in. The destination key file must
|
|
35
|
+
not already exist. The CLI creates it with owner-only permissions and never
|
|
36
|
+
prints the one-time key or its file path.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
logbrew status --json
|
|
40
|
+
install -d -m 700 "$HOME/.logbrew"
|
|
41
|
+
|
|
42
|
+
project_result="$(
|
|
43
|
+
logbrew projects create next-service \
|
|
44
|
+
--runtime node \
|
|
45
|
+
--environment development \
|
|
46
|
+
--ingest-key-file "$HOME/.logbrew/next-service.ingest" \
|
|
47
|
+
--json
|
|
48
|
+
)"
|
|
49
|
+
export LOGBREW_PROJECT_ID="$(jq -er '.project.id' <<<"$project_result")"
|
|
50
|
+
unset project_result
|
|
51
|
+
export LOGBREW_SERVER_API_KEY="$(< "$HOME/.logbrew/next-service.ingest")"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Start the app after wrapping the Route Handler below, then request one safe
|
|
55
|
+
route that your app already owns. For example:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
curl --fail --request POST http://127.0.0.1:3000/api/logbrew
|
|
59
|
+
|
|
60
|
+
logbrew doctor --project "$LOGBREW_PROJECT_ID" --json
|
|
61
|
+
logbrew read logs --project "$LOGBREW_PROJECT_ID" \
|
|
62
|
+
--search "POST /api/logbrew" \
|
|
63
|
+
--since 1h \
|
|
64
|
+
--json
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
A successful ingest response proves submission. The authenticated read proves
|
|
68
|
+
that the event is indexed for the same project. If you no longer need the
|
|
69
|
+
temporary project, archive it and remove its revoked one-time key file:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
unset LOGBREW_SERVER_API_KEY
|
|
73
|
+
logbrew projects archive "$LOGBREW_PROJECT_ID" --yes --json
|
|
74
|
+
rm -f "$HOME/.logbrew/next-service.ingest"
|
|
75
|
+
unset LOGBREW_PROJECT_ID
|
|
16
76
|
```
|
|
17
77
|
|
|
18
78
|
## Release Artifacts
|
|
@@ -43,11 +103,48 @@ export default withLogBrewNextReleaseArtifacts(
|
|
|
43
103
|
|
|
44
104
|
The helper defaults minified URLs to `app:///_next/static/chunks/...`. Use `minifiedPathPrefix`, `manifestPath`, `repositoryUrl`, `commitSha`, or `stripSourcePrefix` when your deploy needs explicit paths or source-link metadata. Set `LOGBREW_RELEASE_ARTIFACT_TOKEN` in the build environment to a dedicated release-artifact token. Use `tokenEnv` for a different CI variable, or `dryRun: true` to prepare the complete build output without a network request. Existing `compiler.runAfterProductionCompile` work runs first. Upload is disabled when `upload` is omitted, and any unsafe preparation or upload result fails the production build without exposing response text or secret values.
|
|
45
105
|
|
|
106
|
+
## App Router Request Errors
|
|
107
|
+
|
|
108
|
+
Use Next.js's root `instrumentation.ts` file when you want one server error hook
|
|
109
|
+
for React Server Components, Route Handlers, Server Actions, and Proxy. The
|
|
110
|
+
instrumentation subpath stays safe to import in mixed-runtime applications and
|
|
111
|
+
delivers only from the Node.js runtime:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
// instrumentation.ts
|
|
115
|
+
import { createLogBrewNextRequestErrorHandler } from "@logbrew/next/instrumentation";
|
|
116
|
+
|
|
117
|
+
export const onRequestError = createLogBrewNextRequestErrorHandler({
|
|
118
|
+
serverApiKey: process.env.LOGBREW_SERVER_API_KEY,
|
|
119
|
+
onCaptureError(error) {
|
|
120
|
+
console.error("LogBrew request-error capture failed", error);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Next.js awaits `onRequestError`, and the LogBrew adapter awaits delivery before
|
|
126
|
+
it returns. A delivery or callback failure is reported through
|
|
127
|
+
`onCaptureError` but never replaces the application error that Next.js is
|
|
128
|
+
already handling. The Edge runtime is left unchanged; use a Node.js route or
|
|
129
|
+
server boundary for LogBrew server delivery.
|
|
130
|
+
|
|
131
|
+
By default, the issue includes the error message, Next.js error digest, method,
|
|
132
|
+
stable route file path, router kind, route type, render source, revalidation
|
|
133
|
+
reason, and render type when Next.js supplies them. It does not capture request
|
|
134
|
+
headers, authorization values, cookies, request bodies, query strings, URL
|
|
135
|
+
fragments, concrete dynamic path values, or raw stack text. Set
|
|
136
|
+
`includePathname: true` only when a query-free concrete pathname is intentional
|
|
137
|
+
and acceptable for that application.
|
|
138
|
+
|
|
139
|
+
If the same Route Handler also uses `withLogBrewRouteHandler`, set
|
|
140
|
+
`captureErrors: false` on that wrapper so the global request-error hook is the
|
|
141
|
+
single issue owner. The wrapper can continue to capture successful requests,
|
|
142
|
+
metrics, and trace context.
|
|
143
|
+
|
|
46
144
|
## App Router Route Handler
|
|
47
145
|
|
|
48
146
|
```js
|
|
49
147
|
// app/api/logbrew/route.js
|
|
50
|
-
import { RecordingTransport } from "@logbrew/sdk";
|
|
51
148
|
import { getActiveLogBrewTrace, withLogBrewRouteHandler } from "@logbrew/next";
|
|
52
149
|
|
|
53
150
|
export const runtime = "nodejs";
|
|
@@ -68,15 +165,37 @@ export const POST = withLogBrewRouteHandler(
|
|
|
68
165
|
return Response.json(JSON.parse(client.previewJson()));
|
|
69
166
|
},
|
|
70
167
|
{
|
|
71
|
-
serverApiKey:
|
|
168
|
+
serverApiKey: process.env.LOGBREW_SERVER_API_KEY,
|
|
72
169
|
spanIdFactory: () => "b7ad6b7169203331",
|
|
73
|
-
|
|
170
|
+
onCaptureError(error) {
|
|
171
|
+
console.error("LogBrew route capture failed", error);
|
|
172
|
+
}
|
|
74
173
|
}
|
|
75
174
|
);
|
|
76
175
|
```
|
|
77
176
|
|
|
177
|
+
With no `transport` option, the wrapper sends to the LogBrew ingest API by default
|
|
178
|
+
through `@logbrew/node`. You can pass `endpoint`, `fetchImpl`, or `headers` to
|
|
179
|
+
configure that fetch transport, or pass an explicit LogBrew `Transport`.
|
|
180
|
+
Delivery failures call `onCaptureError`; they are never converted into a
|
|
181
|
+
simulated successful response.
|
|
182
|
+
|
|
78
183
|
Use `serverApiKey` directly for local server examples, or set `LOGBREW_SERVER_API_KEY` in your server environment and omit it. `apiKey` and `LOGBREW_API_KEY` are still accepted for compatibility with lower-level SDK examples, but Next.js Route Handlers should use server-side keys only. Use the Browser, React, Vue, Svelte, Angular, or React Native packages for frontend `clientKey` setup.
|
|
79
184
|
|
|
185
|
+
`RecordingTransport` remains available from `@logbrew/sdk` when you want to
|
|
186
|
+
inspect serialized server events locally. It does not send data to LogBrew;
|
|
187
|
+
use the default Node fetch transport for production telemetry:
|
|
188
|
+
|
|
189
|
+
```js
|
|
190
|
+
import { RecordingTransport } from "@logbrew/sdk";
|
|
191
|
+
|
|
192
|
+
const previewTransport = RecordingTransport.alwaysAccept();
|
|
193
|
+
export const POST = withLogBrewRouteHandler(handler, {
|
|
194
|
+
serverApiKey: "local-preview-key",
|
|
195
|
+
transport: previewTransport
|
|
196
|
+
});
|
|
197
|
+
```
|
|
198
|
+
|
|
80
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.
|
|
81
200
|
|
|
82
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.
|
|
@@ -113,7 +232,7 @@ import {
|
|
|
113
232
|
const client = createLogBrewNextBrowserClient({
|
|
114
233
|
clientKey: "LOGBREW_CLIENT_KEY",
|
|
115
234
|
sdkName: "my-next-app",
|
|
116
|
-
sdkVersion: "0.1.
|
|
235
|
+
sdkVersion: "0.1.3"
|
|
117
236
|
});
|
|
118
237
|
|
|
119
238
|
const routePatterns = [
|
|
@@ -150,10 +269,15 @@ import { createLogBrewNextClient } from "@logbrew/next";
|
|
|
150
269
|
const client = createLogBrewNextClient({
|
|
151
270
|
serverApiKey: "LOGBREW_SERVER_API_KEY",
|
|
152
271
|
sdkName: "my-next-app",
|
|
153
|
-
sdkVersion: "0.1.
|
|
272
|
+
sdkVersion: "0.1.3"
|
|
154
273
|
});
|
|
155
274
|
```
|
|
156
275
|
|
|
157
276
|
## Example Source
|
|
158
277
|
|
|
159
|
-
The package includes example source for App Router Route Handlers, server-side client creation, and app-owned responses. Use the snippets above as the starting point for wiring LogBrew into your Next.js application.
|
|
278
|
+
The package includes example source for App Router request-error instrumentation, Route Handlers, server-side client creation, and app-owned responses. The packaged server examples use an explicit `RecordingTransport` so they can run offline and print serialized event batches without sending them. Use the default network-delivery snippets above as the starting point for wiring LogBrew into your Next.js application.
|
|
279
|
+
|
|
280
|
+
```bash
|
|
281
|
+
node node_modules/@logbrew/next/examples/index.mjs request-errors
|
|
282
|
+
npm --prefix node_modules/@logbrew/next/examples run request-errors
|
|
283
|
+
```
|
package/client.cjs
CHANGED
package/client.js
CHANGED
|
@@ -13,7 +13,7 @@ const routeTemplate = createNextRouteTemplate({
|
|
|
13
13
|
const client = createLogBrewNextBrowserClient({
|
|
14
14
|
clientKey: "LOGBREW_CLIENT_KEY",
|
|
15
15
|
sdkName: "logbrew-next-client-route-example",
|
|
16
|
-
sdkVersion: "0.1.
|
|
16
|
+
sdkVersion: "0.1.3"
|
|
17
17
|
});
|
|
18
18
|
|
|
19
19
|
const event = captureNextNavigation(client, {
|
package/examples/index.mjs
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const commands = new Map([
|
|
4
4
|
["client-route-spans", new URL("./client-route-spans.mjs", import.meta.url)],
|
|
5
5
|
["readme-example", new URL("./readme-example.mjs", import.meta.url)],
|
|
6
|
+
["request-errors", new URL("./request-errors.mjs", import.meta.url)],
|
|
6
7
|
["real-user-smoke", new URL("./real-user-smoke.mjs", import.meta.url)]
|
|
7
8
|
]);
|
|
8
9
|
|
|
@@ -25,16 +26,19 @@ function printHelp() {
|
|
|
25
26
|
console.log("node node_modules/@logbrew/next/examples/index.mjs --list");
|
|
26
27
|
console.log("node node_modules/@logbrew/next/examples/index.mjs client-route-spans");
|
|
27
28
|
console.log("node node_modules/@logbrew/next/examples/index.mjs readme-example");
|
|
29
|
+
console.log("node node_modules/@logbrew/next/examples/index.mjs request-errors");
|
|
28
30
|
console.log("node node_modules/@logbrew/next/examples/index.mjs real-user-smoke");
|
|
29
31
|
console.log("node node_modules/@logbrew/next/examples/index.mjs");
|
|
30
32
|
console.log("npm --prefix node_modules/@logbrew/next/examples run list");
|
|
31
33
|
console.log("npm --prefix node_modules/@logbrew/next/examples run client-route-spans");
|
|
32
34
|
console.log("npm --prefix node_modules/@logbrew/next/examples run readme-example");
|
|
35
|
+
console.log("npm --prefix node_modules/@logbrew/next/examples run request-errors");
|
|
33
36
|
console.log("npm --prefix node_modules/@logbrew/next/examples run real-user-smoke");
|
|
34
37
|
}
|
|
35
38
|
|
|
36
39
|
function printList() {
|
|
37
40
|
console.log("client-route-spans -> node node_modules/@logbrew/next/examples/index.mjs client-route-spans");
|
|
38
41
|
console.log("readme-example -> node node_modules/@logbrew/next/examples/index.mjs readme-example");
|
|
42
|
+
console.log("request-errors -> node node_modules/@logbrew/next/examples/index.mjs request-errors");
|
|
39
43
|
console.log("real-user-smoke -> node node_modules/@logbrew/next/examples/index.mjs real-user-smoke");
|
|
40
44
|
}
|
package/examples/package.json
CHANGED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { RecordingTransport } from "@logbrew/sdk";
|
|
2
|
+
import { createLogBrewNextRequestErrorHandler } from "@logbrew/next/instrumentation";
|
|
3
|
+
|
|
4
|
+
const transport = RecordingTransport.alwaysAccept();
|
|
5
|
+
const onRequestError = createLogBrewNextRequestErrorHandler({
|
|
6
|
+
serverApiKey: "LOGBREW_SERVER_API_KEY",
|
|
7
|
+
transport,
|
|
8
|
+
idFactory: () => "evt_next_request_error_example",
|
|
9
|
+
now: () => "2026-08-01T10:00:00Z"
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
const error = Object.assign(new Error("checkout render failed"), {
|
|
13
|
+
digest: "next_digest_example"
|
|
14
|
+
});
|
|
15
|
+
await onRequestError(
|
|
16
|
+
error,
|
|
17
|
+
{
|
|
18
|
+
path: "/orders/example?debug=sample",
|
|
19
|
+
method: "POST",
|
|
20
|
+
headers: {}
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
routerKind: "App Router",
|
|
24
|
+
routePath: "/app/orders/[orderId]/page",
|
|
25
|
+
routeType: "render",
|
|
26
|
+
renderSource: "react-server-components",
|
|
27
|
+
renderType: "dynamic"
|
|
28
|
+
}
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
console.log(transport.lastBody());
|
|
32
|
+
console.error(JSON.stringify({ ok: true, attempts: transport.sentBodies.length }));
|
package/index.cjs
CHANGED
|
@@ -1,13 +1,24 @@
|
|
|
1
1
|
const { AsyncLocalStorage } = require("node:async_hooks");
|
|
2
2
|
const {
|
|
3
3
|
LogBrewClient,
|
|
4
|
-
RecordingTransport,
|
|
5
4
|
SdkError,
|
|
6
5
|
parseTraceparent
|
|
7
6
|
} = require("@logbrew/sdk");
|
|
7
|
+
const { createNodeFetchTransport } = require("@logbrew/node");
|
|
8
8
|
|
|
9
9
|
const DEFAULT_SDK_NAME = "logbrew-next";
|
|
10
|
-
const DEFAULT_SDK_VERSION = "0.1.
|
|
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"]);
|
|
11
22
|
const activeTraceContext = new AsyncLocalStorage();
|
|
12
23
|
|
|
13
24
|
function createLogBrewNextClient({
|
|
@@ -27,14 +38,81 @@ function createLogBrewNextClient({
|
|
|
27
38
|
return LogBrewClient.create({ apiKey: authKey, sdkName, sdkVersion, maxRetries });
|
|
28
39
|
}
|
|
29
40
|
|
|
41
|
+
function createLogBrewNextRequestErrorHandler(options = {}) {
|
|
42
|
+
const defaultTransport = options.transport === undefined
|
|
43
|
+
? createNodeFetchTransport(options)
|
|
44
|
+
: undefined;
|
|
45
|
+
|
|
46
|
+
return async function logBrewNextRequestErrorHandler(error, request = {}, context = {}) {
|
|
47
|
+
let runtime = { error, request, context };
|
|
48
|
+
try {
|
|
49
|
+
const resolvedClient = resolveRequestErrorClient(options, runtime);
|
|
50
|
+
const client = resolvedClient.client;
|
|
51
|
+
const transport = resolveRequestErrorTransport(options, { ...runtime, client }, defaultTransport);
|
|
52
|
+
runtime = { ...runtime, client, transport };
|
|
53
|
+
const event = typeof options.errorEvent === "function"
|
|
54
|
+
? options.errorEvent(error, runtime)
|
|
55
|
+
: createNextRequestErrorEvent(error, request, context, options);
|
|
56
|
+
|
|
57
|
+
client.issue(event.id, event.timestamp, event.attributes);
|
|
58
|
+
const response = resolvedClient.owned
|
|
59
|
+
? await client.shutdown(transport)
|
|
60
|
+
: await client.flush(transport);
|
|
61
|
+
await notifyFlush(options, response, runtime);
|
|
62
|
+
} catch (captureError) {
|
|
63
|
+
try {
|
|
64
|
+
await notifyFailure(options, captureError, runtime);
|
|
65
|
+
} catch {
|
|
66
|
+
// Observability callbacks must not replace the application error Next.js is handling.
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function createNextRequestErrorEvent(error, request = {}, context = {}, {
|
|
73
|
+
includePathname = false,
|
|
74
|
+
now = () => new Date().toISOString(),
|
|
75
|
+
idFactory = defaultNextRequestErrorId
|
|
76
|
+
} = {}) {
|
|
77
|
+
const method = nextRequestMethod(request);
|
|
78
|
+
const routePath = nextRoutePath(context?.routePath);
|
|
79
|
+
const pathname = includePathname ? nextRoutePath(request?.path) : undefined;
|
|
80
|
+
const errorDigest = nextErrorDigest(error);
|
|
81
|
+
return {
|
|
82
|
+
id: idFactory(error, request, context),
|
|
83
|
+
timestamp: now(),
|
|
84
|
+
attributes: {
|
|
85
|
+
title: `${method} ${routePath} failed`,
|
|
86
|
+
level: "error",
|
|
87
|
+
message: nextErrorMessage(error),
|
|
88
|
+
metadata: {
|
|
89
|
+
framework: "nextjs",
|
|
90
|
+
method,
|
|
91
|
+
routePath,
|
|
92
|
+
...nextCategoricalMetadata("routerKind", context?.routerKind, NEXT_ROUTER_KINDS),
|
|
93
|
+
...nextCategoricalMetadata("routeType", context?.routeType, NEXT_ROUTE_TYPES),
|
|
94
|
+
...nextCategoricalMetadata("renderSource", context?.renderSource, NEXT_RENDER_SOURCES),
|
|
95
|
+
...nextCategoricalMetadata("revalidateReason", context?.revalidateReason, NEXT_REVALIDATE_REASONS),
|
|
96
|
+
...nextCategoricalMetadata("renderType", context?.renderType, NEXT_RENDER_TYPES),
|
|
97
|
+
...(errorDigest ? { errorDigest } : {}),
|
|
98
|
+
...(pathname ? { pathname } : {})
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
30
104
|
function withLogBrewRouteHandler(handler, options = {}) {
|
|
31
105
|
if (typeof handler !== "function") {
|
|
32
106
|
throw new SdkError("configuration_error", "withLogBrewRouteHandler requires a handler function");
|
|
33
107
|
}
|
|
34
108
|
|
|
109
|
+
const defaultTransport = options.transport === undefined
|
|
110
|
+
? createNodeFetchTransport(options)
|
|
111
|
+
: undefined;
|
|
112
|
+
|
|
35
113
|
return async function logBrewRouteHandler(request, context = {}) {
|
|
36
114
|
const client = resolveClient(options, request, context);
|
|
37
|
-
const transport = resolveTransport(options, request, context, client);
|
|
115
|
+
const transport = resolveTransport(options, request, context, client, defaultTransport);
|
|
38
116
|
const trace = createRouteTraceContext(request, undefined, options);
|
|
39
117
|
const helpers = createRouteHelpers(client, transport, trace);
|
|
40
118
|
const startedAt = nowMs(options);
|
|
@@ -168,11 +246,28 @@ function resolveClient(options, request, context) {
|
|
|
168
246
|
return createLogBrewNextClient(options);
|
|
169
247
|
}
|
|
170
248
|
|
|
171
|
-
function resolveTransport(options, request, context, client) {
|
|
249
|
+
function resolveTransport(options, request, context, client, defaultTransport) {
|
|
172
250
|
if (typeof options.transport === "function") {
|
|
173
251
|
return options.transport({ request, context, client });
|
|
174
252
|
}
|
|
175
|
-
return options.transport ??
|
|
253
|
+
return options.transport ?? defaultTransport;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function resolveRequestErrorClient(options, runtime) {
|
|
257
|
+
if (typeof options.client === "function") {
|
|
258
|
+
return { client: options.client(runtime), owned: true };
|
|
259
|
+
}
|
|
260
|
+
if (options.client) {
|
|
261
|
+
return { client: options.client, owned: false };
|
|
262
|
+
}
|
|
263
|
+
return { client: createLogBrewNextClient(options), owned: true };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function resolveRequestErrorTransport(options, runtime, defaultTransport) {
|
|
267
|
+
if (typeof options.transport === "function") {
|
|
268
|
+
return options.transport(runtime);
|
|
269
|
+
}
|
|
270
|
+
return options.transport ?? defaultTransport;
|
|
176
271
|
}
|
|
177
272
|
|
|
178
273
|
function createRouteHelpers(client, transport, trace) {
|
|
@@ -298,6 +393,10 @@ function defaultRouteErrorId(request) {
|
|
|
298
393
|
return `evt_next_error_${slug || "route"}`;
|
|
299
394
|
}
|
|
300
395
|
|
|
396
|
+
function defaultNextRequestErrorId() {
|
|
397
|
+
return `evt_next_request_error_${randomHex(8)}`;
|
|
398
|
+
}
|
|
399
|
+
|
|
301
400
|
function defaultRouteMetricId(request, response, routeTemplate = safeUrl(request).pathname) {
|
|
302
401
|
const sanitizedRouteTemplate = routeTemplateOnly(routeTemplate);
|
|
303
402
|
const slug = `${request?.method ?? "GET"}-${sanitizedRouteTemplate}-${response?.status ?? 0}`
|
|
@@ -315,6 +414,55 @@ function safeUrl(request) {
|
|
|
315
414
|
}
|
|
316
415
|
}
|
|
317
416
|
|
|
417
|
+
function nextRequestMethod(request) {
|
|
418
|
+
const method = typeof request?.method === "string" ? request.method.trim().toUpperCase() : "";
|
|
419
|
+
return /^[A-Z]{1,16}$/u.test(method) ? method : "UNKNOWN";
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function nextRoutePath(value) {
|
|
423
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
424
|
+
return "/";
|
|
425
|
+
}
|
|
426
|
+
let pathname;
|
|
427
|
+
try {
|
|
428
|
+
pathname = new URL(value, "http://localhost").pathname;
|
|
429
|
+
} catch {
|
|
430
|
+
pathname = value.split(/[?#]/u)[0];
|
|
431
|
+
}
|
|
432
|
+
if (typeof pathname !== "string" || pathname === "") {
|
|
433
|
+
return "/";
|
|
434
|
+
}
|
|
435
|
+
const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
|
436
|
+
return normalized.length <= MAX_REQUEST_ROUTE_PATH_LENGTH ? normalized : "/";
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function nextCategoricalMetadata(key, value, allowed) {
|
|
440
|
+
return typeof value === "string" && allowed.has(value) ? { [key]: value } : {};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function nextErrorDigest(error) {
|
|
444
|
+
const digest = error && typeof error === "object" ? error.digest : undefined;
|
|
445
|
+
if (typeof digest !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/u.test(digest)) {
|
|
446
|
+
return undefined;
|
|
447
|
+
}
|
|
448
|
+
return digest;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function nextErrorMessage(error) {
|
|
452
|
+
let message;
|
|
453
|
+
try {
|
|
454
|
+
message = error instanceof Error ? error.message : String(error);
|
|
455
|
+
} catch {
|
|
456
|
+
message = "Next.js request failed";
|
|
457
|
+
}
|
|
458
|
+
const normalized = typeof message === "string" && message.trim() !== ""
|
|
459
|
+
? message
|
|
460
|
+
: "Next.js request failed";
|
|
461
|
+
return normalized.length <= MAX_REQUEST_ERROR_MESSAGE_LENGTH
|
|
462
|
+
? normalized
|
|
463
|
+
: `${normalized.slice(0, MAX_REQUEST_ERROR_MESSAGE_LENGTH - 1)}…`;
|
|
464
|
+
}
|
|
465
|
+
|
|
318
466
|
function getTraceparentHeader(request) {
|
|
319
467
|
if (!request?.headers || typeof request.headers.get !== "function") {
|
|
320
468
|
return undefined;
|
|
@@ -464,6 +612,8 @@ function readEnvServerApiKey() {
|
|
|
464
612
|
|
|
465
613
|
module.exports = {
|
|
466
614
|
createLogBrewNextClient,
|
|
615
|
+
createLogBrewNextRequestErrorHandler,
|
|
616
|
+
createNextRequestErrorEvent,
|
|
467
617
|
createRequestMetricEvent,
|
|
468
618
|
createRouteErrorEvent,
|
|
469
619
|
createRouteRequestEvent,
|
package/index.d.cts
CHANGED
|
@@ -8,6 +8,12 @@ import type {
|
|
|
8
8
|
TransportResponse
|
|
9
9
|
} from "@logbrew/sdk";
|
|
10
10
|
|
|
11
|
+
type NodeFetchTransportConfig = {
|
|
12
|
+
endpoint?: string;
|
|
13
|
+
fetchImpl?: typeof fetch;
|
|
14
|
+
headers?: Record<string, string>;
|
|
15
|
+
};
|
|
16
|
+
|
|
11
17
|
export type CreateLogBrewNextClientConfig = {
|
|
12
18
|
apiKey?: string;
|
|
13
19
|
serverApiKey?: string;
|
|
@@ -16,6 +22,77 @@ export type CreateLogBrewNextClientConfig = {
|
|
|
16
22
|
maxRetries?: number;
|
|
17
23
|
};
|
|
18
24
|
|
|
25
|
+
export type LogBrewNextRequestError = unknown;
|
|
26
|
+
|
|
27
|
+
export type LogBrewNextRequestErrorRequest = Readonly<{
|
|
28
|
+
path: string;
|
|
29
|
+
method: string;
|
|
30
|
+
headers: Readonly<Record<string, string | string[] | undefined>>;
|
|
31
|
+
}>;
|
|
32
|
+
|
|
33
|
+
export type LogBrewNextRequestErrorContext = Readonly<{
|
|
34
|
+
routerKind: "App Router" | "Pages Router";
|
|
35
|
+
routePath: string;
|
|
36
|
+
routeType: "action" | "middleware" | "proxy" | "render" | "route";
|
|
37
|
+
renderSource?: "react-server-components" | "react-server-components-payload" | "server-rendering";
|
|
38
|
+
revalidateReason?: "on-demand" | "stale";
|
|
39
|
+
renderType?: "dynamic" | "dynamic-resume";
|
|
40
|
+
}>;
|
|
41
|
+
|
|
42
|
+
export type LogBrewNextRequestErrorInput = {
|
|
43
|
+
error: LogBrewNextRequestError;
|
|
44
|
+
request: LogBrewNextRequestErrorRequest;
|
|
45
|
+
context: LogBrewNextRequestErrorContext;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export type LogBrewNextRequestErrorRuntimeContext = LogBrewNextRequestErrorInput & {
|
|
49
|
+
client?: LogBrewClient;
|
|
50
|
+
transport?: Transport;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export type LogBrewNextRequestErrorCaptureContext = LogBrewNextRequestErrorInput & {
|
|
54
|
+
client: LogBrewClient;
|
|
55
|
+
transport: Transport;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export type LogBrewNextRequestErrorEvent = {
|
|
59
|
+
id: string;
|
|
60
|
+
timestamp: string;
|
|
61
|
+
attributes: IssueAttributes;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export type LogBrewNextRequestErrorHandler = (
|
|
65
|
+
error: LogBrewNextRequestError,
|
|
66
|
+
request: LogBrewNextRequestErrorRequest,
|
|
67
|
+
context: LogBrewNextRequestErrorContext
|
|
68
|
+
) => Promise<void>;
|
|
69
|
+
|
|
70
|
+
export type LogBrewNextRequestErrorOptions = CreateLogBrewNextClientConfig & NodeFetchTransportConfig & {
|
|
71
|
+
/** A fixed client stays caller-owned and is flushed, not shut down. A factory must return a fresh client per error. */
|
|
72
|
+
client?: LogBrewClient | ((input: LogBrewNextRequestErrorInput) => LogBrewClient);
|
|
73
|
+
transport?: Transport | ((context: LogBrewNextRequestErrorInput & { client: LogBrewClient }) => Transport);
|
|
74
|
+
/** Opt into a query-free concrete pathname. Stable routePath metadata remains the default. */
|
|
75
|
+
includePathname?: boolean;
|
|
76
|
+
now?: () => string;
|
|
77
|
+
idFactory?: (
|
|
78
|
+
error: LogBrewNextRequestError,
|
|
79
|
+
request: LogBrewNextRequestErrorRequest,
|
|
80
|
+
context: LogBrewNextRequestErrorContext
|
|
81
|
+
) => string;
|
|
82
|
+
errorEvent?: (
|
|
83
|
+
error: LogBrewNextRequestError,
|
|
84
|
+
context: LogBrewNextRequestErrorCaptureContext
|
|
85
|
+
) => LogBrewNextRequestErrorEvent;
|
|
86
|
+
onFlush?: (
|
|
87
|
+
response: TransportResponse,
|
|
88
|
+
context: LogBrewNextRequestErrorCaptureContext
|
|
89
|
+
) => void | Promise<void>;
|
|
90
|
+
onCaptureError?: (
|
|
91
|
+
error: unknown,
|
|
92
|
+
context: LogBrewNextRequestErrorRuntimeContext
|
|
93
|
+
) => void | Promise<void>;
|
|
94
|
+
};
|
|
95
|
+
|
|
19
96
|
export type LogBrewRouteContext = Record<string, unknown>;
|
|
20
97
|
|
|
21
98
|
export type LogBrewTraceContext = {
|
|
@@ -90,8 +167,9 @@ export type LogBrewRouteMetricEvent = {
|
|
|
90
167
|
attributes: MetricAttributes;
|
|
91
168
|
};
|
|
92
169
|
|
|
93
|
-
export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewNextClientConfig & {
|
|
170
|
+
export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewNextClientConfig & NodeFetchTransportConfig & {
|
|
94
171
|
client?: LogBrewClient | LogBrewClientFactory<TContext>;
|
|
172
|
+
/** Override the default Node fetch transport, optionally per request. */
|
|
95
173
|
transport?: Transport | LogBrewTransportFactory<TContext>;
|
|
96
174
|
captureRequests?: boolean;
|
|
97
175
|
captureRequestMetrics?: boolean;
|
|
@@ -133,6 +211,25 @@ export declare function createLogBrewNextClient(
|
|
|
133
211
|
config?: CreateLogBrewNextClientConfig
|
|
134
212
|
): LogBrewClient;
|
|
135
213
|
|
|
214
|
+
export declare function createLogBrewNextRequestErrorHandler(
|
|
215
|
+
options?: LogBrewNextRequestErrorOptions
|
|
216
|
+
): LogBrewNextRequestErrorHandler;
|
|
217
|
+
|
|
218
|
+
export declare function createNextRequestErrorEvent(
|
|
219
|
+
error: LogBrewNextRequestError,
|
|
220
|
+
request: LogBrewNextRequestErrorRequest,
|
|
221
|
+
context: LogBrewNextRequestErrorContext,
|
|
222
|
+
options?: {
|
|
223
|
+
includePathname?: boolean;
|
|
224
|
+
now?: () => string;
|
|
225
|
+
idFactory?: (
|
|
226
|
+
error: LogBrewNextRequestError,
|
|
227
|
+
request: LogBrewNextRequestErrorRequest,
|
|
228
|
+
context: LogBrewNextRequestErrorContext
|
|
229
|
+
) => string;
|
|
230
|
+
}
|
|
231
|
+
): LogBrewNextRequestErrorEvent;
|
|
232
|
+
|
|
136
233
|
export declare function withLogBrewRouteHandler<TContext = LogBrewRouteContext>(
|
|
137
234
|
handler: LogBrewRouteHandler<TContext>,
|
|
138
235
|
options?: LogBrewRouteOptions<TContext>
|
|
@@ -177,6 +274,8 @@ export declare function createRouteErrorEvent(
|
|
|
177
274
|
|
|
178
275
|
declare const defaultExport: {
|
|
179
276
|
createLogBrewNextClient: typeof createLogBrewNextClient;
|
|
277
|
+
createLogBrewNextRequestErrorHandler: typeof createLogBrewNextRequestErrorHandler;
|
|
278
|
+
createNextRequestErrorEvent: typeof createNextRequestErrorEvent;
|
|
180
279
|
createRequestMetricEvent: typeof createRequestMetricEvent;
|
|
181
280
|
createRouteErrorEvent: typeof createRouteErrorEvent;
|
|
182
281
|
createRouteRequestEvent: typeof createRouteRequestEvent;
|
package/index.d.ts
CHANGED
|
@@ -8,6 +8,12 @@ import type {
|
|
|
8
8
|
TransportResponse
|
|
9
9
|
} from "@logbrew/sdk";
|
|
10
10
|
|
|
11
|
+
type NodeFetchTransportConfig = {
|
|
12
|
+
endpoint?: string;
|
|
13
|
+
fetchImpl?: typeof fetch;
|
|
14
|
+
headers?: Record<string, string>;
|
|
15
|
+
};
|
|
16
|
+
|
|
11
17
|
export type CreateLogBrewNextClientConfig = {
|
|
12
18
|
apiKey?: string;
|
|
13
19
|
serverApiKey?: string;
|
|
@@ -16,6 +22,77 @@ export type CreateLogBrewNextClientConfig = {
|
|
|
16
22
|
maxRetries?: number;
|
|
17
23
|
};
|
|
18
24
|
|
|
25
|
+
export type LogBrewNextRequestError = unknown;
|
|
26
|
+
|
|
27
|
+
export type LogBrewNextRequestErrorRequest = Readonly<{
|
|
28
|
+
path: string;
|
|
29
|
+
method: string;
|
|
30
|
+
headers: Readonly<Record<string, string | string[] | undefined>>;
|
|
31
|
+
}>;
|
|
32
|
+
|
|
33
|
+
export type LogBrewNextRequestErrorContext = Readonly<{
|
|
34
|
+
routerKind: "App Router" | "Pages Router";
|
|
35
|
+
routePath: string;
|
|
36
|
+
routeType: "action" | "middleware" | "proxy" | "render" | "route";
|
|
37
|
+
renderSource?: "react-server-components" | "react-server-components-payload" | "server-rendering";
|
|
38
|
+
revalidateReason?: "on-demand" | "stale";
|
|
39
|
+
renderType?: "dynamic" | "dynamic-resume";
|
|
40
|
+
}>;
|
|
41
|
+
|
|
42
|
+
export type LogBrewNextRequestErrorInput = {
|
|
43
|
+
error: LogBrewNextRequestError;
|
|
44
|
+
request: LogBrewNextRequestErrorRequest;
|
|
45
|
+
context: LogBrewNextRequestErrorContext;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export type LogBrewNextRequestErrorRuntimeContext = LogBrewNextRequestErrorInput & {
|
|
49
|
+
client?: LogBrewClient;
|
|
50
|
+
transport?: Transport;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export type LogBrewNextRequestErrorCaptureContext = LogBrewNextRequestErrorInput & {
|
|
54
|
+
client: LogBrewClient;
|
|
55
|
+
transport: Transport;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export type LogBrewNextRequestErrorEvent = {
|
|
59
|
+
id: string;
|
|
60
|
+
timestamp: string;
|
|
61
|
+
attributes: IssueAttributes;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export type LogBrewNextRequestErrorHandler = (
|
|
65
|
+
error: LogBrewNextRequestError,
|
|
66
|
+
request: LogBrewNextRequestErrorRequest,
|
|
67
|
+
context: LogBrewNextRequestErrorContext
|
|
68
|
+
) => Promise<void>;
|
|
69
|
+
|
|
70
|
+
export type LogBrewNextRequestErrorOptions = CreateLogBrewNextClientConfig & NodeFetchTransportConfig & {
|
|
71
|
+
/** A fixed client stays caller-owned and is flushed, not shut down. A factory must return a fresh client per error. */
|
|
72
|
+
client?: LogBrewClient | ((input: LogBrewNextRequestErrorInput) => LogBrewClient);
|
|
73
|
+
transport?: Transport | ((context: LogBrewNextRequestErrorInput & { client: LogBrewClient }) => Transport);
|
|
74
|
+
/** Opt into a query-free concrete pathname. Stable routePath metadata remains the default. */
|
|
75
|
+
includePathname?: boolean;
|
|
76
|
+
now?: () => string;
|
|
77
|
+
idFactory?: (
|
|
78
|
+
error: LogBrewNextRequestError,
|
|
79
|
+
request: LogBrewNextRequestErrorRequest,
|
|
80
|
+
context: LogBrewNextRequestErrorContext
|
|
81
|
+
) => string;
|
|
82
|
+
errorEvent?: (
|
|
83
|
+
error: LogBrewNextRequestError,
|
|
84
|
+
context: LogBrewNextRequestErrorCaptureContext
|
|
85
|
+
) => LogBrewNextRequestErrorEvent;
|
|
86
|
+
onFlush?: (
|
|
87
|
+
response: TransportResponse,
|
|
88
|
+
context: LogBrewNextRequestErrorCaptureContext
|
|
89
|
+
) => void | Promise<void>;
|
|
90
|
+
onCaptureError?: (
|
|
91
|
+
error: unknown,
|
|
92
|
+
context: LogBrewNextRequestErrorRuntimeContext
|
|
93
|
+
) => void | Promise<void>;
|
|
94
|
+
};
|
|
95
|
+
|
|
19
96
|
export type LogBrewRouteContext = Record<string, unknown>;
|
|
20
97
|
|
|
21
98
|
export type LogBrewTraceContext = {
|
|
@@ -90,8 +167,9 @@ export type LogBrewRouteMetricEvent = {
|
|
|
90
167
|
attributes: MetricAttributes;
|
|
91
168
|
};
|
|
92
169
|
|
|
93
|
-
export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewNextClientConfig & {
|
|
170
|
+
export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewNextClientConfig & NodeFetchTransportConfig & {
|
|
94
171
|
client?: LogBrewClient | LogBrewClientFactory<TContext>;
|
|
172
|
+
/** Override the default Node fetch transport, optionally per request. */
|
|
95
173
|
transport?: Transport | LogBrewTransportFactory<TContext>;
|
|
96
174
|
captureRequests?: boolean;
|
|
97
175
|
captureRequestMetrics?: boolean;
|
|
@@ -133,6 +211,25 @@ export declare function createLogBrewNextClient(
|
|
|
133
211
|
config?: CreateLogBrewNextClientConfig
|
|
134
212
|
): LogBrewClient;
|
|
135
213
|
|
|
214
|
+
export declare function createLogBrewNextRequestErrorHandler(
|
|
215
|
+
options?: LogBrewNextRequestErrorOptions
|
|
216
|
+
): LogBrewNextRequestErrorHandler;
|
|
217
|
+
|
|
218
|
+
export declare function createNextRequestErrorEvent(
|
|
219
|
+
error: LogBrewNextRequestError,
|
|
220
|
+
request: LogBrewNextRequestErrorRequest,
|
|
221
|
+
context: LogBrewNextRequestErrorContext,
|
|
222
|
+
options?: {
|
|
223
|
+
includePathname?: boolean;
|
|
224
|
+
now?: () => string;
|
|
225
|
+
idFactory?: (
|
|
226
|
+
error: LogBrewNextRequestError,
|
|
227
|
+
request: LogBrewNextRequestErrorRequest,
|
|
228
|
+
context: LogBrewNextRequestErrorContext
|
|
229
|
+
) => string;
|
|
230
|
+
}
|
|
231
|
+
): LogBrewNextRequestErrorEvent;
|
|
232
|
+
|
|
136
233
|
export declare function withLogBrewRouteHandler<TContext = LogBrewRouteContext>(
|
|
137
234
|
handler: LogBrewRouteHandler<TContext>,
|
|
138
235
|
options?: LogBrewRouteOptions<TContext>
|
|
@@ -177,6 +274,8 @@ export declare function createRouteErrorEvent(
|
|
|
177
274
|
|
|
178
275
|
declare const defaultExport: {
|
|
179
276
|
createLogBrewNextClient: typeof createLogBrewNextClient;
|
|
277
|
+
createLogBrewNextRequestErrorHandler: typeof createLogBrewNextRequestErrorHandler;
|
|
278
|
+
createNextRequestErrorEvent: typeof createNextRequestErrorEvent;
|
|
180
279
|
createRequestMetricEvent: typeof createRequestMetricEvent;
|
|
181
280
|
createRouteErrorEvent: typeof createRouteErrorEvent;
|
|
182
281
|
createRouteRequestEvent: typeof createRouteRequestEvent;
|
package/index.js
CHANGED
|
@@ -1,13 +1,24 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import {
|
|
3
3
|
LogBrewClient,
|
|
4
|
-
RecordingTransport,
|
|
5
4
|
SdkError,
|
|
6
5
|
parseTraceparent
|
|
7
6
|
} from "@logbrew/sdk";
|
|
7
|
+
import { createNodeFetchTransport } from "@logbrew/node";
|
|
8
8
|
|
|
9
9
|
const DEFAULT_SDK_NAME = "logbrew-next";
|
|
10
|
-
const DEFAULT_SDK_VERSION = "0.1.
|
|
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"]);
|
|
11
22
|
const activeTraceContext = new AsyncLocalStorage();
|
|
12
23
|
|
|
13
24
|
export function createLogBrewNextClient({
|
|
@@ -27,14 +38,81 @@ export function createLogBrewNextClient({
|
|
|
27
38
|
return LogBrewClient.create({ apiKey: authKey, sdkName, sdkVersion, maxRetries });
|
|
28
39
|
}
|
|
29
40
|
|
|
41
|
+
export function createLogBrewNextRequestErrorHandler(options = {}) {
|
|
42
|
+
const defaultTransport = options.transport === undefined
|
|
43
|
+
? createNodeFetchTransport(options)
|
|
44
|
+
: undefined;
|
|
45
|
+
|
|
46
|
+
return async function logBrewNextRequestErrorHandler(error, request = {}, context = {}) {
|
|
47
|
+
let runtime = { error, request, context };
|
|
48
|
+
try {
|
|
49
|
+
const resolvedClient = resolveRequestErrorClient(options, runtime);
|
|
50
|
+
const client = resolvedClient.client;
|
|
51
|
+
const transport = resolveRequestErrorTransport(options, { ...runtime, client }, defaultTransport);
|
|
52
|
+
runtime = { ...runtime, client, transport };
|
|
53
|
+
const event = typeof options.errorEvent === "function"
|
|
54
|
+
? options.errorEvent(error, runtime)
|
|
55
|
+
: createNextRequestErrorEvent(error, request, context, options);
|
|
56
|
+
|
|
57
|
+
client.issue(event.id, event.timestamp, event.attributes);
|
|
58
|
+
const response = resolvedClient.owned
|
|
59
|
+
? await client.shutdown(transport)
|
|
60
|
+
: await client.flush(transport);
|
|
61
|
+
await notifyFlush(options, response, runtime);
|
|
62
|
+
} catch (captureError) {
|
|
63
|
+
try {
|
|
64
|
+
await notifyFailure(options, captureError, runtime);
|
|
65
|
+
} catch {
|
|
66
|
+
// Observability callbacks must not replace the application error Next.js is handling.
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function createNextRequestErrorEvent(error, request = {}, context = {}, {
|
|
73
|
+
includePathname = false,
|
|
74
|
+
now = () => new Date().toISOString(),
|
|
75
|
+
idFactory = defaultNextRequestErrorId
|
|
76
|
+
} = {}) {
|
|
77
|
+
const method = nextRequestMethod(request);
|
|
78
|
+
const routePath = nextRoutePath(context?.routePath);
|
|
79
|
+
const pathname = includePathname ? nextRoutePath(request?.path) : undefined;
|
|
80
|
+
const errorDigest = nextErrorDigest(error);
|
|
81
|
+
return {
|
|
82
|
+
id: idFactory(error, request, context),
|
|
83
|
+
timestamp: now(),
|
|
84
|
+
attributes: {
|
|
85
|
+
title: `${method} ${routePath} failed`,
|
|
86
|
+
level: "error",
|
|
87
|
+
message: nextErrorMessage(error),
|
|
88
|
+
metadata: {
|
|
89
|
+
framework: "nextjs",
|
|
90
|
+
method,
|
|
91
|
+
routePath,
|
|
92
|
+
...nextCategoricalMetadata("routerKind", context?.routerKind, NEXT_ROUTER_KINDS),
|
|
93
|
+
...nextCategoricalMetadata("routeType", context?.routeType, NEXT_ROUTE_TYPES),
|
|
94
|
+
...nextCategoricalMetadata("renderSource", context?.renderSource, NEXT_RENDER_SOURCES),
|
|
95
|
+
...nextCategoricalMetadata("revalidateReason", context?.revalidateReason, NEXT_REVALIDATE_REASONS),
|
|
96
|
+
...nextCategoricalMetadata("renderType", context?.renderType, NEXT_RENDER_TYPES),
|
|
97
|
+
...(errorDigest ? { errorDigest } : {}),
|
|
98
|
+
...(pathname ? { pathname } : {})
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
30
104
|
export function withLogBrewRouteHandler(handler, options = {}) {
|
|
31
105
|
if (typeof handler !== "function") {
|
|
32
106
|
throw new SdkError("configuration_error", "withLogBrewRouteHandler requires a handler function");
|
|
33
107
|
}
|
|
34
108
|
|
|
109
|
+
const defaultTransport = options.transport === undefined
|
|
110
|
+
? createNodeFetchTransport(options)
|
|
111
|
+
: undefined;
|
|
112
|
+
|
|
35
113
|
return async function logBrewRouteHandler(request, context = {}) {
|
|
36
114
|
const client = resolveClient(options, request, context);
|
|
37
|
-
const transport = resolveTransport(options, request, context, client);
|
|
115
|
+
const transport = resolveTransport(options, request, context, client, defaultTransport);
|
|
38
116
|
const trace = createRouteTraceContext(request, undefined, options);
|
|
39
117
|
const helpers = createRouteHelpers(client, transport, trace);
|
|
40
118
|
const startedAt = nowMs(options);
|
|
@@ -168,11 +246,28 @@ function resolveClient(options, request, context) {
|
|
|
168
246
|
return createLogBrewNextClient(options);
|
|
169
247
|
}
|
|
170
248
|
|
|
171
|
-
function resolveTransport(options, request, context, client) {
|
|
249
|
+
function resolveTransport(options, request, context, client, defaultTransport) {
|
|
172
250
|
if (typeof options.transport === "function") {
|
|
173
251
|
return options.transport({ request, context, client });
|
|
174
252
|
}
|
|
175
|
-
return options.transport ??
|
|
253
|
+
return options.transport ?? defaultTransport;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function resolveRequestErrorClient(options, runtime) {
|
|
257
|
+
if (typeof options.client === "function") {
|
|
258
|
+
return { client: options.client(runtime), owned: true };
|
|
259
|
+
}
|
|
260
|
+
if (options.client) {
|
|
261
|
+
return { client: options.client, owned: false };
|
|
262
|
+
}
|
|
263
|
+
return { client: createLogBrewNextClient(options), owned: true };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function resolveRequestErrorTransport(options, runtime, defaultTransport) {
|
|
267
|
+
if (typeof options.transport === "function") {
|
|
268
|
+
return options.transport(runtime);
|
|
269
|
+
}
|
|
270
|
+
return options.transport ?? defaultTransport;
|
|
176
271
|
}
|
|
177
272
|
|
|
178
273
|
function createRouteHelpers(client, transport, trace) {
|
|
@@ -298,6 +393,10 @@ function defaultRouteErrorId(request) {
|
|
|
298
393
|
return `evt_next_error_${slug || "route"}`;
|
|
299
394
|
}
|
|
300
395
|
|
|
396
|
+
function defaultNextRequestErrorId() {
|
|
397
|
+
return `evt_next_request_error_${randomHex(8)}`;
|
|
398
|
+
}
|
|
399
|
+
|
|
301
400
|
function defaultRouteMetricId(request, response, routeTemplate = safeUrl(request).pathname) {
|
|
302
401
|
const sanitizedRouteTemplate = routeTemplateOnly(routeTemplate);
|
|
303
402
|
const slug = `${request?.method ?? "GET"}-${sanitizedRouteTemplate}-${response?.status ?? 0}`
|
|
@@ -315,6 +414,55 @@ function safeUrl(request) {
|
|
|
315
414
|
}
|
|
316
415
|
}
|
|
317
416
|
|
|
417
|
+
function nextRequestMethod(request) {
|
|
418
|
+
const method = typeof request?.method === "string" ? request.method.trim().toUpperCase() : "";
|
|
419
|
+
return /^[A-Z]{1,16}$/u.test(method) ? method : "UNKNOWN";
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function nextRoutePath(value) {
|
|
423
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
424
|
+
return "/";
|
|
425
|
+
}
|
|
426
|
+
let pathname;
|
|
427
|
+
try {
|
|
428
|
+
pathname = new URL(value, "http://localhost").pathname;
|
|
429
|
+
} catch {
|
|
430
|
+
pathname = value.split(/[?#]/u)[0];
|
|
431
|
+
}
|
|
432
|
+
if (typeof pathname !== "string" || pathname === "") {
|
|
433
|
+
return "/";
|
|
434
|
+
}
|
|
435
|
+
const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
|
436
|
+
return normalized.length <= MAX_REQUEST_ROUTE_PATH_LENGTH ? normalized : "/";
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function nextCategoricalMetadata(key, value, allowed) {
|
|
440
|
+
return typeof value === "string" && allowed.has(value) ? { [key]: value } : {};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function nextErrorDigest(error) {
|
|
444
|
+
const digest = error && typeof error === "object" ? error.digest : undefined;
|
|
445
|
+
if (typeof digest !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/u.test(digest)) {
|
|
446
|
+
return undefined;
|
|
447
|
+
}
|
|
448
|
+
return digest;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function nextErrorMessage(error) {
|
|
452
|
+
let message;
|
|
453
|
+
try {
|
|
454
|
+
message = error instanceof Error ? error.message : String(error);
|
|
455
|
+
} catch {
|
|
456
|
+
message = "Next.js request failed";
|
|
457
|
+
}
|
|
458
|
+
const normalized = typeof message === "string" && message.trim() !== ""
|
|
459
|
+
? message
|
|
460
|
+
: "Next.js request failed";
|
|
461
|
+
return normalized.length <= MAX_REQUEST_ERROR_MESSAGE_LENGTH
|
|
462
|
+
? normalized
|
|
463
|
+
: `${normalized.slice(0, MAX_REQUEST_ERROR_MESSAGE_LENGTH - 1)}…`;
|
|
464
|
+
}
|
|
465
|
+
|
|
318
466
|
function getTraceparentHeader(request) {
|
|
319
467
|
if (!request?.headers || typeof request.headers.get !== "function") {
|
|
320
468
|
return undefined;
|
|
@@ -464,6 +612,8 @@ function readEnvServerApiKey() {
|
|
|
464
612
|
|
|
465
613
|
export default {
|
|
466
614
|
createLogBrewNextClient,
|
|
615
|
+
createLogBrewNextRequestErrorHandler,
|
|
616
|
+
createNextRequestErrorEvent,
|
|
467
617
|
createRequestMetricEvent,
|
|
468
618
|
createRouteErrorEvent,
|
|
469
619
|
createRouteRequestEvent,
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
let nodeHandlerPromise;
|
|
2
|
+
|
|
3
|
+
function createLogBrewNextRequestErrorHandler(options = {}) {
|
|
4
|
+
let handler;
|
|
5
|
+
return async function logBrewNextRequestErrorHandler(error, request, context) {
|
|
6
|
+
if (globalThis.process?.env?.NEXT_RUNTIME === "edge") {
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
try {
|
|
11
|
+
nodeHandlerPromise ??= Promise.resolve().then(() => require("./index.cjs"));
|
|
12
|
+
const module = await nodeHandlerPromise;
|
|
13
|
+
handler ??= module.createLogBrewNextRequestErrorHandler(options);
|
|
14
|
+
await handler(error, request, context);
|
|
15
|
+
} catch (captureError) {
|
|
16
|
+
if (typeof options.onCaptureError === "function") {
|
|
17
|
+
try {
|
|
18
|
+
await options.onCaptureError(captureError, { error, request, context });
|
|
19
|
+
} catch {
|
|
20
|
+
// Observability callbacks must not replace the application error Next.js is handling.
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
module.exports = {
|
|
28
|
+
createLogBrewNextRequestErrorHandler
|
|
29
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
LogBrewNextRequestErrorHandler,
|
|
3
|
+
LogBrewNextRequestErrorOptions
|
|
4
|
+
} from "./index.cjs";
|
|
5
|
+
|
|
6
|
+
export type {
|
|
7
|
+
LogBrewNextRequestError,
|
|
8
|
+
LogBrewNextRequestErrorCaptureContext,
|
|
9
|
+
LogBrewNextRequestErrorContext,
|
|
10
|
+
LogBrewNextRequestErrorEvent,
|
|
11
|
+
LogBrewNextRequestErrorHandler,
|
|
12
|
+
LogBrewNextRequestErrorInput,
|
|
13
|
+
LogBrewNextRequestErrorOptions,
|
|
14
|
+
LogBrewNextRequestErrorRequest,
|
|
15
|
+
LogBrewNextRequestErrorRuntimeContext
|
|
16
|
+
} from "./index.cjs";
|
|
17
|
+
|
|
18
|
+
export declare function createLogBrewNextRequestErrorHandler(
|
|
19
|
+
options?: LogBrewNextRequestErrorOptions
|
|
20
|
+
): LogBrewNextRequestErrorHandler;
|
|
21
|
+
|
|
22
|
+
declare const defaultExport: {
|
|
23
|
+
createLogBrewNextRequestErrorHandler: typeof createLogBrewNextRequestErrorHandler;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export default defaultExport;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
LogBrewNextRequestErrorHandler,
|
|
3
|
+
LogBrewNextRequestErrorOptions
|
|
4
|
+
} from "./index.js";
|
|
5
|
+
|
|
6
|
+
export type {
|
|
7
|
+
LogBrewNextRequestError,
|
|
8
|
+
LogBrewNextRequestErrorCaptureContext,
|
|
9
|
+
LogBrewNextRequestErrorContext,
|
|
10
|
+
LogBrewNextRequestErrorEvent,
|
|
11
|
+
LogBrewNextRequestErrorHandler,
|
|
12
|
+
LogBrewNextRequestErrorInput,
|
|
13
|
+
LogBrewNextRequestErrorOptions,
|
|
14
|
+
LogBrewNextRequestErrorRequest,
|
|
15
|
+
LogBrewNextRequestErrorRuntimeContext
|
|
16
|
+
} from "./index.js";
|
|
17
|
+
|
|
18
|
+
export declare function createLogBrewNextRequestErrorHandler(
|
|
19
|
+
options?: LogBrewNextRequestErrorOptions
|
|
20
|
+
): LogBrewNextRequestErrorHandler;
|
|
21
|
+
|
|
22
|
+
declare const defaultExport: {
|
|
23
|
+
createLogBrewNextRequestErrorHandler: typeof createLogBrewNextRequestErrorHandler;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export default defaultExport;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
let nodeHandlerPromise;
|
|
2
|
+
|
|
3
|
+
export function createLogBrewNextRequestErrorHandler(options = {}) {
|
|
4
|
+
let handler;
|
|
5
|
+
return async function logBrewNextRequestErrorHandler(error, request, context) {
|
|
6
|
+
if (globalThis.process?.env?.NEXT_RUNTIME === "edge") {
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
try {
|
|
11
|
+
nodeHandlerPromise ??= import("./index.js");
|
|
12
|
+
const module = await nodeHandlerPromise;
|
|
13
|
+
handler ??= module.createLogBrewNextRequestErrorHandler(options);
|
|
14
|
+
await handler(error, request, context);
|
|
15
|
+
} catch (captureError) {
|
|
16
|
+
if (typeof options.onCaptureError === "function") {
|
|
17
|
+
try {
|
|
18
|
+
await options.onCaptureError(captureError, { error, request, context });
|
|
19
|
+
} catch {
|
|
20
|
+
// Observability callbacks must not replace the application error Next.js is handling.
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export default {
|
|
28
|
+
createLogBrewNextRequestErrorHandler
|
|
29
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@logbrew/next",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Next.js App Router helpers for the public LogBrew JavaScript SDK.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.cjs",
|
|
@@ -28,6 +28,17 @@
|
|
|
28
28
|
},
|
|
29
29
|
"default": "./client.js"
|
|
30
30
|
},
|
|
31
|
+
"./instrumentation": {
|
|
32
|
+
"import": {
|
|
33
|
+
"types": "./instrumentation.d.ts",
|
|
34
|
+
"default": "./instrumentation.js"
|
|
35
|
+
},
|
|
36
|
+
"require": {
|
|
37
|
+
"types": "./instrumentation.d.cts",
|
|
38
|
+
"default": "./instrumentation.cjs"
|
|
39
|
+
},
|
|
40
|
+
"default": "./instrumentation.js"
|
|
41
|
+
},
|
|
31
42
|
"./release-artifacts": {
|
|
32
43
|
"import": {
|
|
33
44
|
"types": "./release-artifacts.d.ts",
|
|
@@ -49,6 +60,10 @@
|
|
|
49
60
|
"client.js",
|
|
50
61
|
"client.d.ts",
|
|
51
62
|
"client.d.cts",
|
|
63
|
+
"instrumentation.cjs",
|
|
64
|
+
"instrumentation.js",
|
|
65
|
+
"instrumentation.d.ts",
|
|
66
|
+
"instrumentation.d.cts",
|
|
52
67
|
"release-artifacts.cjs",
|
|
53
68
|
"release-artifacts.js",
|
|
54
69
|
"release-artifacts.d.ts",
|
|
@@ -75,12 +90,13 @@
|
|
|
75
90
|
"url": "git+https://github.com/LogBrewCo/sdk.git"
|
|
76
91
|
},
|
|
77
92
|
"peerDependencies": {
|
|
78
|
-
"@logbrew/
|
|
93
|
+
"@logbrew/node": "^0.1.2",
|
|
94
|
+
"@logbrew/sdk": "^0.1.3",
|
|
79
95
|
"next": ">=15",
|
|
80
96
|
"react": ">=18",
|
|
81
97
|
"react-dom": ">=18"
|
|
82
98
|
},
|
|
83
99
|
"scripts": {
|
|
84
|
-
"test": "node --check index.js && node --check index.cjs && node --check client.js && node --check client.cjs && node --check release-artifacts.js && node --check release-artifacts.cjs && node --check examples/index.mjs && node --check examples/client-route-spans.mjs && node --check examples/readme-example.mjs && node --check examples/real-user-smoke.mjs && node --test"
|
|
100
|
+
"test": "node --check index.js && node --check index.cjs && node --check client.js && node --check client.cjs && node --check instrumentation.js && node --check instrumentation.cjs && node --check release-artifacts.js && node --check release-artifacts.cjs && node --check examples/index.mjs && node --check examples/client-route-spans.mjs && node --check examples/readme-example.mjs && node --check examples/request-errors.mjs && node --check examples/real-user-smoke.mjs && node --test"
|
|
85
101
|
}
|
|
86
102
|
}
|