nestjs-pino 5.3.1-alpha.c0c90a → 5.3.2
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.
|
@@ -19,11 +19,12 @@ export declare class LoggerModule implements NestModule {
|
|
|
19
19
|
*/
|
|
20
20
|
private exposeFastifyResponseHeaders;
|
|
21
21
|
/**
|
|
22
|
-
* A path excluded from the global prefix is served outside of it, while
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
22
|
+
* A path excluded from the global prefix is served outside of it, while the
|
|
23
|
+
* default route is prefixed like any other middleware route, so such a path
|
|
24
|
+
* would go unlogged. NestJS adds excluded paths back on its own, but only
|
|
25
|
+
* for routes that `RouteInfoPathExtractor.isAWildcard` recognises — which
|
|
26
|
+
* the default route, with its leading slash deliberately missing under a
|
|
27
|
+
* prefix, is not.
|
|
27
28
|
*
|
|
28
29
|
* Since @nestjs/core@12.5.0 and 11.2.10 NestJS also mounts a non-wildcard
|
|
29
30
|
* route on the controller routes it covers on the other side of the prefix,
|
package/dist/cjs/LoggerModule.js
CHANGED
|
@@ -29,13 +29,19 @@ const storage_js_1 = require("./storage.js");
|
|
|
29
29
|
* the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so
|
|
30
30
|
* as soon as a global prefix is set.
|
|
31
31
|
*
|
|
32
|
-
*
|
|
33
|
-
* @nestjs/common@11.0.8 `addLeadingSlash` leaves a
|
|
34
|
-
* alone.
|
|
35
|
-
* `/v1/{*splat}`, which matters because the latter
|
|
36
|
-
* root itself — `/v1` would go unlogged, while
|
|
32
|
+
* Under a global prefix the missing leading slash is deliberate, and is
|
|
33
|
+
* supported upstream: since @nestjs/common@11.0.8 `addLeadingSlash` leaves a
|
|
34
|
+
* path starting with `{/` alone. The prefix is then applied as
|
|
35
|
+
* `/v1{/*splat}` rather than `/v1/{*splat}`, which matters because the latter
|
|
36
|
+
* does not match the prefix root itself — `/v1` would go unlogged, while
|
|
37
|
+
* `/v1/anything` would not.
|
|
38
|
+
*
|
|
39
|
+
* Without a prefix there is nothing to join, and the leading slash has to be
|
|
40
|
+
* there: since @fastify/middie@9.3.6 a mount path without one is prefixed with
|
|
41
|
+
* `/` to close GHSA-5p92-8765-9fv8, turning `{/*splat}` into `/{/*splat}`,
|
|
42
|
+
* which only matches `/` and paths starting with `//`.
|
|
37
43
|
*/
|
|
38
|
-
const
|
|
44
|
+
const defaultRoutePath = (withPrefix) => withPrefix ? '{/*splat}' : '/{*splat}';
|
|
39
45
|
let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
40
46
|
params;
|
|
41
47
|
applicationConfig;
|
|
@@ -146,11 +152,12 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
|
146
152
|
});
|
|
147
153
|
}
|
|
148
154
|
/**
|
|
149
|
-
* A path excluded from the global prefix is served outside of it, while
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
*
|
|
155
|
+
* A path excluded from the global prefix is served outside of it, while the
|
|
156
|
+
* default route is prefixed like any other middleware route, so such a path
|
|
157
|
+
* would go unlogged. NestJS adds excluded paths back on its own, but only
|
|
158
|
+
* for routes that `RouteInfoPathExtractor.isAWildcard` recognises — which
|
|
159
|
+
* the default route, with its leading slash deliberately missing under a
|
|
160
|
+
* prefix, is not.
|
|
154
161
|
*
|
|
155
162
|
* Since @nestjs/core@12.5.0 and 11.2.10 NestJS also mounts a non-wildcard
|
|
156
163
|
* route on the controller routes it covers on the other side of the prefix,
|
|
@@ -161,8 +168,12 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
|
161
168
|
*/
|
|
162
169
|
defaultRoutes() {
|
|
163
170
|
const { exclude } = this.applicationConfig.getGlobalPrefixOptions();
|
|
171
|
+
const prefix = this.applicationConfig.getGlobalPrefix();
|
|
164
172
|
return [
|
|
165
|
-
|
|
173
|
+
{
|
|
174
|
+
path: defaultRoutePath(!!prefix),
|
|
175
|
+
method: common_1.RequestMethod.ALL,
|
|
176
|
+
},
|
|
166
177
|
...(exclude ?? []).map(({ path, requestMethod }) => ({
|
|
167
178
|
path,
|
|
168
179
|
method: requestMethod,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LoggerModule.js","sourceRoot":"","sources":["../../src/LoggerModule.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAEA,2CASwB;AACxB,uCAAkE;AAElE,+DAAoE;AACpE,2CAAqC;AACrC,uDAI2B;AAC3B,uDAAiD;AACjD,mDAA6C;AAC7C,2CAIqB;AACrB,mDAA2E;AAC3E,6CAA8C;AAE9C;;;;;;;;;;GAUG;AACH,MAAM,cAAc,GAAG,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,sBAAa,CAAC,GAAG,EAAE,CAAC,CAAC;AAInE,IAAM,YAAY,oBAAlB,MAAM,YAAY;IA6E2B,MAAM;IACrC,iBAAiB;IACjB,eAAe;IA9E3B,AAAP,MAAM,CAAC,OAAO,CAIZ,MAAqC;QACrC,MAAM,cAAc,GAA2C;YAC7D,OAAO,EAAE,iCAAqB;YAC9B,QAAQ,EAAE,MAAM,IAAI,EAAE;SACvB,CAAC;QAEF,MAAM,SAAS,GAAG,IAAA,iDAA2B,GAAE,CAAC;QAChD,MAAM,YAAY,GAAG,kBAAkB,EAAE,CAAC;QAE1C,OAAO;YACL,MAAM,gBAAc;YACpB,SAAS,EAAE;gBACT,kBAAM;gBACN,8BAAY;gBACZ,GAAG,SAAS;gBACZ,0BAAU;gBACV,cAAc;gBACd,YAAY;aACb;YACD,OAAO,EAAE;gBACP,kBAAM;gBACN,8BAAY;gBACZ,GAAG,SAAS;gBACZ,0BAAU;gBACV,cAAc;gBACd,YAAY;aACb;SACF,CAAC;IACJ,CAAC;IAEM,AAAP,MAAM,CAAC,YAAY,CAIjB,MAAqD;QACrD,MAAM,cAAc,GAEhB;YACF,OAAO,EAAE,iCAAqB;YAC9B,UAAU,EAAE,MAAM,CAAC,U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n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger.js';\nimport { Logger } from './Logger.js';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice.js';\nimport { NativeLogger } from './NativeLogger.js';\nimport { PinoLogger } from './PinoLogger.js';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params.js';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger.js';\nimport { Store, storage } from './storage.js';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * The missing leading slash is deliberate, and is supported upstream: since\n * @nestjs/common@11.0.8 `addLeadingSlash` leaves a path starting with `{/`\n * alone. A global prefix is then applied as `/v1{/*splat}` rather than\n * `/v1/{*splat}`, which matters because the latter does not match the prefix\n * root itself — `/v1` would go unlogged, while `/v1/anything` would not.\n */\nconst DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n private readonly httpAdapterHost: HttpAdapterHost,\n ) {\n // Microservices have no middleware, so `configure` is never called for\n // them. The hook is registered here instead, early enough that the message\n // handlers being built later pick it up.\n if (params.microservice) {\n ensureRootLogger(params.pinoHttp);\n registerMicroserviceHook(applicationConfig, params);\n }\n }\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = runOncePerRequest(\n createLoggerMiddlewares(pinoHttp || {}, useExisting, assignResponse),\n );\n\n if (exclude) {\n consumer\n .apply(middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(middlewares).forRoutes(...forRoutes);\n }\n\n this.exposeFastifyResponseHeaders();\n }\n\n /**\n * Fastify hands its headers to the raw response in a single `writeHead`\n * call, and Node keeps no record of headers passed that way: `getHeaders()`,\n * which the `res` serializer reads, stays empty. Setting them on the raw\n * response first makes `writeHead` merge into that record instead, so the\n * request log carries the response headers as it does under Express.\n */\n private exposeFastifyResponseHeaders() {\n const adapter = this.httpAdapterHost.httpAdapter;\n if (adapter?.getType() !== 'fastify') return;\n\n adapter\n .getInstance()\n .addHook(\n 'onSend',\n (\n _req: unknown,\n reply: FastifyReplyLike,\n _payload: unknown,\n done: () => void,\n ) => {\n for (const [name, value] of Object.entries(reply.getHeaders())) {\n if (value !== undefined) reply.raw.setHeader(name, value);\n }\n done();\n },\n );\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while\n * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a\n * path would go unlogged. NestJS adds excluded paths back on its own, but\n * only for routes that `RouteInfoPathExtractor.isAWildcard` recognises —\n * which `{/*splat}`, with its leading slash deliberately missing, is not.\n *\n * Since @nestjs/core@12.5.0 and 11.2.10 NestJS also mounts a non-wildcard\n * route on the controller routes it covers on the other side of the prefix,\n * so an excluded path ends up mounted twice there. `runOncePerRequest` keeps\n * that from logging the request twice, on every version.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n\n return [\n ...DEFAULT_ROUTES,\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\n/** The part of fastify's `Reply` used here, spelled out to not depend on it. */\ntype FastifyReplyLike = {\n raw: ServerResponse;\n getHeaders(): Record<string, number | string | string[] | undefined>;\n};\n\n/**\n * Exposes the very hook the module registers on its own, for the one case it\n * cannot reach: a hybrid application connected without `inheritAppConfig`.\n */\nfunction createHookProvider(): Provider {\n return {\n provide: PINO_PRE_REQUEST_HOOK,\n useFactory: (params: Params) => {\n ensureRootLogger(params.pinoHttp);\n return getMicroserviceHook(params);\n },\n inject: [PARAMS_PROVIDER_TOKEN],\n };\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\ntype Middleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n) => void;\n\n/**\n * Chains the middlewares into one that runs at most once per request.\n *\n * NestJS may mount the same middleware on several paths that match one\n * request: an excluded path covered by the default route is mounted both by\n * `defaultRoutes()` and, since @nestjs/core@12.5.0 and 11.2.10, by NestJS\n * itself; overlapping `forRoutes` entries do the same. Each run would attach\n * another pino-http logger and emit another \"request completed\" log. Later\n * runs just pass the request on, still inside the context of the first one.\n */\nfunction runOncePerRequest(middlewares: Middleware[]): Middleware {\n const handled = new WeakSet<IncomingMessage>();\n\n return function loggerMiddleware(req, res, next) {\n if (handled.has(req)) return next();\n handled.add(req);\n\n const run = (index: number, error?: unknown): void => {\n if (error !== undefined || index === middlewares.length) {\n next(error);\n return;\n }\n middlewares[index]!(req, res, (err) => run(index + 1, err));\n };\n run(0);\n };\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"LoggerModule.js","sourceRoot":"","sources":["../../src/LoggerModule.ts"],"names":[],"mappings":";;;;;;;;;;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AC,KAAa,EAAE,KAAe,EAAQ,EAAE;YACnD,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,WAAW,CAAC,MAAM,EAAE,CAAC;gBACxD,IAAI,CAAC,KAAK,CAAC,CAAC;gBACZ,OAAO;YACT,CAAC;YACD,WAAW,CAAC,KAAK,CAAE,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;QAC9D,CAAC,CAAC;QACF,GAAG,CAAC,CAAC,CAAC,CAAC;IACT,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,2BAA2B,CAClC,WAAoB,EACpB,cAAuB;IAEvB,OAAO,SAAS,oBAAoB,CAClC,GAAoB,EACpB,GAAmB,EACnB,IAAgB;QAEhB,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC;QAClB,IAAI,MAAM,GAAG,cAAc,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC;QAElD,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAChC,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAC7C,CAAC;QACD,IAAI,cAAc,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAClD,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAChD,CAAC;QAED,oBAAO,CAAC,GAAG,CAAC,IAAI,kBAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger.js';\nimport { Logger } from './Logger.js';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice.js';\nimport { NativeLogger } from './NativeLogger.js';\nimport { PinoLogger } from './PinoLogger.js';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params.js';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger.js';\nimport { Store, storage } from './storage.js';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * Under a global prefix the missing leading slash is deliberate, and is\n * supported upstream: since @nestjs/common@11.0.8 `addLeadingSlash` leaves a\n * path starting with `{/` alone. The prefix is then applied as\n * `/v1{/*splat}` rather than `/v1/{*splat}`, which matters because the latter\n * does not match the prefix root itself — `/v1` would go unlogged, while\n * `/v1/anything` would not.\n *\n * Without a prefix there is nothing to join, and the leading slash has to be\n * there: since @fastify/middie@9.3.6 a mount path without one is prefixed with\n * `/` to close GHSA-5p92-8765-9fv8, turning `{/*splat}` into `/{/*splat}`,\n * which only matches `/` and paths starting with `//`.\n */\nconst defaultRoutePath = (withPrefix: boolean) =>\n withPrefix ? '{/*splat}' : '/{*splat}';\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n private readonly httpAdapterHost: HttpAdapterHost,\n ) {\n // Microservices have no middleware, so `configure` is never called for\n // them. The hook is registered here instead, early enough that the message\n // handlers being built later pick it up.\n if (params.microservice) {\n ensureRootLogger(params.pinoHttp);\n registerMicroserviceHook(applicationConfig, params);\n }\n }\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = runOncePerRequest(\n createLoggerMiddlewares(pinoHttp || {}, useExisting, assignResponse),\n );\n\n if (exclude) {\n consumer\n .apply(middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(middlewares).forRoutes(...forRoutes);\n }\n\n this.exposeFastifyResponseHeaders();\n }\n\n /**\n * Fastify hands its headers to the raw response in a single `writeHead`\n * call, and Node keeps no record of headers passed that way: `getHeaders()`,\n * which the `res` serializer reads, stays empty. Setting them on the raw\n * response first makes `writeHead` merge into that record instead, so the\n * request log carries the response headers as it does under Express.\n */\n private exposeFastifyResponseHeaders() {\n const adapter = this.httpAdapterHost.httpAdapter;\n if (adapter?.getType() !== 'fastify') return;\n\n adapter\n .getInstance()\n .addHook(\n 'onSend',\n (\n _req: unknown,\n reply: FastifyReplyLike,\n _payload: unknown,\n done: () => void,\n ) => {\n for (const [name, value] of Object.entries(reply.getHeaders())) {\n if (value !== undefined) reply.raw.setHeader(name, value);\n }\n done();\n },\n );\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while the\n * default route is prefixed like any other middleware route, so such a path\n * would go unlogged. NestJS adds excluded paths back on its own, but only\n * for routes that `RouteInfoPathExtractor.isAWildcard` recognises — which\n * the default route, with its leading slash deliberately missing under a\n * prefix, is not.\n *\n * Since @nestjs/core@12.5.0 and 11.2.10 NestJS also mounts a non-wildcard\n * route on the controller routes it covers on the other side of the prefix,\n * so an excluded path ends up mounted twice there. `runOncePerRequest` keeps\n * that from logging the request twice, on every version.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n const prefix = this.applicationConfig.getGlobalPrefix();\n\n return [\n {\n path: defaultRoutePath(!!prefix),\n method: RequestMethod.ALL,\n },\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\n/** The part of fastify's `Reply` used here, spelled out to not depend on it. */\ntype FastifyReplyLike = {\n raw: ServerResponse;\n getHeaders(): Record<string, number | string | string[] | undefined>;\n};\n\n/**\n * Exposes the very hook the module registers on its own, for the one case it\n * cannot reach: a hybrid application connected without `inheritAppConfig`.\n */\nfunction createHookProvider(): Provider {\n return {\n provide: PINO_PRE_REQUEST_HOOK,\n useFactory: (params: Params) => {\n ensureRootLogger(params.pinoHttp);\n return getMicroserviceHook(params);\n },\n inject: [PARAMS_PROVIDER_TOKEN],\n };\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\ntype Middleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n) => void;\n\n/**\n * Chains the middlewares into one that runs at most once per request.\n *\n * NestJS may mount the same middleware on several paths that match one\n * request: an excluded path covered by the default route is mounted both by\n * `defaultRoutes()` and, since @nestjs/core@12.5.0 and 11.2.10, by NestJS\n * itself; overlapping `forRoutes` entries do the same. Each run would attach\n * another pino-http logger and emit another \"request completed\" log. Later\n * runs just pass the request on, still inside the context of the first one.\n */\nfunction runOncePerRequest(middlewares: Middleware[]): Middleware {\n const handled = new WeakSet<IncomingMessage>();\n\n return function loggerMiddleware(req, res, next) {\n if (handled.has(req)) return next();\n handled.add(req);\n\n const run = (index: number, error?: unknown): void => {\n if (error !== undefined || index === middlewares.length) {\n next(error);\n return;\n }\n middlewares[index]!(req, res, (err) => run(index + 1, err));\n };\n run(0);\n };\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
|
|
@@ -19,11 +19,12 @@ export declare class LoggerModule implements NestModule {
|
|
|
19
19
|
*/
|
|
20
20
|
private exposeFastifyResponseHeaders;
|
|
21
21
|
/**
|
|
22
|
-
* A path excluded from the global prefix is served outside of it, while
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
22
|
+
* A path excluded from the global prefix is served outside of it, while the
|
|
23
|
+
* default route is prefixed like any other middleware route, so such a path
|
|
24
|
+
* would go unlogged. NestJS adds excluded paths back on its own, but only
|
|
25
|
+
* for routes that `RouteInfoPathExtractor.isAWildcard` recognises — which
|
|
26
|
+
* the default route, with its leading slash deliberately missing under a
|
|
27
|
+
* prefix, is not.
|
|
27
28
|
*
|
|
28
29
|
* Since @nestjs/core@12.5.0 and 11.2.10 NestJS also mounts a non-wildcard
|
|
29
30
|
* route on the controller routes it covers on the other side of the prefix,
|
package/dist/esm/LoggerModule.js
CHANGED
|
@@ -26,13 +26,19 @@ import { Store, storage } from './storage.js';
|
|
|
26
26
|
* the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so
|
|
27
27
|
* as soon as a global prefix is set.
|
|
28
28
|
*
|
|
29
|
-
*
|
|
30
|
-
* @nestjs/common@11.0.8 `addLeadingSlash` leaves a
|
|
31
|
-
* alone.
|
|
32
|
-
* `/v1/{*splat}`, which matters because the latter
|
|
33
|
-
* root itself — `/v1` would go unlogged, while
|
|
29
|
+
* Under a global prefix the missing leading slash is deliberate, and is
|
|
30
|
+
* supported upstream: since @nestjs/common@11.0.8 `addLeadingSlash` leaves a
|
|
31
|
+
* path starting with `{/` alone. The prefix is then applied as
|
|
32
|
+
* `/v1{/*splat}` rather than `/v1/{*splat}`, which matters because the latter
|
|
33
|
+
* does not match the prefix root itself — `/v1` would go unlogged, while
|
|
34
|
+
* `/v1/anything` would not.
|
|
35
|
+
*
|
|
36
|
+
* Without a prefix there is nothing to join, and the leading slash has to be
|
|
37
|
+
* there: since @fastify/middie@9.3.6 a mount path without one is prefixed with
|
|
38
|
+
* `/` to close GHSA-5p92-8765-9fv8, turning `{/*splat}` into `/{/*splat}`,
|
|
39
|
+
* which only matches `/` and paths starting with `//`.
|
|
34
40
|
*/
|
|
35
|
-
const
|
|
41
|
+
const defaultRoutePath = (withPrefix) => withPrefix ? '{/*splat}' : '/{*splat}';
|
|
36
42
|
let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
37
43
|
params;
|
|
38
44
|
applicationConfig;
|
|
@@ -143,11 +149,12 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
|
143
149
|
});
|
|
144
150
|
}
|
|
145
151
|
/**
|
|
146
|
-
* A path excluded from the global prefix is served outside of it, while
|
|
147
|
-
*
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
152
|
+
* A path excluded from the global prefix is served outside of it, while the
|
|
153
|
+
* default route is prefixed like any other middleware route, so such a path
|
|
154
|
+
* would go unlogged. NestJS adds excluded paths back on its own, but only
|
|
155
|
+
* for routes that `RouteInfoPathExtractor.isAWildcard` recognises — which
|
|
156
|
+
* the default route, with its leading slash deliberately missing under a
|
|
157
|
+
* prefix, is not.
|
|
151
158
|
*
|
|
152
159
|
* Since @nestjs/core@12.5.0 and 11.2.10 NestJS also mounts a non-wildcard
|
|
153
160
|
* route on the controller routes it covers on the other side of the prefix,
|
|
@@ -158,8 +165,12 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
|
158
165
|
*/
|
|
159
166
|
defaultRoutes() {
|
|
160
167
|
const { exclude } = this.applicationConfig.getGlobalPrefixOptions();
|
|
168
|
+
const prefix = this.applicationConfig.getGlobalPrefix();
|
|
161
169
|
return [
|
|
162
|
-
|
|
170
|
+
{
|
|
171
|
+
path: defaultRoutePath(!!prefix),
|
|
172
|
+
method: RequestMethod.ALL,
|
|
173
|
+
},
|
|
163
174
|
...(exclude ?? []).map(({ path, requestMethod }) => ({
|
|
164
175
|
path,
|
|
165
176
|
method: requestMethod,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LoggerModule.js","sourceRoot":"","sources":["../../src/LoggerModule.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAEA,OAAO,EAEL,MAAM,EACN,MAAM,EAEN,MAAM,EAGN,aAAa,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAElE,OAAO,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAC;AACpE,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAEL,qBAAqB,GAEtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE9C;;;;;;;;;;GAUG;AACH,MAAM,cAAc,GAAG,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,CAAC,GAAG,EAAE,CAAC,CAAC;AAInE,IAAM,YAAY,oBAAlB,MAAM,YAAY;IA6E2B,MAAM;IACrC,iBAAiB;IACjB,eAAe;IA9E3B,AAAP,MAAM,CAAC,OAAO,CAIZ,MAAqC;QACrC,MAAM,cAAc,GAA2C;YAC7D,OAAO,EAAE,qBAAqB;YAC9B,QAAQ,EAAE,MAAM,IAAI,EAAE;SACvB,CAAC;QAEF,MAAM,SAAS,GAAG,2BAA2B,EAAE,CAAC;QAChD,MAAM,YAAY,GAAG,kBAAk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,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAClD,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAChD,CAAC;QAED,OAAO,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger.js';\nimport { Logger } from './Logger.js';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice.js';\nimport { NativeLogger } from './NativeLogger.js';\nimport { PinoLogger } from './PinoLogger.js';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params.js';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger.js';\nimport { Store, storage } from './storage.js';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * The missing leading slash is deliberate, and is supported upstream: since\n * @nestjs/common@11.0.8 `addLeadingSlash` leaves a path starting with `{/`\n * alone. A global prefix is then applied as `/v1{/*splat}` rather than\n * `/v1/{*splat}`, which matters because the latter does not match the prefix\n * root itself — `/v1` would go unlogged, while `/v1/anything` would not.\n */\nconst DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n private readonly httpAdapterHost: HttpAdapterHost,\n ) {\n // Microservices have no middleware, so `configure` is never called for\n // them. The hook is registered here instead, early enough that the message\n // handlers being built later pick it up.\n if (params.microservice) {\n ensureRootLogger(params.pinoHttp);\n registerMicroserviceHook(applicationConfig, params);\n }\n }\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = runOncePerRequest(\n createLoggerMiddlewares(pinoHttp || {}, useExisting, assignResponse),\n );\n\n if (exclude) {\n consumer\n .apply(middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(middlewares).forRoutes(...forRoutes);\n }\n\n this.exposeFastifyResponseHeaders();\n }\n\n /**\n * Fastify hands its headers to the raw response in a single `writeHead`\n * call, and Node keeps no record of headers passed that way: `getHeaders()`,\n * which the `res` serializer reads, stays empty. Setting them on the raw\n * response first makes `writeHead` merge into that record instead, so the\n * request log carries the response headers as it does under Express.\n */\n private exposeFastifyResponseHeaders() {\n const adapter = this.httpAdapterHost.httpAdapter;\n if (adapter?.getType() !== 'fastify') return;\n\n adapter\n .getInstance()\n .addHook(\n 'onSend',\n (\n _req: unknown,\n reply: FastifyReplyLike,\n _payload: unknown,\n done: () => void,\n ) => {\n for (const [name, value] of Object.entries(reply.getHeaders())) {\n if (value !== undefined) reply.raw.setHeader(name, value);\n }\n done();\n },\n );\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while\n * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a\n * path would go unlogged. NestJS adds excluded paths back on its own, but\n * only for routes that `RouteInfoPathExtractor.isAWildcard` recognises —\n * which `{/*splat}`, with its leading slash deliberately missing, is not.\n *\n * Since @nestjs/core@12.5.0 and 11.2.10 NestJS also mounts a non-wildcard\n * route on the controller routes it covers on the other side of the prefix,\n * so an excluded path ends up mounted twice there. `runOncePerRequest` keeps\n * that from logging the request twice, on every version.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n\n return [\n ...DEFAULT_ROUTES,\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\n/** The part of fastify's `Reply` used here, spelled out to not depend on it. */\ntype FastifyReplyLike = {\n raw: ServerResponse;\n getHeaders(): Record<string, number | string | string[] | undefined>;\n};\n\n/**\n * Exposes the very hook the module registers on its own, for the one case it\n * cannot reach: a hybrid application connected without `inheritAppConfig`.\n */\nfunction createHookProvider(): Provider {\n return {\n provide: PINO_PRE_REQUEST_HOOK,\n useFactory: (params: Params) => {\n ensureRootLogger(params.pinoHttp);\n return getMicroserviceHook(params);\n },\n inject: [PARAMS_PROVIDER_TOKEN],\n };\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\ntype Middleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n) => void;\n\n/**\n * Chains the middlewares into one that runs at most once per request.\n *\n * NestJS may mount the same middleware on several paths that match one\n * request: an excluded path covered by the default route is mounted both by\n * `defaultRoutes()` and, since @nestjs/core@12.5.0 and 11.2.10, by NestJS\n * itself; overlapping `forRoutes` entries do the same. Each run would attach\n * another pino-http logger and emit another \"request completed\" log. Later\n * runs just pass the request on, still inside the context of the first one.\n */\nfunction runOncePerRequest(middlewares: Middleware[]): Middleware {\n const handled = new WeakSet<IncomingMessage>();\n\n return function loggerMiddleware(req, res, next) {\n if (handled.has(req)) return next();\n handled.add(req);\n\n const run = (index: number, error?: unknown): void => {\n if (error !== undefined || index === middlewares.length) {\n next(error);\n return;\n }\n middlewares[index]!(req, res, (err) => run(index + 1, err));\n };\n run(0);\n };\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"LoggerModule.js","sourceRoot":"","sources":["../../src/LoggerModule.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAEA,OAAO,EAEL,MAAM,EACN,MAAM,EAEN,MAAM,EAGN,aAAa,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAElE,OAAO,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAC;AACpE,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAEL,qBAAqB,GAEtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE9C;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,gBAAgB,GAAG,CAAC,UAAmB,EAAE,EAAE,CAC/C,UAAU,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC;AAIlC,IAAM,YAAY,oBAAlB,MAAM,YAAY;IA6E2B,MAAM;IACrC,iBAAiB;IACjB,eAAe;IA9E3B,AAAP,MAAM,CAAC,OAAO,CAIZ,MAAqC;QACrC,MA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B,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC;QAClB,IAAI,MAAM,GAAG,cAAc,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC;QAElD,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAChC,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAC7C,CAAC;QACD,IAAI,cAAc,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAClD,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAChD,CAAC;QAED,OAAO,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger.js';\nimport { Logger } from './Logger.js';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice.js';\nimport { NativeLogger } from './NativeLogger.js';\nimport { PinoLogger } from './PinoLogger.js';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params.js';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger.js';\nimport { Store, storage } from './storage.js';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * Under a global prefix the missing leading slash is deliberate, and is\n * supported upstream: since @nestjs/common@11.0.8 `addLeadingSlash` leaves a\n * path starting with `{/` alone. The prefix is then applied as\n * `/v1{/*splat}` rather than `/v1/{*splat}`, which matters because the latter\n * does not match the prefix root itself — `/v1` would go unlogged, while\n * `/v1/anything` would not.\n *\n * Without a prefix there is nothing to join, and the leading slash has to be\n * there: since @fastify/middie@9.3.6 a mount path without one is prefixed with\n * `/` to close GHSA-5p92-8765-9fv8, turning `{/*splat}` into `/{/*splat}`,\n * which only matches `/` and paths starting with `//`.\n */\nconst defaultRoutePath = (withPrefix: boolean) =>\n withPrefix ? '{/*splat}' : '/{*splat}';\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n private readonly httpAdapterHost: HttpAdapterHost,\n ) {\n // Microservices have no middleware, so `configure` is never called for\n // them. The hook is registered here instead, early enough that the message\n // handlers being built later pick it up.\n if (params.microservice) {\n ensureRootLogger(params.pinoHttp);\n registerMicroserviceHook(applicationConfig, params);\n }\n }\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = runOncePerRequest(\n createLoggerMiddlewares(pinoHttp || {}, useExisting, assignResponse),\n );\n\n if (exclude) {\n consumer\n .apply(middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(middlewares).forRoutes(...forRoutes);\n }\n\n this.exposeFastifyResponseHeaders();\n }\n\n /**\n * Fastify hands its headers to the raw response in a single `writeHead`\n * call, and Node keeps no record of headers passed that way: `getHeaders()`,\n * which the `res` serializer reads, stays empty. Setting them on the raw\n * response first makes `writeHead` merge into that record instead, so the\n * request log carries the response headers as it does under Express.\n */\n private exposeFastifyResponseHeaders() {\n const adapter = this.httpAdapterHost.httpAdapter;\n if (adapter?.getType() !== 'fastify') return;\n\n adapter\n .getInstance()\n .addHook(\n 'onSend',\n (\n _req: unknown,\n reply: FastifyReplyLike,\n _payload: unknown,\n done: () => void,\n ) => {\n for (const [name, value] of Object.entries(reply.getHeaders())) {\n if (value !== undefined) reply.raw.setHeader(name, value);\n }\n done();\n },\n );\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while the\n * default route is prefixed like any other middleware route, so such a path\n * would go unlogged. NestJS adds excluded paths back on its own, but only\n * for routes that `RouteInfoPathExtractor.isAWildcard` recognises — which\n * the default route, with its leading slash deliberately missing under a\n * prefix, is not.\n *\n * Since @nestjs/core@12.5.0 and 11.2.10 NestJS also mounts a non-wildcard\n * route on the controller routes it covers on the other side of the prefix,\n * so an excluded path ends up mounted twice there. `runOncePerRequest` keeps\n * that from logging the request twice, on every version.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n const prefix = this.applicationConfig.getGlobalPrefix();\n\n return [\n {\n path: defaultRoutePath(!!prefix),\n method: RequestMethod.ALL,\n },\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\n/** The part of fastify's `Reply` used here, spelled out to not depend on it. */\ntype FastifyReplyLike = {\n raw: ServerResponse;\n getHeaders(): Record<string, number | string | string[] | undefined>;\n};\n\n/**\n * Exposes the very hook the module registers on its own, for the one case it\n * cannot reach: a hybrid application connected without `inheritAppConfig`.\n */\nfunction createHookProvider(): Provider {\n return {\n provide: PINO_PRE_REQUEST_HOOK,\n useFactory: (params: Params) => {\n ensureRootLogger(params.pinoHttp);\n return getMicroserviceHook(params);\n },\n inject: [PARAMS_PROVIDER_TOKEN],\n };\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\ntype Middleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n) => void;\n\n/**\n * Chains the middlewares into one that runs at most once per request.\n *\n * NestJS may mount the same middleware on several paths that match one\n * request: an excluded path covered by the default route is mounted both by\n * `defaultRoutes()` and, since @nestjs/core@12.5.0 and 11.2.10, by NestJS\n * itself; overlapping `forRoutes` entries do the same. Each run would attach\n * another pino-http logger and emit another \"request completed\" log. Later\n * runs just pass the request on, still inside the context of the first one.\n */\nfunction runOncePerRequest(middlewares: Middleware[]): Middleware {\n const handled = new WeakSet<IncomingMessage>();\n\n return function loggerMiddleware(req, res, next) {\n if (handled.has(req)) return next();\n handled.add(req);\n\n const run = (index: number, error?: unknown): void => {\n if (error !== undefined || index === middlewares.length) {\n next(error);\n return;\n }\n middlewares[index]!(req, res, (err) => run(index + 1, err));\n };\n run(0);\n };\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
|