@logbrew/next 0.1.0

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 ADDED
@@ -0,0 +1,77 @@
1
+ # @logbrew/next
2
+
3
+ Next.js App Router helpers for the public LogBrew JavaScript SDK.
4
+
5
+ This package is intentionally thin. It creates server-side LogBrew clients, wraps App Router Route Handlers, captures successful route requests and thrown route errors, and still keeps manual event creation available through the route helpers.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @logbrew/sdk @logbrew/next next react react-dom
11
+ pnpm add @logbrew/sdk @logbrew/next next react react-dom
12
+ ```
13
+
14
+ ## App Router Route Handler
15
+
16
+ ```js
17
+ // app/api/logbrew/route.js
18
+ import { RecordingTransport } from "@logbrew/sdk";
19
+ import { withLogBrewRouteHandler } from "@logbrew/next";
20
+
21
+ export const runtime = "nodejs";
22
+
23
+ export const POST = withLogBrewRouteHandler(
24
+ async (_request, _context, { client }) => {
25
+ client.log("evt_log_001", "2026-06-02T10:00:03Z", {
26
+ message: "worker started",
27
+ level: "info",
28
+ logger: "job-runner"
29
+ });
30
+
31
+ return Response.json(JSON.parse(client.previewJson()));
32
+ },
33
+ {
34
+ serverApiKey: "LOGBREW_SERVER_API_KEY",
35
+ spanIdFactory: () => "b7ad6b7169203331",
36
+ transport: RecordingTransport.alwaysAccept()
37
+ }
38
+ );
39
+ ```
40
+
41
+ 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.
42
+
43
+ By default, successful Route Handler responses are captured after your handler returns. When the incoming `Request` has a valid W3C `traceparent` header, request capture records a LogBrew `span` that continues the incoming trace. 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 tests or edge runtimes need deterministic child span IDs, and use `onCaptureError` to observe telemetry delivery failures without letting observability own the route response.
44
+
45
+ Automatic route error events record the method and pathname, but omit query strings by default. Pass `includeSearchParams: true` only when query capture is intentional and safe for the route.
46
+
47
+ The wrapper expects App Router Route Handlers that return standard `Response` objects. It does not call `NextResponse.next()` and does not use the deprecated `middleware` filename. For Next.js 16 request interception, use the framework's `proxy.js` convention separately and keep LogBrew event creation in server-side route code.
48
+
49
+ ## Client Helper
50
+
51
+ ```js
52
+ import { createLogBrewNextClient } from "@logbrew/next";
53
+
54
+ const client = createLogBrewNextClient({
55
+ serverApiKey: "LOGBREW_SERVER_API_KEY",
56
+ sdkName: "my-next-app",
57
+ sdkVersion: "0.1.0"
58
+ });
59
+ ```
60
+
61
+ ## Packaged Examples
62
+
63
+ After install, these commands are available from a consumer app:
64
+
65
+ ```bash
66
+ node node_modules/@logbrew/next/examples/index.mjs --help
67
+ node node_modules/@logbrew/next/examples/index.mjs --list
68
+ node node_modules/@logbrew/next/examples/index.mjs readme-example
69
+ node node_modules/@logbrew/next/examples/index.mjs real-user-smoke
70
+ node node_modules/@logbrew/next/examples/index.mjs
71
+ npm --prefix node_modules/@logbrew/next/examples run help
72
+ npm --prefix node_modules/@logbrew/next/examples run list
73
+ npm --prefix node_modules/@logbrew/next/examples run readme-example
74
+ npm --prefix node_modules/@logbrew/next/examples run real-user-smoke
75
+ ```
76
+
77
+ The default launcher path runs `real-user-smoke`.
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+
3
+ const commands = new Map([
4
+ ["readme-example", new URL("./readme-example.mjs", import.meta.url)],
5
+ ["real-user-smoke", new URL("./real-user-smoke.mjs", import.meta.url)]
6
+ ]);
7
+
8
+ const command = process.argv[2] ?? "real-user-smoke";
9
+
10
+ if (command === "--help" || command === "-h") {
11
+ printHelp();
12
+ } else if (command === "--list") {
13
+ printList();
14
+ } else if (commands.has(command)) {
15
+ await import(commands.get(command));
16
+ } else {
17
+ console.error(`Unknown LogBrew Next.js example: ${command}`);
18
+ printList();
19
+ process.exitCode = 1;
20
+ }
21
+
22
+ function printHelp() {
23
+ console.log("LogBrew Next.js examples");
24
+ console.log("node node_modules/@logbrew/next/examples/index.mjs --list");
25
+ console.log("node node_modules/@logbrew/next/examples/index.mjs readme-example");
26
+ console.log("node node_modules/@logbrew/next/examples/index.mjs real-user-smoke");
27
+ console.log("node node_modules/@logbrew/next/examples/index.mjs");
28
+ console.log("npm --prefix node_modules/@logbrew/next/examples run list");
29
+ console.log("npm --prefix node_modules/@logbrew/next/examples run readme-example");
30
+ console.log("npm --prefix node_modules/@logbrew/next/examples run real-user-smoke");
31
+ }
32
+
33
+ function printList() {
34
+ console.log("readme-example -> node node_modules/@logbrew/next/examples/index.mjs readme-example");
35
+ console.log("real-user-smoke -> node node_modules/@logbrew/next/examples/index.mjs real-user-smoke");
36
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "private": true,
3
+ "type": "module",
4
+ "scripts": {
5
+ "help": "node ./index.mjs --help",
6
+ "list": "node ./index.mjs --list",
7
+ "readme-example": "node ./index.mjs readme-example",
8
+ "real-user-smoke": "node ./index.mjs real-user-smoke"
9
+ }
10
+ }
@@ -0,0 +1,55 @@
1
+ import { RecordingTransport } from "@logbrew/sdk";
2
+ import { withLogBrewRouteHandler } from "@logbrew/next";
3
+
4
+ const transport = RecordingTransport.alwaysAccept();
5
+
6
+ const POST = withLogBrewRouteHandler(
7
+ async (_request, _context, { client }) => {
8
+ addFullBatch(client);
9
+ return Response.json(JSON.parse(client.previewJson()));
10
+ },
11
+ {
12
+ serverApiKey: "LOGBREW_SERVER_API_KEY",
13
+ captureRequests: false,
14
+ sdkName: "logbrew-next-readme-example",
15
+ sdkVersion: "0.1.0",
16
+ transport
17
+ }
18
+ );
19
+
20
+ const response = await POST(new Request("https://example.com/api/logbrew", { method: "POST" }), {});
21
+ console.log(await response.text());
22
+ console.error(JSON.stringify({ ok: true, status: response.status, attempts: transport.sentBodies.length, events: 6 }));
23
+
24
+ function addFullBatch(client) {
25
+ client.release("evt_release_001", "2026-06-02T10:00:00Z", {
26
+ version: "1.2.3",
27
+ commit: "abc123def456",
28
+ notes: "Public release marker"
29
+ });
30
+ client.environment("evt_environment_001", "2026-06-02T10:00:01Z", {
31
+ name: "production",
32
+ region: "global"
33
+ });
34
+ client.issue("evt_issue_001", "2026-06-02T10:00:02Z", {
35
+ title: "Checkout timeout",
36
+ level: "error",
37
+ message: "Request timed out after retry budget"
38
+ });
39
+ client.log("evt_log_001", "2026-06-02T10:00:03Z", {
40
+ message: "worker started",
41
+ level: "info",
42
+ logger: "job-runner"
43
+ });
44
+ client.span("evt_span_001", "2026-06-02T10:00:04Z", {
45
+ name: "GET /health",
46
+ traceId: "trace_001",
47
+ spanId: "span_001",
48
+ status: "ok",
49
+ durationMs: 12.5
50
+ });
51
+ client.action("evt_action_001", "2026-06-02T10:00:05Z", {
52
+ name: "deploy",
53
+ status: "success"
54
+ });
55
+ }
@@ -0,0 +1,56 @@
1
+ import { RecordingTransport } from "@logbrew/sdk";
2
+ import { withLogBrewRouteHandler } from "@logbrew/next";
3
+
4
+ const transport = new RecordingTransport([{ statusCode: 503 }, { statusCode: 202 }]);
5
+
6
+ const POST = withLogBrewRouteHandler(
7
+ async (_request, _context, { client }) => {
8
+ addFullBatch(client);
9
+ return Response.json(JSON.parse(client.previewJson()));
10
+ },
11
+ {
12
+ serverApiKey: "LOGBREW_SERVER_API_KEY",
13
+ captureRequests: false,
14
+ sdkName: "logbrew-next-real-user-smoke",
15
+ sdkVersion: "0.1.0",
16
+ maxRetries: 1,
17
+ transport
18
+ }
19
+ );
20
+
21
+ const response = await POST(new Request("https://example.com/api/logbrew", { method: "POST" }), {});
22
+ console.log(await response.text());
23
+ console.error(JSON.stringify({ ok: true, status: response.status, attempts: transport.sentBodies.length, events: 6 }));
24
+
25
+ function addFullBatch(client) {
26
+ client.release("evt_release_001", "2026-06-02T10:00:00Z", {
27
+ version: "1.2.3",
28
+ commit: "abc123def456",
29
+ notes: "Public release marker"
30
+ });
31
+ client.environment("evt_environment_001", "2026-06-02T10:00:01Z", {
32
+ name: "production",
33
+ region: "global"
34
+ });
35
+ client.issue("evt_issue_001", "2026-06-02T10:00:02Z", {
36
+ title: "Checkout timeout",
37
+ level: "error",
38
+ message: "Request timed out after retry budget"
39
+ });
40
+ client.log("evt_log_001", "2026-06-02T10:00:03Z", {
41
+ message: "worker started",
42
+ level: "info",
43
+ logger: "job-runner"
44
+ });
45
+ client.span("evt_span_001", "2026-06-02T10:00:04Z", {
46
+ name: "GET /health",
47
+ traceId: "trace_001",
48
+ spanId: "span_001",
49
+ status: "ok",
50
+ durationMs: 12.5
51
+ });
52
+ client.action("evt_action_001", "2026-06-02T10:00:05Z", {
53
+ name: "deploy",
54
+ status: "success"
55
+ });
56
+ }
package/index.cjs ADDED
@@ -0,0 +1,322 @@
1
+ const {
2
+ LogBrewClient,
3
+ RecordingTransport,
4
+ SdkError,
5
+ parseTraceparent,
6
+ spanAttributesFromTraceparent
7
+ } = require("@logbrew/sdk");
8
+
9
+ const DEFAULT_SDK_NAME = "logbrew-next";
10
+ const DEFAULT_SDK_VERSION = "0.1.0";
11
+
12
+ function createLogBrewNextClient({
13
+ apiKey,
14
+ serverApiKey,
15
+ sdkName = DEFAULT_SDK_NAME,
16
+ sdkVersion = DEFAULT_SDK_VERSION,
17
+ maxRetries = 2
18
+ } = {}) {
19
+ const authKey = serverApiKey ?? apiKey ?? readEnvServerApiKey() ?? readEnvApiKey();
20
+ if (!authKey) {
21
+ throw new SdkError(
22
+ "configuration_error",
23
+ "createLogBrewNextClient requires serverApiKey, apiKey, LOGBREW_SERVER_API_KEY, or LOGBREW_API_KEY"
24
+ );
25
+ }
26
+ return LogBrewClient.create({ apiKey: authKey, sdkName, sdkVersion, maxRetries });
27
+ }
28
+
29
+ function withLogBrewRouteHandler(handler, options = {}) {
30
+ if (typeof handler !== "function") {
31
+ throw new SdkError("configuration_error", "withLogBrewRouteHandler requires a handler function");
32
+ }
33
+
34
+ return async function logBrewRouteHandler(request, context = {}) {
35
+ const client = resolveClient(options, request, context);
36
+ const transport = resolveTransport(options, request, context, client);
37
+ const helpers = createRouteHelpers(client, transport);
38
+ const startedAt = nowMs(options);
39
+
40
+ try {
41
+ const response = await handler(request, context, helpers);
42
+ ensureResponse(response);
43
+ await captureRouteSuccess(options, { request, response, context, client, transport, startedAt });
44
+ return response;
45
+ } catch (error) {
46
+ await recordRouteError(options, error, { request, context, client, transport });
47
+ throw error;
48
+ }
49
+ };
50
+ }
51
+
52
+ function createRouteRequestEvent(request, response, {
53
+ now = () => new Date().toISOString(),
54
+ durationMs = 0,
55
+ idFactory = defaultRouteRequestId,
56
+ spanIdFactory = defaultSpanIdFactory
57
+ } = {}) {
58
+ const url = safeUrl(request);
59
+ const method = request?.method ?? "GET";
60
+ const statusCode = Number(response?.status ?? 0);
61
+ const id = idFactory(request, response);
62
+ const traceparent = getTraceparentHeader(request);
63
+ const spanEvent = traceparent
64
+ ? createTraceparentRouteSpan(traceparent, {
65
+ durationMs,
66
+ id,
67
+ method,
68
+ now,
69
+ pathname: url.pathname,
70
+ spanIdFactory: () => spanIdFactory(request, response),
71
+ statusCode
72
+ })
73
+ : undefined;
74
+ if (spanEvent) {
75
+ return spanEvent;
76
+ }
77
+
78
+ return {
79
+ id,
80
+ timestamp: now(),
81
+ attributes: {
82
+ message: `${method} ${url.pathname} ${statusCode}`,
83
+ level: statusCode >= 500 ? "error" : "info",
84
+ logger: "next",
85
+ metadata: {
86
+ framework: "nextjs",
87
+ method,
88
+ pathname: url.pathname,
89
+ statusCode,
90
+ durationMs
91
+ }
92
+ }
93
+ };
94
+ }
95
+
96
+ function createRouteErrorEvent(error, request, {
97
+ includeSearchParams = false,
98
+ now = () => new Date().toISOString(),
99
+ idFactory = defaultRouteErrorId
100
+ } = {}) {
101
+ const url = safeUrl(request);
102
+ const method = request?.method ?? "GET";
103
+ const message = error instanceof Error ? error.message : String(error);
104
+ return {
105
+ id: idFactory(request),
106
+ timestamp: now(),
107
+ attributes: {
108
+ title: `${method} ${url.pathname} failed`,
109
+ level: "error",
110
+ message,
111
+ metadata: {
112
+ method,
113
+ pathname: url.pathname,
114
+ ...(includeSearchParams ? { search: url.search || null } : {})
115
+ }
116
+ }
117
+ };
118
+ }
119
+
120
+ function resolveClient(options, request, context) {
121
+ if (typeof options.client === "function") {
122
+ return options.client({ request, context });
123
+ }
124
+ if (options.client) {
125
+ return options.client;
126
+ }
127
+ return createLogBrewNextClient(options);
128
+ }
129
+
130
+ function resolveTransport(options, request, context, client) {
131
+ if (typeof options.transport === "function") {
132
+ return options.transport({ request, context, client });
133
+ }
134
+ return options.transport ?? RecordingTransport.alwaysAccept();
135
+ }
136
+
137
+ function createRouteHelpers(client, transport) {
138
+ return {
139
+ client,
140
+ logbrew: client,
141
+ previewJson: () => client.previewJson(),
142
+ flush: () => client.flush(transport),
143
+ shutdown: () => client.shutdown(transport)
144
+ };
145
+ }
146
+
147
+ function ensureResponse(response) {
148
+ if (!(response instanceof Response)) {
149
+ throw new SdkError("route_handler_error", "Next.js route handler must return a Response");
150
+ }
151
+ }
152
+
153
+ async function notifyFlush(options, flushResponse, context) {
154
+ if (typeof options.onFlush === "function") {
155
+ await options.onFlush(flushResponse, context);
156
+ }
157
+ }
158
+
159
+ async function notifyFailure(options, error, context) {
160
+ if (typeof options.onCaptureError === "function") {
161
+ await options.onCaptureError(error, context);
162
+ }
163
+ }
164
+
165
+ async function captureRouteSuccess(options, { request, response, context, client, transport, startedAt }) {
166
+ try {
167
+ if (options.captureRequests !== false) {
168
+ recordRouteRequest(options, { request, response, context, client, startedAt });
169
+ }
170
+ const flushResponse = await client.shutdown(transport);
171
+ await notifyFlush(options, flushResponse, { request, context, client });
172
+ } catch (error) {
173
+ await notifyFailure(options, error, { request, context, client });
174
+ }
175
+ }
176
+
177
+ function recordRouteRequest(options, { request, response, context, client, startedAt }) {
178
+ const durationMs = Math.max(0, Math.round(nowMs(options) - startedAt));
179
+ const event = typeof options.requestEvent === "function"
180
+ ? options.requestEvent(request, response, { client, context, durationMs, request, response })
181
+ : createRouteRequestEvent(request, response, {
182
+ ...options,
183
+ durationMs,
184
+ idFactory: options.requestIdFactory
185
+ });
186
+ captureRouteRequestEvent(client, event);
187
+ }
188
+
189
+ async function recordRouteError(options, error, { request, context, client, transport }) {
190
+ if (options.captureErrors === false) {
191
+ return;
192
+ }
193
+ const event = typeof options.errorEvent === "function"
194
+ ? options.errorEvent(error, { request, context, client })
195
+ : createRouteErrorEvent(error, request, options);
196
+ try {
197
+ client.issue(event.id, event.timestamp, event.attributes);
198
+ const flushResponse = await client.shutdown(transport);
199
+ await notifyFlush(options, flushResponse, { request, context, client });
200
+ } catch (captureError) {
201
+ await notifyFailure(options, captureError, { request, context, client });
202
+ }
203
+ }
204
+
205
+ function captureRouteRequestEvent(client, event) {
206
+ if (event.type === "span") {
207
+ client.span(event.id, event.timestamp, event.attributes);
208
+ return;
209
+ }
210
+ client.log(event.id, event.timestamp, event.attributes);
211
+ }
212
+
213
+ function defaultRouteRequestId(request, response) {
214
+ const url = safeUrl(request);
215
+ const slug = `${request?.method ?? "GET"}-${url.pathname}-${response?.status ?? 0}`
216
+ .toLowerCase()
217
+ .replace(/[^a-z0-9]+/g, "_")
218
+ .replace(/^_+|_+$/g, "");
219
+ return `evt_next_request_${slug || "route"}`;
220
+ }
221
+
222
+ function defaultSpanIdFactory() {
223
+ return randomHex(8);
224
+ }
225
+
226
+ function defaultRouteErrorId(request) {
227
+ const url = safeUrl(request);
228
+ const slug = `${request?.method ?? "GET"}-${url.pathname}`
229
+ .toLowerCase()
230
+ .replace(/[^a-z0-9]+/g, "_")
231
+ .replace(/^_+|_+$/g, "");
232
+ return `evt_next_error_${slug || "route"}`;
233
+ }
234
+
235
+ function safeUrl(request) {
236
+ try {
237
+ return new URL(request?.url ?? "http://localhost/");
238
+ } catch {
239
+ return new URL("http://localhost/");
240
+ }
241
+ }
242
+
243
+ function getTraceparentHeader(request) {
244
+ if (!request?.headers || typeof request.headers.get !== "function") {
245
+ return undefined;
246
+ }
247
+ const value = request.headers.get("traceparent");
248
+ return typeof value === "string" ? value : undefined;
249
+ }
250
+
251
+ function createTraceparentRouteSpan(traceparent, {
252
+ durationMs,
253
+ id,
254
+ method,
255
+ now,
256
+ pathname,
257
+ spanIdFactory,
258
+ statusCode
259
+ }) {
260
+ if (!traceparent) {
261
+ return undefined;
262
+ }
263
+
264
+ try {
265
+ parseTraceparent(traceparent);
266
+ const spanId = spanIdFactory();
267
+ return {
268
+ id,
269
+ timestamp: now(),
270
+ type: "span",
271
+ attributes: spanAttributesFromTraceparent(traceparent, {
272
+ durationMs,
273
+ metadata: {
274
+ framework: "nextjs",
275
+ method,
276
+ pathname,
277
+ statusCode
278
+ },
279
+ name: `${method} ${pathname}`,
280
+ spanId,
281
+ status: statusCode >= 500 ? "error" : "ok"
282
+ })
283
+ };
284
+ } catch {
285
+ return undefined;
286
+ }
287
+ }
288
+
289
+ function nowMs(options) {
290
+ if (typeof options.nowMs === "function") {
291
+ return options.nowMs();
292
+ }
293
+ return performance.now();
294
+ }
295
+
296
+ function randomHex(byteLength) {
297
+ const bytes = new Uint8Array(byteLength);
298
+ if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
299
+ globalThis.crypto.getRandomValues(bytes);
300
+ } else {
301
+ for (let index = 0; index < bytes.length; index += 1) {
302
+ bytes[index] = Math.floor(Math.random() * 256);
303
+ }
304
+ }
305
+ const value = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
306
+ return /^0+$/.test(value) ? "0000000000000001" : value;
307
+ }
308
+
309
+ function readEnvApiKey() {
310
+ return globalThis.process?.env?.LOGBREW_API_KEY;
311
+ }
312
+
313
+ function readEnvServerApiKey() {
314
+ return globalThis.process?.env?.LOGBREW_SERVER_API_KEY;
315
+ }
316
+
317
+ module.exports = {
318
+ createLogBrewNextClient,
319
+ createRouteErrorEvent,
320
+ createRouteRequestEvent,
321
+ withLogBrewRouteHandler
322
+ };
package/index.d.cts ADDED
@@ -0,0 +1,144 @@
1
+ import type {
2
+ IssueAttributes,
3
+ LogAttributes,
4
+ LogBrewClient,
5
+ SpanAttributes,
6
+ Transport,
7
+ TransportResponse
8
+ } from "@logbrew/sdk";
9
+
10
+ export type CreateLogBrewNextClientConfig = {
11
+ apiKey?: string;
12
+ serverApiKey?: string;
13
+ sdkName?: string;
14
+ sdkVersion?: string;
15
+ maxRetries?: number;
16
+ };
17
+
18
+ export type LogBrewRouteContext = Record<string, unknown>;
19
+
20
+ export type LogBrewRouteHelpers = {
21
+ client: LogBrewClient;
22
+ logbrew: LogBrewClient;
23
+ previewJson(): string;
24
+ flush(): Promise<TransportResponse>;
25
+ shutdown(): Promise<TransportResponse>;
26
+ };
27
+
28
+ export type LogBrewRouteHandler<TContext = LogBrewRouteContext> = (
29
+ request: Request,
30
+ context: TContext,
31
+ helpers: LogBrewRouteHelpers
32
+ ) => Response | Promise<Response>;
33
+
34
+ export type LogBrewRouteRuntimeContext<TContext = LogBrewRouteContext> = {
35
+ request: Request;
36
+ context: TContext;
37
+ client: LogBrewClient;
38
+ };
39
+
40
+ export type LogBrewRouteRequestRuntimeContext<TContext = LogBrewRouteContext> =
41
+ LogBrewRouteRuntimeContext<TContext> & {
42
+ response: Response;
43
+ durationMs: number;
44
+ };
45
+
46
+ export type LogBrewClientFactory<TContext = LogBrewRouteContext> = (
47
+ context: Omit<LogBrewRouteRuntimeContext<TContext>, "client">
48
+ ) => LogBrewClient;
49
+
50
+ export type LogBrewTransportFactory<TContext = LogBrewRouteContext> = (
51
+ context: LogBrewRouteRuntimeContext<TContext>
52
+ ) => Transport;
53
+
54
+ export type LogBrewRouteErrorEvent = {
55
+ id: string;
56
+ timestamp: string;
57
+ attributes: IssueAttributes;
58
+ };
59
+
60
+ export type LogBrewRouteLogRequestEvent = {
61
+ id: string;
62
+ timestamp: string;
63
+ type?: "log";
64
+ attributes: LogAttributes;
65
+ };
66
+
67
+ export type LogBrewRouteSpanRequestEvent = {
68
+ id: string;
69
+ timestamp: string;
70
+ type: "span";
71
+ attributes: SpanAttributes;
72
+ };
73
+
74
+ export type LogBrewRouteRequestEvent =
75
+ LogBrewRouteLogRequestEvent | LogBrewRouteSpanRequestEvent;
76
+
77
+ export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewNextClientConfig & {
78
+ client?: LogBrewClient | LogBrewClientFactory<TContext>;
79
+ transport?: Transport | LogBrewTransportFactory<TContext>;
80
+ captureRequests?: boolean;
81
+ captureErrors?: boolean;
82
+ includeSearchParams?: boolean;
83
+ now?: () => string;
84
+ nowMs?: () => number;
85
+ idFactory?: (request: Request) => string;
86
+ requestIdFactory?: (request: Request, response: Response) => string;
87
+ spanIdFactory?: (request: Request, response: Response) => string;
88
+ requestEvent?: (
89
+ request: Request,
90
+ response: Response,
91
+ context: LogBrewRouteRequestRuntimeContext<TContext>
92
+ ) => LogBrewRouteRequestEvent;
93
+ errorEvent?: (
94
+ error: unknown,
95
+ context: LogBrewRouteRuntimeContext<TContext>
96
+ ) => LogBrewRouteErrorEvent;
97
+ onFlush?: (
98
+ response: TransportResponse,
99
+ context: LogBrewRouteRuntimeContext<TContext>
100
+ ) => void | Promise<void>;
101
+ onCaptureError?: (
102
+ error: unknown,
103
+ context: LogBrewRouteRuntimeContext<TContext>
104
+ ) => void | Promise<void>;
105
+ };
106
+
107
+ export declare function createLogBrewNextClient(
108
+ config?: CreateLogBrewNextClientConfig
109
+ ): LogBrewClient;
110
+
111
+ export declare function withLogBrewRouteHandler<TContext = LogBrewRouteContext>(
112
+ handler: LogBrewRouteHandler<TContext>,
113
+ options?: LogBrewRouteOptions<TContext>
114
+ ): (request: Request, context?: TContext) => Promise<Response>;
115
+
116
+ export declare function createRouteRequestEvent(
117
+ request: Request,
118
+ response: Response,
119
+ options?: {
120
+ now?: () => string;
121
+ durationMs?: number;
122
+ idFactory?: (request: Request, response: Response) => string;
123
+ spanIdFactory?: (request: Request, response: Response) => string;
124
+ }
125
+ ): LogBrewRouteRequestEvent;
126
+
127
+ export declare function createRouteErrorEvent(
128
+ error: unknown,
129
+ request: Request,
130
+ options?: {
131
+ includeSearchParams?: boolean;
132
+ now?: () => string;
133
+ idFactory?: (request: Request) => string;
134
+ }
135
+ ): LogBrewRouteErrorEvent;
136
+
137
+ declare const defaultExport: {
138
+ createLogBrewNextClient: typeof createLogBrewNextClient;
139
+ createRouteErrorEvent: typeof createRouteErrorEvent;
140
+ createRouteRequestEvent: typeof createRouteRequestEvent;
141
+ withLogBrewRouteHandler: typeof withLogBrewRouteHandler;
142
+ };
143
+
144
+ export default defaultExport;
package/index.d.ts ADDED
@@ -0,0 +1,144 @@
1
+ import type {
2
+ IssueAttributes,
3
+ LogAttributes,
4
+ LogBrewClient,
5
+ SpanAttributes,
6
+ Transport,
7
+ TransportResponse
8
+ } from "@logbrew/sdk";
9
+
10
+ export type CreateLogBrewNextClientConfig = {
11
+ apiKey?: string;
12
+ serverApiKey?: string;
13
+ sdkName?: string;
14
+ sdkVersion?: string;
15
+ maxRetries?: number;
16
+ };
17
+
18
+ export type LogBrewRouteContext = Record<string, unknown>;
19
+
20
+ export type LogBrewRouteHelpers = {
21
+ client: LogBrewClient;
22
+ logbrew: LogBrewClient;
23
+ previewJson(): string;
24
+ flush(): Promise<TransportResponse>;
25
+ shutdown(): Promise<TransportResponse>;
26
+ };
27
+
28
+ export type LogBrewRouteHandler<TContext = LogBrewRouteContext> = (
29
+ request: Request,
30
+ context: TContext,
31
+ helpers: LogBrewRouteHelpers
32
+ ) => Response | Promise<Response>;
33
+
34
+ export type LogBrewRouteRuntimeContext<TContext = LogBrewRouteContext> = {
35
+ request: Request;
36
+ context: TContext;
37
+ client: LogBrewClient;
38
+ };
39
+
40
+ export type LogBrewRouteRequestRuntimeContext<TContext = LogBrewRouteContext> =
41
+ LogBrewRouteRuntimeContext<TContext> & {
42
+ response: Response;
43
+ durationMs: number;
44
+ };
45
+
46
+ export type LogBrewClientFactory<TContext = LogBrewRouteContext> = (
47
+ context: Omit<LogBrewRouteRuntimeContext<TContext>, "client">
48
+ ) => LogBrewClient;
49
+
50
+ export type LogBrewTransportFactory<TContext = LogBrewRouteContext> = (
51
+ context: LogBrewRouteRuntimeContext<TContext>
52
+ ) => Transport;
53
+
54
+ export type LogBrewRouteErrorEvent = {
55
+ id: string;
56
+ timestamp: string;
57
+ attributes: IssueAttributes;
58
+ };
59
+
60
+ export type LogBrewRouteLogRequestEvent = {
61
+ id: string;
62
+ timestamp: string;
63
+ type?: "log";
64
+ attributes: LogAttributes;
65
+ };
66
+
67
+ export type LogBrewRouteSpanRequestEvent = {
68
+ id: string;
69
+ timestamp: string;
70
+ type: "span";
71
+ attributes: SpanAttributes;
72
+ };
73
+
74
+ export type LogBrewRouteRequestEvent =
75
+ LogBrewRouteLogRequestEvent | LogBrewRouteSpanRequestEvent;
76
+
77
+ export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewNextClientConfig & {
78
+ client?: LogBrewClient | LogBrewClientFactory<TContext>;
79
+ transport?: Transport | LogBrewTransportFactory<TContext>;
80
+ captureRequests?: boolean;
81
+ captureErrors?: boolean;
82
+ includeSearchParams?: boolean;
83
+ now?: () => string;
84
+ nowMs?: () => number;
85
+ idFactory?: (request: Request) => string;
86
+ requestIdFactory?: (request: Request, response: Response) => string;
87
+ spanIdFactory?: (request: Request, response: Response) => string;
88
+ requestEvent?: (
89
+ request: Request,
90
+ response: Response,
91
+ context: LogBrewRouteRequestRuntimeContext<TContext>
92
+ ) => LogBrewRouteRequestEvent;
93
+ errorEvent?: (
94
+ error: unknown,
95
+ context: LogBrewRouteRuntimeContext<TContext>
96
+ ) => LogBrewRouteErrorEvent;
97
+ onFlush?: (
98
+ response: TransportResponse,
99
+ context: LogBrewRouteRuntimeContext<TContext>
100
+ ) => void | Promise<void>;
101
+ onCaptureError?: (
102
+ error: unknown,
103
+ context: LogBrewRouteRuntimeContext<TContext>
104
+ ) => void | Promise<void>;
105
+ };
106
+
107
+ export declare function createLogBrewNextClient(
108
+ config?: CreateLogBrewNextClientConfig
109
+ ): LogBrewClient;
110
+
111
+ export declare function withLogBrewRouteHandler<TContext = LogBrewRouteContext>(
112
+ handler: LogBrewRouteHandler<TContext>,
113
+ options?: LogBrewRouteOptions<TContext>
114
+ ): (request: Request, context?: TContext) => Promise<Response>;
115
+
116
+ export declare function createRouteRequestEvent(
117
+ request: Request,
118
+ response: Response,
119
+ options?: {
120
+ now?: () => string;
121
+ durationMs?: number;
122
+ idFactory?: (request: Request, response: Response) => string;
123
+ spanIdFactory?: (request: Request, response: Response) => string;
124
+ }
125
+ ): LogBrewRouteRequestEvent;
126
+
127
+ export declare function createRouteErrorEvent(
128
+ error: unknown,
129
+ request: Request,
130
+ options?: {
131
+ includeSearchParams?: boolean;
132
+ now?: () => string;
133
+ idFactory?: (request: Request) => string;
134
+ }
135
+ ): LogBrewRouteErrorEvent;
136
+
137
+ declare const defaultExport: {
138
+ createLogBrewNextClient: typeof createLogBrewNextClient;
139
+ createRouteErrorEvent: typeof createRouteErrorEvent;
140
+ createRouteRequestEvent: typeof createRouteRequestEvent;
141
+ withLogBrewRouteHandler: typeof withLogBrewRouteHandler;
142
+ };
143
+
144
+ export default defaultExport;
package/index.js ADDED
@@ -0,0 +1,322 @@
1
+ import {
2
+ LogBrewClient,
3
+ RecordingTransport,
4
+ SdkError,
5
+ parseTraceparent,
6
+ spanAttributesFromTraceparent
7
+ } from "@logbrew/sdk";
8
+
9
+ const DEFAULT_SDK_NAME = "logbrew-next";
10
+ const DEFAULT_SDK_VERSION = "0.1.0";
11
+
12
+ export function createLogBrewNextClient({
13
+ apiKey,
14
+ serverApiKey,
15
+ sdkName = DEFAULT_SDK_NAME,
16
+ sdkVersion = DEFAULT_SDK_VERSION,
17
+ maxRetries = 2
18
+ } = {}) {
19
+ const authKey = serverApiKey ?? apiKey ?? readEnvServerApiKey() ?? readEnvApiKey();
20
+ if (!authKey) {
21
+ throw new SdkError(
22
+ "configuration_error",
23
+ "createLogBrewNextClient requires serverApiKey, apiKey, LOGBREW_SERVER_API_KEY, or LOGBREW_API_KEY"
24
+ );
25
+ }
26
+ return LogBrewClient.create({ apiKey: authKey, sdkName, sdkVersion, maxRetries });
27
+ }
28
+
29
+ export function withLogBrewRouteHandler(handler, options = {}) {
30
+ if (typeof handler !== "function") {
31
+ throw new SdkError("configuration_error", "withLogBrewRouteHandler requires a handler function");
32
+ }
33
+
34
+ return async function logBrewRouteHandler(request, context = {}) {
35
+ const client = resolveClient(options, request, context);
36
+ const transport = resolveTransport(options, request, context, client);
37
+ const helpers = createRouteHelpers(client, transport);
38
+ const startedAt = nowMs(options);
39
+
40
+ try {
41
+ const response = await handler(request, context, helpers);
42
+ ensureResponse(response);
43
+ await captureRouteSuccess(options, { request, response, context, client, transport, startedAt });
44
+ return response;
45
+ } catch (error) {
46
+ await recordRouteError(options, error, { request, context, client, transport });
47
+ throw error;
48
+ }
49
+ };
50
+ }
51
+
52
+ export function createRouteRequestEvent(request, response, {
53
+ now = () => new Date().toISOString(),
54
+ durationMs = 0,
55
+ idFactory = defaultRouteRequestId,
56
+ spanIdFactory = defaultSpanIdFactory
57
+ } = {}) {
58
+ const url = safeUrl(request);
59
+ const method = request?.method ?? "GET";
60
+ const statusCode = Number(response?.status ?? 0);
61
+ const id = idFactory(request, response);
62
+ const traceparent = getTraceparentHeader(request);
63
+ const spanEvent = traceparent
64
+ ? createTraceparentRouteSpan(traceparent, {
65
+ durationMs,
66
+ id,
67
+ method,
68
+ now,
69
+ pathname: url.pathname,
70
+ spanIdFactory: () => spanIdFactory(request, response),
71
+ statusCode
72
+ })
73
+ : undefined;
74
+ if (spanEvent) {
75
+ return spanEvent;
76
+ }
77
+
78
+ return {
79
+ id,
80
+ timestamp: now(),
81
+ attributes: {
82
+ message: `${method} ${url.pathname} ${statusCode}`,
83
+ level: statusCode >= 500 ? "error" : "info",
84
+ logger: "next",
85
+ metadata: {
86
+ framework: "nextjs",
87
+ method,
88
+ pathname: url.pathname,
89
+ statusCode,
90
+ durationMs
91
+ }
92
+ }
93
+ };
94
+ }
95
+
96
+ export function createRouteErrorEvent(error, request, {
97
+ includeSearchParams = false,
98
+ now = () => new Date().toISOString(),
99
+ idFactory = defaultRouteErrorId
100
+ } = {}) {
101
+ const url = safeUrl(request);
102
+ const method = request?.method ?? "GET";
103
+ const message = error instanceof Error ? error.message : String(error);
104
+ return {
105
+ id: idFactory(request),
106
+ timestamp: now(),
107
+ attributes: {
108
+ title: `${method} ${url.pathname} failed`,
109
+ level: "error",
110
+ message,
111
+ metadata: {
112
+ method,
113
+ pathname: url.pathname,
114
+ ...(includeSearchParams ? { search: url.search || null } : {})
115
+ }
116
+ }
117
+ };
118
+ }
119
+
120
+ function resolveClient(options, request, context) {
121
+ if (typeof options.client === "function") {
122
+ return options.client({ request, context });
123
+ }
124
+ if (options.client) {
125
+ return options.client;
126
+ }
127
+ return createLogBrewNextClient(options);
128
+ }
129
+
130
+ function resolveTransport(options, request, context, client) {
131
+ if (typeof options.transport === "function") {
132
+ return options.transport({ request, context, client });
133
+ }
134
+ return options.transport ?? RecordingTransport.alwaysAccept();
135
+ }
136
+
137
+ function createRouteHelpers(client, transport) {
138
+ return {
139
+ client,
140
+ logbrew: client,
141
+ previewJson: () => client.previewJson(),
142
+ flush: () => client.flush(transport),
143
+ shutdown: () => client.shutdown(transport)
144
+ };
145
+ }
146
+
147
+ function ensureResponse(response) {
148
+ if (!(response instanceof Response)) {
149
+ throw new SdkError("route_handler_error", "Next.js route handler must return a Response");
150
+ }
151
+ }
152
+
153
+ async function notifyFlush(options, flushResponse, context) {
154
+ if (typeof options.onFlush === "function") {
155
+ await options.onFlush(flushResponse, context);
156
+ }
157
+ }
158
+
159
+ async function notifyFailure(options, error, context) {
160
+ if (typeof options.onCaptureError === "function") {
161
+ await options.onCaptureError(error, context);
162
+ }
163
+ }
164
+
165
+ async function captureRouteSuccess(options, { request, response, context, client, transport, startedAt }) {
166
+ try {
167
+ if (options.captureRequests !== false) {
168
+ recordRouteRequest(options, { request, response, context, client, startedAt });
169
+ }
170
+ const flushResponse = await client.shutdown(transport);
171
+ await notifyFlush(options, flushResponse, { request, context, client });
172
+ } catch (error) {
173
+ await notifyFailure(options, error, { request, context, client });
174
+ }
175
+ }
176
+
177
+ function recordRouteRequest(options, { request, response, context, client, startedAt }) {
178
+ const durationMs = Math.max(0, Math.round(nowMs(options) - startedAt));
179
+ const event = typeof options.requestEvent === "function"
180
+ ? options.requestEvent(request, response, { client, context, durationMs, request, response })
181
+ : createRouteRequestEvent(request, response, {
182
+ ...options,
183
+ durationMs,
184
+ idFactory: options.requestIdFactory
185
+ });
186
+ captureRouteRequestEvent(client, event);
187
+ }
188
+
189
+ async function recordRouteError(options, error, { request, context, client, transport }) {
190
+ if (options.captureErrors === false) {
191
+ return;
192
+ }
193
+ const event = typeof options.errorEvent === "function"
194
+ ? options.errorEvent(error, { request, context, client })
195
+ : createRouteErrorEvent(error, request, options);
196
+ try {
197
+ client.issue(event.id, event.timestamp, event.attributes);
198
+ const flushResponse = await client.shutdown(transport);
199
+ await notifyFlush(options, flushResponse, { request, context, client });
200
+ } catch (captureError) {
201
+ await notifyFailure(options, captureError, { request, context, client });
202
+ }
203
+ }
204
+
205
+ function captureRouteRequestEvent(client, event) {
206
+ if (event.type === "span") {
207
+ client.span(event.id, event.timestamp, event.attributes);
208
+ return;
209
+ }
210
+ client.log(event.id, event.timestamp, event.attributes);
211
+ }
212
+
213
+ function defaultRouteRequestId(request, response) {
214
+ const url = safeUrl(request);
215
+ const slug = `${request?.method ?? "GET"}-${url.pathname}-${response?.status ?? 0}`
216
+ .toLowerCase()
217
+ .replace(/[^a-z0-9]+/g, "_")
218
+ .replace(/^_+|_+$/g, "");
219
+ return `evt_next_request_${slug || "route"}`;
220
+ }
221
+
222
+ function defaultSpanIdFactory() {
223
+ return randomHex(8);
224
+ }
225
+
226
+ function defaultRouteErrorId(request) {
227
+ const url = safeUrl(request);
228
+ const slug = `${request?.method ?? "GET"}-${url.pathname}`
229
+ .toLowerCase()
230
+ .replace(/[^a-z0-9]+/g, "_")
231
+ .replace(/^_+|_+$/g, "");
232
+ return `evt_next_error_${slug || "route"}`;
233
+ }
234
+
235
+ function safeUrl(request) {
236
+ try {
237
+ return new URL(request?.url ?? "http://localhost/");
238
+ } catch {
239
+ return new URL("http://localhost/");
240
+ }
241
+ }
242
+
243
+ function getTraceparentHeader(request) {
244
+ if (!request?.headers || typeof request.headers.get !== "function") {
245
+ return undefined;
246
+ }
247
+ const value = request.headers.get("traceparent");
248
+ return typeof value === "string" ? value : undefined;
249
+ }
250
+
251
+ function createTraceparentRouteSpan(traceparent, {
252
+ durationMs,
253
+ id,
254
+ method,
255
+ now,
256
+ pathname,
257
+ spanIdFactory,
258
+ statusCode
259
+ }) {
260
+ if (!traceparent) {
261
+ return undefined;
262
+ }
263
+
264
+ try {
265
+ parseTraceparent(traceparent);
266
+ const spanId = spanIdFactory();
267
+ return {
268
+ id,
269
+ timestamp: now(),
270
+ type: "span",
271
+ attributes: spanAttributesFromTraceparent(traceparent, {
272
+ durationMs,
273
+ metadata: {
274
+ framework: "nextjs",
275
+ method,
276
+ pathname,
277
+ statusCode
278
+ },
279
+ name: `${method} ${pathname}`,
280
+ spanId,
281
+ status: statusCode >= 500 ? "error" : "ok"
282
+ })
283
+ };
284
+ } catch {
285
+ return undefined;
286
+ }
287
+ }
288
+
289
+ function nowMs(options) {
290
+ if (typeof options.nowMs === "function") {
291
+ return options.nowMs();
292
+ }
293
+ return performance.now();
294
+ }
295
+
296
+ function randomHex(byteLength) {
297
+ const bytes = new Uint8Array(byteLength);
298
+ if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
299
+ globalThis.crypto.getRandomValues(bytes);
300
+ } else {
301
+ for (let index = 0; index < bytes.length; index += 1) {
302
+ bytes[index] = Math.floor(Math.random() * 256);
303
+ }
304
+ }
305
+ const value = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
306
+ return /^0+$/.test(value) ? "0000000000000001" : value;
307
+ }
308
+
309
+ function readEnvApiKey() {
310
+ return globalThis.process?.env?.LOGBREW_API_KEY;
311
+ }
312
+
313
+ function readEnvServerApiKey() {
314
+ return globalThis.process?.env?.LOGBREW_SERVER_API_KEY;
315
+ }
316
+
317
+ export default {
318
+ createLogBrewNextClient,
319
+ createRouteErrorEvent,
320
+ createRouteRequestEvent,
321
+ withLogBrewRouteHandler
322
+ };
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@logbrew/next",
3
+ "version": "0.1.0",
4
+ "description": "Next.js App Router helpers for the public LogBrew JavaScript SDK.",
5
+ "type": "module",
6
+ "main": "./index.cjs",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./index.d.ts",
12
+ "default": "./index.js"
13
+ },
14
+ "require": {
15
+ "types": "./index.d.cts",
16
+ "default": "./index.cjs"
17
+ },
18
+ "default": "./index.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "index.cjs",
23
+ "index.js",
24
+ "index.d.ts",
25
+ "index.d.cts",
26
+ "README.md",
27
+ "examples"
28
+ ],
29
+ "keywords": [
30
+ "logbrew",
31
+ "nextjs",
32
+ "next",
33
+ "observability",
34
+ "logs",
35
+ "traces",
36
+ "events"
37
+ ],
38
+ "sideEffects": false,
39
+ "engines": {
40
+ "node": ">=18"
41
+ },
42
+ "license": "MIT",
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/LogBrewCo/sdk.git"
46
+ },
47
+ "peerDependencies": {
48
+ "@logbrew/sdk": "^0.1.0",
49
+ "next": ">=15",
50
+ "react": ">=18",
51
+ "react-dom": ">=18"
52
+ },
53
+ "scripts": {
54
+ "test": "node --check index.js && node --check index.cjs && node --check examples/index.mjs && node --check examples/readme-example.mjs && node --check examples/real-user-smoke.mjs"
55
+ }
56
+ }