@orpc/pino 2.0.0-beta.49 → 2.0.0-beta.50

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/dist/context.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Logger } from 'pino';
1
+ import { Logger } from "pino";
2
2
  /**
3
3
  * Context symbol under which the Pino logger is stored. Use it to provide a
4
4
  * custom logger instance per request, e.g. when integrating with pino-http.
@@ -12,11 +12,11 @@ export declare const LOGGER_CONTEXT_SYMBOL: unique symbol;
12
12
  * @see {@link https://orpc.dev/docs/integrations/pino#using-the-logger-in-your-code | Pino Integration - Using the Logger in Your Code}
13
13
  */
14
14
  export interface LoggerContext {
15
- [LOGGER_CONTEXT_SYMBOL]?: Logger | undefined;
15
+ [LOGGER_CONTEXT_SYMBOL]?: Logger | undefined;
16
16
  }
17
17
  /**
18
18
  * Retrieves the Pino logger from the oRPC context, if available.
19
19
  *
20
20
  * @see {@link https://orpc.dev/docs/integrations/pino#using-the-logger-in-your-code | Pino Integration - Using the Logger in Your Code}
21
21
  */
22
- export declare function getLogger(context: LoggerContext): Logger | undefined;
22
+ export declare function getLogger(context: LoggerContext): Logger | undefined;
package/dist/context.js CHANGED
@@ -1,15 +1,17 @@
1
+ // src/context.ts
1
2
  /**
2
- * Context symbol under which the Pino logger is stored. Use it to provide a
3
- * custom logger instance per request, e.g. when integrating with pino-http.
4
- *
5
- * @see {@link https://orpc.dev/docs/integrations/pino#providing-custom-logger-per-request | Pino Integration - Providing Custom Logger per Request}
6
- */
7
- export const LOGGER_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for('ORPC_PINO_LOGGER_CONTEXT');
3
+ * Context symbol under which the Pino logger is stored. Use it to provide a
4
+ * custom logger instance per request, e.g. when integrating with pino-http.
5
+ *
6
+ * @see {@link https://orpc.dev/docs/integrations/pino#providing-custom-logger-per-request | Pino Integration - Providing Custom Logger per Request}
7
+ */
8
+ const LOGGER_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("ORPC_PINO_LOGGER_CONTEXT");
8
9
  /**
9
- * Retrieves the Pino logger from the oRPC context, if available.
10
- *
11
- * @see {@link https://orpc.dev/docs/integrations/pino#using-the-logger-in-your-code | Pino Integration - Using the Logger in Your Code}
12
- */
13
- export function getLogger(context) {
14
- return context[LOGGER_CONTEXT_SYMBOL];
10
+ * Retrieves the Pino logger from the oRPC context, if available.
11
+ *
12
+ * @see {@link https://orpc.dev/docs/integrations/pino#using-the-logger-in-your-code | Pino Integration - Using the Logger in Your Code}
13
+ */
14
+ function getLogger(context) {
15
+ return context[LOGGER_CONTEXT_SYMBOL];
15
16
  }
17
+ export { LOGGER_CONTEXT_SYMBOL, getLogger };
@@ -1,42 +1,41 @@
1
- import type { Context } from '@orpc/server';
2
- import type { StandardHandlerOptions, StandardHandlerPlugin, StandardHandlerRoutingInterceptorOptions } from '@orpc/server/standard';
3
- import type { Logger } from 'pino';
4
- import pino from 'pino';
1
+ import pino, { Logger } from "pino";
2
+ import { Context } from "@orpc/server";
3
+ import { StandardHandlerOptions, StandardHandlerPlugin, StandardHandlerRoutingInterceptorOptions } from "@orpc/server/standard";
5
4
  export interface PinoHandlerPluginOptions<T extends Context> {
6
- /**
7
- * Logger instance to use for logging.
8
- *
9
- * @default pino()
10
- */
11
- logger?: Logger | undefined;
12
- /**
13
- * Function to generate a unique ID for each request.
14
- *
15
- * @default ({ request }) => flattenStandardHeader(request.headers['x-request-id']) ?? crypto.randomUUID()
16
- */
17
- generateRequestId?: ((options: StandardHandlerRoutingInterceptorOptions<T>) => string) | undefined;
18
- /**
19
- * If true, this plugin will log information about request lifecycle,
20
- * including when a request is received, handled, or no matching procedure is found.
21
- *
22
- * @default false
23
- */
24
- logLifecycle?: boolean | undefined;
25
- /**
26
- * If true, this plugin will log when a request signal is aborted.
27
- *
28
- * @default false
29
- */
30
- logAbort?: boolean | undefined;
31
- /**
32
- * Customizes the log level for errors thrown from procedures;
33
- * internal handler failures are always logged at error level.
34
- * Receives the level applied by default; return it to keep the default behavior:
35
- * 'info' for abort errors, 'warn' for ORPCError except INTERNAL_SERVER_ERROR, 'error' otherwise.
36
- *
37
- * @default (error, level) => level
38
- */
39
- procedureErrorLevel?: ((error: unknown, level: pino.Level) => pino.Level) | undefined;
5
+ /**
6
+ * Logger instance to use for logging.
7
+ *
8
+ * @default pino()
9
+ */
10
+ logger?: Logger | undefined;
11
+ /**
12
+ * Function to generate a unique ID for each request.
13
+ *
14
+ * @default ({ request }) => flattenStandardHeader(request.headers['x-request-id']) ?? crypto.randomUUID()
15
+ */
16
+ generateRequestId?: ((options: StandardHandlerRoutingInterceptorOptions<T>) => string) | undefined;
17
+ /**
18
+ * If true, this plugin will log information about request lifecycle,
19
+ * including when a request is received, handled, or no matching procedure is found.
20
+ *
21
+ * @default false
22
+ */
23
+ logLifecycle?: boolean | undefined;
24
+ /**
25
+ * If true, this plugin will log when a request signal is aborted.
26
+ *
27
+ * @default false
28
+ */
29
+ logAbort?: boolean | undefined;
30
+ /**
31
+ * Customizes the log level for errors thrown from procedures;
32
+ * internal handler failures are always logged at error level.
33
+ * Receives the level applied by default; return it to keep the default behavior:
34
+ * 'info' for abort errors, 'warn' for ORPCError except INTERNAL_SERVER_ERROR, 'error' otherwise.
35
+ *
36
+ * @default (error, level) => level
37
+ */
38
+ procedureErrorLevel?: ((error: unknown, level: pino.Level) => pino.Level) | undefined;
40
39
  }
41
40
  /**
42
41
  * Instruments an oRPC handler with Pino structured logging, request tracking,
@@ -45,19 +44,19 @@ export interface PinoHandlerPluginOptions<T extends Context> {
45
44
  * @see {@link https://orpc.dev/docs/integrations/pino | Pino Integration}
46
45
  */
47
46
  export declare class PinoHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
48
- name: string;
49
- /**
50
- * - Logging interceptors should run after tracing interceptors
51
- * so they execute within the active request span.
52
- * - Logging interceptors should run after batch interceptors
53
- * so they log each individual request instead of the batch request.
54
- */
55
- before: string[];
56
- private readonly logger;
57
- private readonly generateRequestId;
58
- private readonly logLifecycle;
59
- private readonly logAbort;
60
- private readonly procedureErrorLevel;
61
- constructor(options?: PinoHandlerPluginOptions<T>);
62
- init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
63
- }
47
+ name: string;
48
+ /**
49
+ * - Logging interceptors should run after tracing interceptors
50
+ * so they execute within the active request span.
51
+ * - Logging interceptors should run after batch interceptors
52
+ * so they log each individual request instead of the batch request.
53
+ */
54
+ before: string[];
55
+ private readonly logger;
56
+ private readonly generateRequestId;
57
+ private readonly logLifecycle;
58
+ private readonly logAbort;
59
+ private readonly procedureErrorLevel;
60
+ constructor(options?: PinoHandlerPluginOptions<T>);
61
+ init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
62
+ }
@@ -1,167 +1,139 @@
1
- import { ORPCError, wrapAsyncIteratorPreservingEventMeta } from '@orpc/client';
2
- import { isAbortError, isAsyncIteratorObject, ORPC_NAME, override, toArray, wrapReadableStream, } from '@orpc/shared';
3
- import { flattenStandardHeader } from '@standard-server/core';
4
- import pino from 'pino';
5
- import { getLogger, LOGGER_CONTEXT_SYMBOL } from './context.js';
1
+ import { LOGGER_CONTEXT_SYMBOL, getLogger } from "./context.js";
2
+ import { ORPCError, wrapAsyncIteratorPreservingEventMeta } from "@orpc/client";
3
+ import { ORPC_NAME, isAbortError, isAsyncIteratorObject, override, toArray, wrapReadableStream } from "@orpc/shared";
4
+ import { flattenStandardHeader } from "@standard-server/core";
5
+ import pino from "pino";
6
+ // src/handler-plugin.ts
6
7
  /**
7
- * Instruments an oRPC handler with Pino structured logging, request tracking,
8
- * and error monitoring.
9
- *
10
- * @see {@link https://orpc.dev/docs/integrations/pino | Pino Integration}
11
- */
12
- export class PinoHandlerPlugin {
13
- name = '~pino';
14
- /**
15
- * - Logging interceptors should run after tracing interceptors
16
- * so they execute within the active request span.
17
- * - Logging interceptors should run after batch interceptors
18
- * so they log each individual request instead of the batch request.
19
- */
20
- before = ['~tracing', '~batch', '~hibernation'];
21
- logger;
22
- generateRequestId;
23
- logLifecycle;
24
- logAbort;
25
- procedureErrorLevel;
26
- constructor(options = {}) {
27
- this.logger = options.logger ?? pino();
28
- this.generateRequestId =
29
- options.generateRequestId ??
30
- (({ request }) => flattenStandardHeader(request.headers['x-request-id']) ?? crypto.randomUUID());
31
- this.logLifecycle = options.logLifecycle ?? false;
32
- this.logAbort = options.logAbort ?? false;
33
- this.procedureErrorLevel = options.procedureErrorLevel ?? ((_, level) => level);
34
- }
35
- init(options) {
36
- const routingInterceptor = async ({ next, ...interceptorOptions }) => {
37
- const startMs = Date.now();
38
- const logger = (interceptorOptions.context[LOGGER_CONTEXT_SYMBOL] ?? this.logger).child({});
39
- /**
40
- * pino-http might have already set req info in bindings
41
- */
42
- if (!logger.bindings().req) {
43
- logger.setBindings({
44
- req: {
45
- id: this.generateRequestId(interceptorOptions),
46
- url: interceptorOptions.request.url,
47
- method: interceptorOptions.request.method,
48
- headers: {
49
- 'content-type': interceptorOptions.request.headers['content-type'],
50
- 'content-length': interceptorOptions.request.headers['content-length'],
51
- 'content-disposition': interceptorOptions.request.headers['content-disposition'],
52
- 'standard-server': interceptorOptions.request.headers['standard-server'],
53
- },
54
- },
55
- });
56
- }
57
- try {
58
- if (this.logLifecycle) {
59
- logger?.info('request received');
60
- }
61
- const result = await next({
62
- ...interceptorOptions,
63
- context: {
64
- ...interceptorOptions.context,
65
- [LOGGER_CONTEXT_SYMBOL]: logger,
66
- },
67
- });
68
- if (this.logLifecycle) {
69
- if (result.matched) {
70
- logger?.info({
71
- msg: 'request handled',
72
- res: {
73
- status: result.response.status,
74
- },
75
- responseTime: Date.now() - startMs,
76
- });
77
- }
78
- else {
79
- logger?.info('no matching procedure found');
80
- }
81
- }
82
- return result;
83
- }
84
- catch (error) {
85
- /**
86
- * Any error here is internal (interceptor/framework), not business logic.
87
- * Indicates unexpected handler failure.
88
- */
89
- logger.error(error);
90
- throw error;
91
- }
92
- };
93
- const interceptor = async ({ next, context, path, request }) => {
94
- const logger = getLogger(context);
95
- logger?.setBindings({ rpc: { system: ORPC_NAME, method: path.join('.') } });
96
- if (this.logAbort) {
97
- const signal = request.signal;
98
- if (signal?.aborted) {
99
- logger?.info(`request was aborted before handling (${String(signal.reason)})`);
100
- }
101
- else {
102
- signal?.addEventListener('abort', () => {
103
- logger?.info(`request is aborted (${String(signal.reason)})`);
104
- }, { once: true });
105
- }
106
- }
107
- try {
108
- return await next();
109
- }
110
- catch (error) {
111
- logProcedureError(logger, error, this.procedureErrorLevel);
112
- throw error;
113
- }
114
- };
115
- const clientInterceptor = async ({ next, context, }) => {
116
- const output = await next();
117
- if (isAsyncIteratorObject(output)) {
118
- /**
119
- * @remarks
120
- * **Warning**: Remember use `override` for AsyncIteratorObject to remain other special properties
121
- */
122
- return override(output, wrapAsyncIteratorPreservingEventMeta(output, {
123
- onError: (error) => {
124
- logProcedureError(getLogger(context), error, this.procedureErrorLevel);
125
- },
126
- }));
127
- }
128
- if (output instanceof ReadableStream) {
129
- /**
130
- * @remarks
131
- * **Warning**: Remember use `override` for ReadableStream to remain other special properties
132
- */
133
- return override(output, wrapReadableStream(output, {
134
- onError: (error) => {
135
- logProcedureError(getLogger(context), error, this.procedureErrorLevel);
136
- },
137
- }));
138
- }
139
- return output;
140
- };
141
- return {
142
- ...options,
143
- routingInterceptors: [routingInterceptor, ...toArray(options.routingInterceptors)],
144
- interceptors: [interceptor, ...toArray(options.interceptors)],
145
- clientInterceptors: [clientInterceptor, ...toArray(options.clientInterceptors)],
146
- };
147
- }
148
- }
8
+ * Instruments an oRPC handler with Pino structured logging, request tracking,
9
+ * and error monitoring.
10
+ *
11
+ * @see {@link https://orpc.dev/docs/integrations/pino | Pino Integration}
12
+ */
13
+ var PinoHandlerPlugin = class {
14
+ name = "~pino";
15
+ /**
16
+ * - Logging interceptors should run after tracing interceptors
17
+ * so they execute within the active request span.
18
+ * - Logging interceptors should run after batch interceptors
19
+ * so they log each individual request instead of the batch request.
20
+ */
21
+ before = [
22
+ "~tracing",
23
+ "~batch",
24
+ "~hibernation"
25
+ ];
26
+ logger;
27
+ generateRequestId;
28
+ logLifecycle;
29
+ logAbort;
30
+ procedureErrorLevel;
31
+ constructor(options = {}) {
32
+ this.logger = options.logger ?? pino();
33
+ this.generateRequestId = options.generateRequestId ?? (({ request }) => flattenStandardHeader(request.headers["x-request-id"]) ?? crypto.randomUUID());
34
+ this.logLifecycle = options.logLifecycle ?? false;
35
+ this.logAbort = options.logAbort ?? false;
36
+ this.procedureErrorLevel = options.procedureErrorLevel ?? ((_, level) => level);
37
+ }
38
+ init(options) {
39
+ const routingInterceptor = async ({ next, ...interceptorOptions }) => {
40
+ const startMs = Date.now();
41
+ const logger = (interceptorOptions.context[LOGGER_CONTEXT_SYMBOL] ?? this.logger).child({});
42
+ /**
43
+ * pino-http might have already set req info in bindings
44
+ */
45
+ if (!logger.bindings().req) logger.setBindings({ req: {
46
+ id: this.generateRequestId(interceptorOptions),
47
+ url: interceptorOptions.request.url,
48
+ method: interceptorOptions.request.method,
49
+ headers: {
50
+ "content-type": interceptorOptions.request.headers["content-type"],
51
+ "content-length": interceptorOptions.request.headers["content-length"],
52
+ "content-disposition": interceptorOptions.request.headers["content-disposition"],
53
+ "standard-server": interceptorOptions.request.headers["standard-server"]
54
+ }
55
+ } });
56
+ try {
57
+ if (this.logLifecycle) logger?.info("request received");
58
+ const result = await next({
59
+ ...interceptorOptions,
60
+ context: {
61
+ ...interceptorOptions.context,
62
+ [LOGGER_CONTEXT_SYMBOL]: logger
63
+ }
64
+ });
65
+ if (this.logLifecycle) {
66
+ if (result.matched) logger?.info({
67
+ msg: "request handled",
68
+ res: { status: result.response.status },
69
+ responseTime: Date.now() - startMs
70
+ });
71
+ else logger?.info("no matching procedure found");
72
+ }
73
+ return result;
74
+ } catch (error) {
75
+ /**
76
+ * Any error here is internal (interceptor/framework), not business logic.
77
+ * Indicates unexpected handler failure.
78
+ */
79
+ logger.error(error);
80
+ throw error;
81
+ }
82
+ };
83
+ const interceptor = async ({ next, context, path, request }) => {
84
+ const logger = getLogger(context);
85
+ logger?.setBindings({ rpc: {
86
+ system: ORPC_NAME,
87
+ method: path.join(".")
88
+ } });
89
+ if (this.logAbort) {
90
+ const signal = request.signal;
91
+ if (signal?.aborted) logger?.info(`request was aborted before handling (${String(signal.reason)})`);
92
+ else signal?.addEventListener("abort", () => {
93
+ logger?.info(`request is aborted (${String(signal.reason)})`);
94
+ }, { once: true });
95
+ }
96
+ try {
97
+ return await next();
98
+ } catch (error) {
99
+ logProcedureError(logger, error, this.procedureErrorLevel);
100
+ throw error;
101
+ }
102
+ };
103
+ const clientInterceptor = async ({ next, context }) => {
104
+ const output = await next();
105
+ if (isAsyncIteratorObject(output))
106
+ /**
107
+ * @remarks
108
+ * **Warning**: Remember use `override` for AsyncIteratorObject to remain other special properties
109
+ */
110
+ return override(output, wrapAsyncIteratorPreservingEventMeta(output, { onError: (error) => {
111
+ logProcedureError(getLogger(context), error, this.procedureErrorLevel);
112
+ } }));
113
+ if (output instanceof ReadableStream)
114
+ /**
115
+ * @remarks
116
+ * **Warning**: Remember use `override` for ReadableStream to remain other special properties
117
+ */
118
+ return override(output, wrapReadableStream(output, { onError: (error) => {
119
+ logProcedureError(getLogger(context), error, this.procedureErrorLevel);
120
+ } }));
121
+ return output;
122
+ };
123
+ return {
124
+ ...options,
125
+ routingInterceptors: [routingInterceptor, ...toArray(options.routingInterceptors)],
126
+ interceptors: [interceptor, ...toArray(options.interceptors)],
127
+ clientInterceptors: [clientInterceptor, ...toArray(options.clientInterceptors)]
128
+ };
129
+ }
130
+ };
149
131
  function logProcedureError(logger, error, procedureErrorLevel) {
150
- logger?.[procedureErrorLevel(error, defaultProcedureErrorLevel(error))](error);
132
+ logger?.[procedureErrorLevel(error, defaultProcedureErrorLevel(error))](error);
151
133
  }
152
134
  function defaultProcedureErrorLevel(error) {
153
- // An abort means the client withdrew the request, not that something failed,
154
- // so record it as normal operation.
155
- if (isAbortError(error)) {
156
- return 'info';
157
- }
158
- // A thrown ORPCError is a deliberate business rejection delivered to the client,
159
- // so keep it reviewable without treating it as a failure. INTERNAL_SERVER_ERROR
160
- // is the exception: it signals a server-side failure (oRPC itself throws it for
161
- // failures like output validation), so it stays at error level along with
162
- // anything unexpected.
163
- if (error instanceof ORPCError && error.code !== 'INTERNAL_SERVER_ERROR') {
164
- return 'warn';
165
- }
166
- return 'error';
135
+ if (isAbortError(error)) return "info";
136
+ if (error instanceof ORPCError && error.code !== "INTERNAL_SERVER_ERROR") return "warn";
137
+ return "error";
167
138
  }
139
+ export { PinoHandlerPlugin };
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- export * from './context.ts';
2
- export * from './handler-plugin.ts';
1
+ import { LOGGER_CONTEXT_SYMBOL, LoggerContext, getLogger } from "./context.js";
2
+ import { PinoHandlerPlugin, PinoHandlerPluginOptions } from "./handler-plugin.js";
3
+ export { LOGGER_CONTEXT_SYMBOL, LoggerContext, PinoHandlerPlugin, PinoHandlerPluginOptions, getLogger };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export * from './context.js';
2
- export * from './handler-plugin.js';
1
+ export { LOGGER_CONTEXT_SYMBOL, getLogger } from "./context.js";
2
+ export { PinoHandlerPlugin } from "./handler-plugin.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orpc/pino",
3
- "version": "2.0.0-beta.49",
3
+ "version": "2.0.0-beta.50",
4
4
  "description": "Pino integration for oRPC: structured logging for typesafe APIs",
5
5
  "keywords": [
6
6
  "logger",
@@ -35,10 +35,10 @@
35
35
  }
36
36
  },
37
37
  "dependencies": {
38
- "@orpc/client": "2.0.0-beta.49",
39
- "@orpc/server": "2.0.0-beta.49",
40
- "@orpc/shared": "2.0.0-beta.49",
41
- "@standard-server/core": "~0.15.0"
38
+ "@orpc/client": "2.0.0-beta.50",
39
+ "@orpc/server": "2.0.0-beta.50",
40
+ "@orpc/shared": "2.0.0-beta.50",
41
+ "@standard-server/core": "~0.16.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "pino": "^10.4.0"