@logtape/express 2.2.0-dev.684 → 2.2.0-dev.686
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 +43 -0
- package/dist/mod.cjs +156 -14
- package/dist/mod.d.cts +71 -1
- package/dist/mod.d.cts.map +1 -1
- package/dist/mod.d.ts +71 -1
- package/dist/mod.d.ts.map +1 -1
- package/dist/mod.js +157 -15
- package/dist/mod.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -66,6 +66,49 @@ app.use(expressLogger({
|
|
|
66
66
|
format: "dev", // Predefined format (default: "combined")
|
|
67
67
|
skip: (req, res) => res.statusCode < 400, // Skip successful requests
|
|
68
68
|
immediate: false, // Log after response (default)
|
|
69
|
+
context: true, // Add requestId to request-scoped logs
|
|
70
|
+
}));
|
|
71
|
+
~~~~
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
Request context
|
|
75
|
+
---------------
|
|
76
|
+
|
|
77
|
+
Set `context: true` to add request-scoped correlation fields. By default,
|
|
78
|
+
the middleware reads the `x-request-id` request header, generates an ID when
|
|
79
|
+
the header is missing, writes the resolved ID to the `x-request-id` response
|
|
80
|
+
header, and adds `requestId` to the request log record.
|
|
81
|
+
|
|
82
|
+
To make logs emitted by your route handlers inherit the same `requestId`, also
|
|
83
|
+
configure LogTape with `contextLocalStorage`:
|
|
84
|
+
|
|
85
|
+
~~~~ typescript
|
|
86
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
87
|
+
import { configure } from "@logtape/logtape";
|
|
88
|
+
|
|
89
|
+
await configure({
|
|
90
|
+
// ... sinks and loggers ...
|
|
91
|
+
contextLocalStorage: new AsyncLocalStorage(),
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
app.use(expressLogger({ context: true }));
|
|
95
|
+
~~~~
|
|
96
|
+
|
|
97
|
+
The context is still established when `skip` suppresses the request log, so
|
|
98
|
+
application logs inside the skipped request can keep the same request ID.
|
|
99
|
+
|
|
100
|
+
You can customize request ID headers and add more request fields:
|
|
101
|
+
|
|
102
|
+
~~~~ typescript
|
|
103
|
+
app.use(expressLogger({
|
|
104
|
+
context: {
|
|
105
|
+
requestId: {
|
|
106
|
+
headerNames: ["x-correlation-id", "x-request-id"],
|
|
107
|
+
responseHeader: "x-request-id",
|
|
108
|
+
},
|
|
109
|
+
include: ["requestId", "method", "url", "httpVersion"],
|
|
110
|
+
enrich: (req) => ({ route: req.path }),
|
|
111
|
+
},
|
|
69
112
|
}));
|
|
70
113
|
~~~~
|
|
71
114
|
|
package/dist/mod.cjs
CHANGED
|
@@ -2,6 +2,133 @@ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
|
2
2
|
const __logtape_logtape = require_rolldown_runtime.__toESM(require("@logtape/logtape"));
|
|
3
3
|
|
|
4
4
|
//#region src/mod.ts
|
|
5
|
+
const defaultRequestIdHeader = "x-request-id";
|
|
6
|
+
/**
|
|
7
|
+
* Normalize request context options.
|
|
8
|
+
*/
|
|
9
|
+
function normalizeRequestContextOptions(options) {
|
|
10
|
+
if (options === true) return {};
|
|
11
|
+
if (options === false || options == null) return void 0;
|
|
12
|
+
return options;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Normalize request ID options.
|
|
16
|
+
*/
|
|
17
|
+
function normalizeRequestIdOptions(options) {
|
|
18
|
+
if (options === false) return void 0;
|
|
19
|
+
if (options === true || options == null) return {};
|
|
20
|
+
return options;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Generate a request ID with Web Crypto when possible.
|
|
24
|
+
*/
|
|
25
|
+
function generateRequestId() {
|
|
26
|
+
if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
|
|
27
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Normalize an incoming request ID.
|
|
31
|
+
*/
|
|
32
|
+
function defaultNormalizeRequestId(value) {
|
|
33
|
+
const trimmed = value.trim();
|
|
34
|
+
return trimmed === "" ? null : trimmed;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Resolve the request ID for a request.
|
|
38
|
+
*/
|
|
39
|
+
function resolveRequestId(req, res, options) {
|
|
40
|
+
const property = options.property ?? "requestId";
|
|
41
|
+
const normalize = options.normalize ?? defaultNormalizeRequestId;
|
|
42
|
+
const headerNames = options.headerNames ?? [defaultRequestIdHeader];
|
|
43
|
+
for (const headerName of headerNames) {
|
|
44
|
+
const headerValue = req.get(headerName);
|
|
45
|
+
if (headerValue == null) continue;
|
|
46
|
+
const normalized = normalize(headerValue);
|
|
47
|
+
if (normalized != null) {
|
|
48
|
+
const responseHeader$1 = options.responseHeader ?? defaultRequestIdHeader;
|
|
49
|
+
if (responseHeader$1 !== false) res.setHeader?.(responseHeader$1, normalized);
|
|
50
|
+
return {
|
|
51
|
+
property,
|
|
52
|
+
value: normalized
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const generated = (options.generate ?? generateRequestId)();
|
|
57
|
+
const responseHeader = options.responseHeader ?? defaultRequestIdHeader;
|
|
58
|
+
if (responseHeader !== false) res.setHeader?.(responseHeader, generated);
|
|
59
|
+
return {
|
|
60
|
+
property,
|
|
61
|
+
value: generated
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Build request context fields from a request.
|
|
66
|
+
*/
|
|
67
|
+
function buildIncludedContext(req, resolvedRequestId, include) {
|
|
68
|
+
const context = {};
|
|
69
|
+
for (const field of include) switch (field) {
|
|
70
|
+
case "requestId":
|
|
71
|
+
if (resolvedRequestId != null) context[resolvedRequestId.property] = resolvedRequestId.value;
|
|
72
|
+
break;
|
|
73
|
+
case "method":
|
|
74
|
+
context.method = req.method;
|
|
75
|
+
break;
|
|
76
|
+
case "url":
|
|
77
|
+
context.url = req.originalUrl || req.url;
|
|
78
|
+
break;
|
|
79
|
+
case "path":
|
|
80
|
+
context.path = req.path;
|
|
81
|
+
break;
|
|
82
|
+
case "userAgent":
|
|
83
|
+
context.userAgent = getUserAgent(req);
|
|
84
|
+
break;
|
|
85
|
+
case "remoteAddr":
|
|
86
|
+
context.remoteAddr = getRemoteAddr(req);
|
|
87
|
+
break;
|
|
88
|
+
case "referrer":
|
|
89
|
+
context.referrer = getReferrer(req);
|
|
90
|
+
break;
|
|
91
|
+
case "httpVersion":
|
|
92
|
+
context.httpVersion = req.httpVersion;
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
return context;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Check whether a value is a promise-like object.
|
|
99
|
+
*/
|
|
100
|
+
function isPromiseLike(value) {
|
|
101
|
+
return value != null && typeof value === "object" && typeof value.then === "function";
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Build the implicit context for a request.
|
|
105
|
+
*/
|
|
106
|
+
function buildRequestContext(req, res, options) {
|
|
107
|
+
const requestIdOptions = normalizeRequestIdOptions(options.requestId);
|
|
108
|
+
const resolvedRequestId = requestIdOptions == null ? void 0 : resolveRequestId(req, res, requestIdOptions);
|
|
109
|
+
const include = options.include ?? (resolvedRequestId == null ? [] : ["requestId"]);
|
|
110
|
+
const context = buildIncludedContext(req, resolvedRequestId, include);
|
|
111
|
+
if (options.enrich == null) return context;
|
|
112
|
+
const enriched = options.enrich(req, res);
|
|
113
|
+
if (isPromiseLike(enriched)) return Promise.resolve(enriched).then((extraContext) => ({
|
|
114
|
+
...context,
|
|
115
|
+
...extraContext
|
|
116
|
+
}));
|
|
117
|
+
return {
|
|
118
|
+
...context,
|
|
119
|
+
...enriched
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Add request context fields to a request log result.
|
|
124
|
+
*/
|
|
125
|
+
function withRequestLogContext(result, context) {
|
|
126
|
+
if (typeof result === "string") return result;
|
|
127
|
+
return {
|
|
128
|
+
...result,
|
|
129
|
+
...context
|
|
130
|
+
};
|
|
131
|
+
}
|
|
5
132
|
/**
|
|
6
133
|
* Get remote address from request.
|
|
7
134
|
*/
|
|
@@ -163,28 +290,43 @@ function expressLogger(options = {}) {
|
|
|
163
290
|
const formatOption = options.format ?? "combined";
|
|
164
291
|
const skip = options.skip ?? (() => false);
|
|
165
292
|
const immediate = options.immediate ?? false;
|
|
293
|
+
const contextOptions = normalizeRequestContextOptions(options.context);
|
|
166
294
|
const formatFn = typeof formatOption === "string" ? predefinedFormats[formatOption] : formatOption;
|
|
167
295
|
const logMethod = logger[level].bind(logger);
|
|
168
296
|
return (req, res, next) => {
|
|
169
297
|
const startTime = Date.now();
|
|
170
|
-
|
|
171
|
-
if (
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
298
|
+
const handleRequest = (requestContext$1) => {
|
|
299
|
+
if (immediate) {
|
|
300
|
+
if (!skip(req, res)) {
|
|
301
|
+
const result = withRequestLogContext(formatFn(req, res, 0), requestContext$1);
|
|
302
|
+
if (typeof result === "string") logMethod(result, requestContext$1);
|
|
303
|
+
else logMethod("{method} {url}", result);
|
|
304
|
+
}
|
|
305
|
+
next();
|
|
306
|
+
return;
|
|
175
307
|
}
|
|
308
|
+
const logRequest = () => {
|
|
309
|
+
if (skip(req, res)) return;
|
|
310
|
+
const responseTime = Date.now() - startTime;
|
|
311
|
+
const result = withRequestLogContext(formatFn(req, res, responseTime), requestContext$1);
|
|
312
|
+
if (typeof result === "string") logMethod(result, requestContext$1);
|
|
313
|
+
else logMethod("{method} {url} {status} - {responseTime} ms", result);
|
|
314
|
+
};
|
|
315
|
+
res.on("finish", logRequest);
|
|
176
316
|
next();
|
|
317
|
+
};
|
|
318
|
+
if (contextOptions == null) {
|
|
319
|
+
handleRequest({});
|
|
177
320
|
return;
|
|
178
321
|
}
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
next();
|
|
322
|
+
const requestContext = buildRequestContext(req, res, contextOptions);
|
|
323
|
+
if (isPromiseLike(requestContext)) {
|
|
324
|
+
Promise.resolve(requestContext).then((resolvedContext) => {
|
|
325
|
+
(0, __logtape_logtape.withContext)(resolvedContext, () => handleRequest(resolvedContext));
|
|
326
|
+
}, next);
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
(0, __logtape_logtape.withContext)(requestContext, () => handleRequest(requestContext));
|
|
188
330
|
};
|
|
189
331
|
}
|
|
190
332
|
|
package/dist/mod.d.cts
CHANGED
|
@@ -26,6 +26,7 @@ interface ExpressResponse {
|
|
|
26
26
|
statusCode: number;
|
|
27
27
|
on(event: string, listener: () => void): void;
|
|
28
28
|
getHeader(name: string): string | number | string[] | undefined;
|
|
29
|
+
setHeader?(name: string, value: string): void;
|
|
29
30
|
}
|
|
30
31
|
/**
|
|
31
32
|
* Express NextFunction type.
|
|
@@ -76,6 +77,63 @@ interface RequestLogProperties {
|
|
|
76
77
|
/** HTTP version (e.g., "1.1") */
|
|
77
78
|
httpVersion: string;
|
|
78
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* Request fields that can be added to the implicit request context.
|
|
82
|
+
* @since 2.2.0
|
|
83
|
+
*/
|
|
84
|
+
type RequestContextField = "requestId" | "method" | "url" | "path" | "userAgent" | "remoteAddr" | "referrer" | "httpVersion";
|
|
85
|
+
/**
|
|
86
|
+
* Options for extracting, generating, and propagating a request ID.
|
|
87
|
+
* @since 2.2.0
|
|
88
|
+
*/
|
|
89
|
+
interface RequestIdOptions {
|
|
90
|
+
/**
|
|
91
|
+
* The property name used in implicit context and request log records.
|
|
92
|
+
* @default "requestId"
|
|
93
|
+
*/
|
|
94
|
+
readonly property?: string;
|
|
95
|
+
/**
|
|
96
|
+
* Incoming request headers to inspect in order.
|
|
97
|
+
* @default ["x-request-id"]
|
|
98
|
+
*/
|
|
99
|
+
readonly headerNames?: readonly string[];
|
|
100
|
+
/**
|
|
101
|
+
* Response header that receives the resolved request ID.
|
|
102
|
+
* Set to `false` to disable response header propagation.
|
|
103
|
+
* @default "x-request-id"
|
|
104
|
+
*/
|
|
105
|
+
readonly responseHeader?: string | false;
|
|
106
|
+
/**
|
|
107
|
+
* Generates a request ID when no incoming header is present.
|
|
108
|
+
* @default crypto.randomUUID()
|
|
109
|
+
*/
|
|
110
|
+
readonly generate?: () => string;
|
|
111
|
+
/**
|
|
112
|
+
* Normalizes an incoming request ID. Return `null` to reject the value and
|
|
113
|
+
* keep looking for another header or generate a new ID.
|
|
114
|
+
*/
|
|
115
|
+
readonly normalize?: (value: string) => string | null;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Options for request-scoped implicit context.
|
|
119
|
+
* @since 2.2.0
|
|
120
|
+
*/
|
|
121
|
+
interface RequestContextOptions {
|
|
122
|
+
/**
|
|
123
|
+
* Enables request ID extraction, generation, and response propagation.
|
|
124
|
+
* @default true
|
|
125
|
+
*/
|
|
126
|
+
readonly requestId?: boolean | RequestIdOptions;
|
|
127
|
+
/**
|
|
128
|
+
* Fields to add to the implicit context.
|
|
129
|
+
* @default ["requestId"]
|
|
130
|
+
*/
|
|
131
|
+
readonly include?: readonly RequestContextField[];
|
|
132
|
+
/**
|
|
133
|
+
* Adds application-specific fields to the implicit request context.
|
|
134
|
+
*/
|
|
135
|
+
readonly enrich?: (req: ExpressRequest, res: ExpressResponse) => Record<string, unknown> | Promise<Record<string, unknown>>;
|
|
136
|
+
}
|
|
79
137
|
/**
|
|
80
138
|
* Options for configuring the Express LogTape middleware.
|
|
81
139
|
* @since 1.3.0
|
|
@@ -129,6 +187,18 @@ interface ExpressLogTapeOptions {
|
|
|
129
187
|
* @default false
|
|
130
188
|
*/
|
|
131
189
|
readonly immediate?: boolean;
|
|
190
|
+
/**
|
|
191
|
+
* Enables request-scoped implicit context and request ID correlation.
|
|
192
|
+
*
|
|
193
|
+
* When set to `true`, the middleware reads the `x-request-id` header,
|
|
194
|
+
* generates one when it is absent, writes it to the `x-request-id` response
|
|
195
|
+
* header, and adds `requestId` to all LogTape records emitted while handling
|
|
196
|
+
* the request.
|
|
197
|
+
*
|
|
198
|
+
* @default false
|
|
199
|
+
* @since 2.2.0
|
|
200
|
+
*/
|
|
201
|
+
readonly context?: boolean | RequestContextOptions;
|
|
132
202
|
}
|
|
133
203
|
/**
|
|
134
204
|
* Creates Express middleware for HTTP request logging using LogTape.
|
|
@@ -188,5 +258,5 @@ interface ExpressLogTapeOptions {
|
|
|
188
258
|
declare function expressLogger(options?: ExpressLogTapeOptions): ExpressMiddleware;
|
|
189
259
|
//# sourceMappingURL=mod.d.ts.map
|
|
190
260
|
//#endregion
|
|
191
|
-
export { ExpressLogTapeOptions, ExpressMiddleware, ExpressNextFunction, ExpressRequest, ExpressResponse, FormatFunction, LogLevel, PredefinedFormat, RequestLogProperties, expressLogger };
|
|
261
|
+
export { ExpressLogTapeOptions, ExpressMiddleware, ExpressNextFunction, ExpressRequest, ExpressResponse, FormatFunction, LogLevel, PredefinedFormat, RequestContextField, RequestContextOptions, RequestIdOptions, RequestLogProperties, expressLogger };
|
|
192
262
|
//# sourceMappingURL=mod.d.cts.map
|
package/dist/mod.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mod.d.cts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;AAWA;AAeA;
|
|
1
|
+
{"version":3,"file":"mod.d.cts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;AAWA;AAeA;AAWA;AAMY,UAhCK,cAAA,CAgCY;EAAA,MAAA,EAAA,MAAA;EAAA,GACtB,EAAA,MAAA;EAAc,WACd,CAAA,EAAA,MAAA;EAAe,IACd,CAAA,EAAA,MAAA;EAAmB,WAAA,EAAA,MAAA;EAOf,EAAA,CAAA,EAAA,MAAA;EAWA,MAAA,CAAA,EAAA;IAAc,aAAA,CAAA,EAAA,MAAA;EAAA,CAAA;EACL,GACd,CAAA,MAAA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 -26,6 +26,7 @@ interface ExpressResponse {
|
|
|
26
26
|
statusCode: number;
|
|
27
27
|
on(event: string, listener: () => void): void;
|
|
28
28
|
getHeader(name: string): string | number | string[] | undefined;
|
|
29
|
+
setHeader?(name: string, value: string): void;
|
|
29
30
|
}
|
|
30
31
|
/**
|
|
31
32
|
* Express NextFunction type.
|
|
@@ -76,6 +77,63 @@ interface RequestLogProperties {
|
|
|
76
77
|
/** HTTP version (e.g., "1.1") */
|
|
77
78
|
httpVersion: string;
|
|
78
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* Request fields that can be added to the implicit request context.
|
|
82
|
+
* @since 2.2.0
|
|
83
|
+
*/
|
|
84
|
+
type RequestContextField = "requestId" | "method" | "url" | "path" | "userAgent" | "remoteAddr" | "referrer" | "httpVersion";
|
|
85
|
+
/**
|
|
86
|
+
* Options for extracting, generating, and propagating a request ID.
|
|
87
|
+
* @since 2.2.0
|
|
88
|
+
*/
|
|
89
|
+
interface RequestIdOptions {
|
|
90
|
+
/**
|
|
91
|
+
* The property name used in implicit context and request log records.
|
|
92
|
+
* @default "requestId"
|
|
93
|
+
*/
|
|
94
|
+
readonly property?: string;
|
|
95
|
+
/**
|
|
96
|
+
* Incoming request headers to inspect in order.
|
|
97
|
+
* @default ["x-request-id"]
|
|
98
|
+
*/
|
|
99
|
+
readonly headerNames?: readonly string[];
|
|
100
|
+
/**
|
|
101
|
+
* Response header that receives the resolved request ID.
|
|
102
|
+
* Set to `false` to disable response header propagation.
|
|
103
|
+
* @default "x-request-id"
|
|
104
|
+
*/
|
|
105
|
+
readonly responseHeader?: string | false;
|
|
106
|
+
/**
|
|
107
|
+
* Generates a request ID when no incoming header is present.
|
|
108
|
+
* @default crypto.randomUUID()
|
|
109
|
+
*/
|
|
110
|
+
readonly generate?: () => string;
|
|
111
|
+
/**
|
|
112
|
+
* Normalizes an incoming request ID. Return `null` to reject the value and
|
|
113
|
+
* keep looking for another header or generate a new ID.
|
|
114
|
+
*/
|
|
115
|
+
readonly normalize?: (value: string) => string | null;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Options for request-scoped implicit context.
|
|
119
|
+
* @since 2.2.0
|
|
120
|
+
*/
|
|
121
|
+
interface RequestContextOptions {
|
|
122
|
+
/**
|
|
123
|
+
* Enables request ID extraction, generation, and response propagation.
|
|
124
|
+
* @default true
|
|
125
|
+
*/
|
|
126
|
+
readonly requestId?: boolean | RequestIdOptions;
|
|
127
|
+
/**
|
|
128
|
+
* Fields to add to the implicit context.
|
|
129
|
+
* @default ["requestId"]
|
|
130
|
+
*/
|
|
131
|
+
readonly include?: readonly RequestContextField[];
|
|
132
|
+
/**
|
|
133
|
+
* Adds application-specific fields to the implicit request context.
|
|
134
|
+
*/
|
|
135
|
+
readonly enrich?: (req: ExpressRequest, res: ExpressResponse) => Record<string, unknown> | Promise<Record<string, unknown>>;
|
|
136
|
+
}
|
|
79
137
|
/**
|
|
80
138
|
* Options for configuring the Express LogTape middleware.
|
|
81
139
|
* @since 1.3.0
|
|
@@ -129,6 +187,18 @@ interface ExpressLogTapeOptions {
|
|
|
129
187
|
* @default false
|
|
130
188
|
*/
|
|
131
189
|
readonly immediate?: boolean;
|
|
190
|
+
/**
|
|
191
|
+
* Enables request-scoped implicit context and request ID correlation.
|
|
192
|
+
*
|
|
193
|
+
* When set to `true`, the middleware reads the `x-request-id` header,
|
|
194
|
+
* generates one when it is absent, writes it to the `x-request-id` response
|
|
195
|
+
* header, and adds `requestId` to all LogTape records emitted while handling
|
|
196
|
+
* the request.
|
|
197
|
+
*
|
|
198
|
+
* @default false
|
|
199
|
+
* @since 2.2.0
|
|
200
|
+
*/
|
|
201
|
+
readonly context?: boolean | RequestContextOptions;
|
|
132
202
|
}
|
|
133
203
|
/**
|
|
134
204
|
* Creates Express middleware for HTTP request logging using LogTape.
|
|
@@ -188,5 +258,5 @@ interface ExpressLogTapeOptions {
|
|
|
188
258
|
declare function expressLogger(options?: ExpressLogTapeOptions): ExpressMiddleware;
|
|
189
259
|
//# sourceMappingURL=mod.d.ts.map
|
|
190
260
|
//#endregion
|
|
191
|
-
export { ExpressLogTapeOptions, ExpressMiddleware, ExpressNextFunction, ExpressRequest, ExpressResponse, FormatFunction, LogLevel, PredefinedFormat, RequestLogProperties, expressLogger };
|
|
261
|
+
export { ExpressLogTapeOptions, ExpressMiddleware, ExpressNextFunction, ExpressRequest, ExpressResponse, FormatFunction, LogLevel, PredefinedFormat, RequestContextField, RequestContextOptions, RequestIdOptions, RequestLogProperties, expressLogger };
|
|
192
262
|
//# sourceMappingURL=mod.d.ts.map
|
package/dist/mod.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mod.d.ts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;AAWA;AAeA;
|
|
1
|
+
{"version":3,"file":"mod.d.ts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;AAWA;AAeA;AAWA;AAMY,UAhCK,cAAA,CAgCY;EAAA,MAAA,EAAA,MAAA;EAAA,GACtB,EAAA,MAAA;EAAc,WACd,CAAA,EAAA,MAAA;EAAe,IACd,CAAA,EAAA,MAAA;EAAmB,WAAA,EAAA,MAAA;EAOf,EAAA,CAAA,EAAA,MAAA;EAWA,MAAA,CAAA,EAAA;IAAc,aAAA,CAAA,EAAA,MAAA;EAAA,CAAA;EACL,GACd,CAAA,MAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,SAAA;;AAEa;AAMpB;AAyBA;AAcA;AAqCiB,UA5HA,eAAA,CA4HqB;EAAA,UAAA,EAAA,MAAA;EAAA,EAAA,CAKL,KAAA,EAAA,MAAA,EAAA,QAAA,EAAA,GAAA,GAAA,IAAA,CAAA,EAAA,IAAA;EAAgB,SAMnB,CAAA,IAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,MAAA,GAAA,MAAA,EAAA,GAAA,SAAA;EAAmB,SAMxC,EAAA,IAAA,EAAA,MAAA,EAAA,KAAA,EAAA,MAAA,CAAA,EAAA,IAAA;;;;;AAE+B;AAOvB,KA3IL,mBAAA,GA2I0B,CAAA,GAAA,CAAA,EAAA,OAAA,EAAA,GAAA,IAAA;;;;;AAyCd,KA9KZ,iBAAA,GA8KY,CAAA,GAAA,EA7KjB,cA6KiB,EAAA,GAAA,EA5KjB,eA4KiB,EAAA,IAAA,EA3KhB,mBA2KgB,EAAA,GAAA,IAAA;;;AAwB4B;AAuWpD;AAA6B,KAniBjB,gBAAA,GAmiBiB,UAAA,GAAA,QAAA,GAAA,KAAA,GAAA,OAAA,GAAA,MAAA;;;AAET;;;;;;;KA1hBR,cAAA,SACL,qBACA,mDAEO;;;;;UAMG,oBAAA;;;;;;;;;;;;;;;;;;;;;;;;KAyBL,mBAAA;;;;;UAcK,gBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAqCA,qBAAA;;;;;iCAKgB;;;;;8BAMH;;;;0BAMrB,qBACA,oBACF,0BAA0B,QAAQ;;;;;;UAOxB,qBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;oBAeC,mBAAmB;;;;;;;;;;;;;;wBAef,qBAAqB;;;;;;;;;;;;;;;;;;;;;;+BAwBd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAuWf,aAAA,WACL,wBACR"}
|
package/dist/mod.js
CHANGED
|
@@ -1,6 +1,133 @@
|
|
|
1
|
-
import { getLogger } from "@logtape/logtape";
|
|
1
|
+
import { getLogger, withContext } from "@logtape/logtape";
|
|
2
2
|
|
|
3
3
|
//#region src/mod.ts
|
|
4
|
+
const defaultRequestIdHeader = "x-request-id";
|
|
5
|
+
/**
|
|
6
|
+
* Normalize request context options.
|
|
7
|
+
*/
|
|
8
|
+
function normalizeRequestContextOptions(options) {
|
|
9
|
+
if (options === true) return {};
|
|
10
|
+
if (options === false || options == null) return void 0;
|
|
11
|
+
return options;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Normalize request ID options.
|
|
15
|
+
*/
|
|
16
|
+
function normalizeRequestIdOptions(options) {
|
|
17
|
+
if (options === false) return void 0;
|
|
18
|
+
if (options === true || options == null) return {};
|
|
19
|
+
return options;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Generate a request ID with Web Crypto when possible.
|
|
23
|
+
*/
|
|
24
|
+
function generateRequestId() {
|
|
25
|
+
if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
|
|
26
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Normalize an incoming request ID.
|
|
30
|
+
*/
|
|
31
|
+
function defaultNormalizeRequestId(value) {
|
|
32
|
+
const trimmed = value.trim();
|
|
33
|
+
return trimmed === "" ? null : trimmed;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Resolve the request ID for a request.
|
|
37
|
+
*/
|
|
38
|
+
function resolveRequestId(req, res, options) {
|
|
39
|
+
const property = options.property ?? "requestId";
|
|
40
|
+
const normalize = options.normalize ?? defaultNormalizeRequestId;
|
|
41
|
+
const headerNames = options.headerNames ?? [defaultRequestIdHeader];
|
|
42
|
+
for (const headerName of headerNames) {
|
|
43
|
+
const headerValue = req.get(headerName);
|
|
44
|
+
if (headerValue == null) continue;
|
|
45
|
+
const normalized = normalize(headerValue);
|
|
46
|
+
if (normalized != null) {
|
|
47
|
+
const responseHeader$1 = options.responseHeader ?? defaultRequestIdHeader;
|
|
48
|
+
if (responseHeader$1 !== false) res.setHeader?.(responseHeader$1, normalized);
|
|
49
|
+
return {
|
|
50
|
+
property,
|
|
51
|
+
value: normalized
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const generated = (options.generate ?? generateRequestId)();
|
|
56
|
+
const responseHeader = options.responseHeader ?? defaultRequestIdHeader;
|
|
57
|
+
if (responseHeader !== false) res.setHeader?.(responseHeader, generated);
|
|
58
|
+
return {
|
|
59
|
+
property,
|
|
60
|
+
value: generated
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Build request context fields from a request.
|
|
65
|
+
*/
|
|
66
|
+
function buildIncludedContext(req, resolvedRequestId, include) {
|
|
67
|
+
const context = {};
|
|
68
|
+
for (const field of include) switch (field) {
|
|
69
|
+
case "requestId":
|
|
70
|
+
if (resolvedRequestId != null) context[resolvedRequestId.property] = resolvedRequestId.value;
|
|
71
|
+
break;
|
|
72
|
+
case "method":
|
|
73
|
+
context.method = req.method;
|
|
74
|
+
break;
|
|
75
|
+
case "url":
|
|
76
|
+
context.url = req.originalUrl || req.url;
|
|
77
|
+
break;
|
|
78
|
+
case "path":
|
|
79
|
+
context.path = req.path;
|
|
80
|
+
break;
|
|
81
|
+
case "userAgent":
|
|
82
|
+
context.userAgent = getUserAgent(req);
|
|
83
|
+
break;
|
|
84
|
+
case "remoteAddr":
|
|
85
|
+
context.remoteAddr = getRemoteAddr(req);
|
|
86
|
+
break;
|
|
87
|
+
case "referrer":
|
|
88
|
+
context.referrer = getReferrer(req);
|
|
89
|
+
break;
|
|
90
|
+
case "httpVersion":
|
|
91
|
+
context.httpVersion = req.httpVersion;
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
return context;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Check whether a value is a promise-like object.
|
|
98
|
+
*/
|
|
99
|
+
function isPromiseLike(value) {
|
|
100
|
+
return value != null && typeof value === "object" && typeof value.then === "function";
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Build the implicit context for a request.
|
|
104
|
+
*/
|
|
105
|
+
function buildRequestContext(req, res, options) {
|
|
106
|
+
const requestIdOptions = normalizeRequestIdOptions(options.requestId);
|
|
107
|
+
const resolvedRequestId = requestIdOptions == null ? void 0 : resolveRequestId(req, res, requestIdOptions);
|
|
108
|
+
const include = options.include ?? (resolvedRequestId == null ? [] : ["requestId"]);
|
|
109
|
+
const context = buildIncludedContext(req, resolvedRequestId, include);
|
|
110
|
+
if (options.enrich == null) return context;
|
|
111
|
+
const enriched = options.enrich(req, res);
|
|
112
|
+
if (isPromiseLike(enriched)) return Promise.resolve(enriched).then((extraContext) => ({
|
|
113
|
+
...context,
|
|
114
|
+
...extraContext
|
|
115
|
+
}));
|
|
116
|
+
return {
|
|
117
|
+
...context,
|
|
118
|
+
...enriched
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Add request context fields to a request log result.
|
|
123
|
+
*/
|
|
124
|
+
function withRequestLogContext(result, context) {
|
|
125
|
+
if (typeof result === "string") return result;
|
|
126
|
+
return {
|
|
127
|
+
...result,
|
|
128
|
+
...context
|
|
129
|
+
};
|
|
130
|
+
}
|
|
4
131
|
/**
|
|
5
132
|
* Get remote address from request.
|
|
6
133
|
*/
|
|
@@ -162,28 +289,43 @@ function expressLogger(options = {}) {
|
|
|
162
289
|
const formatOption = options.format ?? "combined";
|
|
163
290
|
const skip = options.skip ?? (() => false);
|
|
164
291
|
const immediate = options.immediate ?? false;
|
|
292
|
+
const contextOptions = normalizeRequestContextOptions(options.context);
|
|
165
293
|
const formatFn = typeof formatOption === "string" ? predefinedFormats[formatOption] : formatOption;
|
|
166
294
|
const logMethod = logger[level].bind(logger);
|
|
167
295
|
return (req, res, next) => {
|
|
168
296
|
const startTime = Date.now();
|
|
169
|
-
|
|
170
|
-
if (
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
297
|
+
const handleRequest = (requestContext$1) => {
|
|
298
|
+
if (immediate) {
|
|
299
|
+
if (!skip(req, res)) {
|
|
300
|
+
const result = withRequestLogContext(formatFn(req, res, 0), requestContext$1);
|
|
301
|
+
if (typeof result === "string") logMethod(result, requestContext$1);
|
|
302
|
+
else logMethod("{method} {url}", result);
|
|
303
|
+
}
|
|
304
|
+
next();
|
|
305
|
+
return;
|
|
174
306
|
}
|
|
307
|
+
const logRequest = () => {
|
|
308
|
+
if (skip(req, res)) return;
|
|
309
|
+
const responseTime = Date.now() - startTime;
|
|
310
|
+
const result = withRequestLogContext(formatFn(req, res, responseTime), requestContext$1);
|
|
311
|
+
if (typeof result === "string") logMethod(result, requestContext$1);
|
|
312
|
+
else logMethod("{method} {url} {status} - {responseTime} ms", result);
|
|
313
|
+
};
|
|
314
|
+
res.on("finish", logRequest);
|
|
175
315
|
next();
|
|
316
|
+
};
|
|
317
|
+
if (contextOptions == null) {
|
|
318
|
+
handleRequest({});
|
|
176
319
|
return;
|
|
177
320
|
}
|
|
178
|
-
const
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
next();
|
|
321
|
+
const requestContext = buildRequestContext(req, res, contextOptions);
|
|
322
|
+
if (isPromiseLike(requestContext)) {
|
|
323
|
+
Promise.resolve(requestContext).then((resolvedContext) => {
|
|
324
|
+
withContext(resolvedContext, () => handleRequest(resolvedContext));
|
|
325
|
+
}, next);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
withContext(requestContext, () => handleRequest(requestContext));
|
|
187
329
|
};
|
|
188
330
|
}
|
|
189
331
|
|
package/dist/mod.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mod.js","names":["req: ExpressRequest","res: ExpressResponse","responseTime: number","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","options: ExpressLogTapeOptions","formatFn: FormatFunction","next: ExpressNextFunction"],"sources":["../src/mod.ts"],"sourcesContent":["import { getLogger, type LogLevel } from \"@logtape/logtape\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n// Use minimal type definitions for Express compatibility across Express 4.x and 5.x\n// These are compatible with both versions and avoid strict type checking issues\n\n/**\n * Minimal Express Request interface for compatibility.\n * @since 1.3.0\n */\nexport interface ExpressRequest {\n method: string;\n url: string;\n originalUrl?: string;\n path?: string;\n httpVersion: string;\n ip?: string;\n socket?: { remoteAddress?: string };\n get(header: string): string | undefined;\n}\n\n/**\n * Minimal Express Response interface for compatibility.\n * @since 1.3.0\n */\nexport interface ExpressResponse {\n statusCode: number;\n on(event: string, listener: () => void): void;\n getHeader(name: string): string | number | string[] | undefined;\n}\n\n/**\n * Express NextFunction type.\n * @since 1.3.0\n */\nexport type ExpressNextFunction = (err?: unknown) => void;\n\n/**\n * Express middleware function type.\n * @since 1.3.0\n */\nexport type ExpressMiddleware = (\n req: ExpressRequest,\n res: ExpressResponse,\n next: ExpressNextFunction,\n) => void;\n\n/**\n * Predefined log format names compatible with Morgan.\n * @since 1.3.0\n */\nexport type PredefinedFormat = \"combined\" | \"common\" | \"dev\" | \"short\" | \"tiny\";\n\n/**\n * Custom format function for request logging.\n *\n * @param req The Express request object.\n * @param res The Express response object.\n * @param responseTime The response time in milliseconds.\n * @returns A string message or an object with structured properties.\n * @since 1.3.0\n */\nexport type FormatFunction = (\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n) => string | Record<string, unknown>;\n\n/**\n * Structured log properties for HTTP requests.\n * @since 1.3.0\n */\nexport interface RequestLogProperties {\n /** HTTP request method */\n method: string;\n /** Request URL */\n url: string;\n /** HTTP response status code */\n status: number;\n /** Response time in milliseconds */\n responseTime: number;\n /** Response content-length header value */\n contentLength: string | undefined;\n /** Remote client address */\n remoteAddr: string | undefined;\n /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\n /** HTTP version (e.g., \"1.1\") */\n httpVersion: string;\n}\n\n/**\n * Options for configuring the Express LogTape middleware.\n * @since 1.3.0\n */\nexport interface ExpressLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"express\"]\n */\n readonly category?: string | readonly string[];\n\n /**\n * The log level to use for request logging.\n * @default \"info\"\n */\n readonly level?: LogLevel;\n\n /**\n * The format for log output.\n * Can be a predefined format name or a custom format function.\n *\n * Predefined formats:\n * - `\"combined\"` - Apache Combined Log Format (structured, default)\n * - `\"common\"` - Apache Common Log Format (structured, no referrer/userAgent)\n * - `\"dev\"` - Concise colored output for development (string)\n * - `\"short\"` - Shorter than common (string)\n * - `\"tiny\"` - Minimal output (string)\n *\n * @default \"combined\"\n */\n readonly format?: PredefinedFormat | FormatFunction;\n\n /**\n * Function to determine whether logging should be skipped.\n * Return `true` to skip logging for a request.\n *\n * @example Skip logging for successful requests\n * ```typescript\n * app.use(expressLogger({\n * skip: (req, res) => res.statusCode < 400,\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (req: ExpressRequest, res: ExpressResponse) => boolean;\n\n /**\n * If `true`, logs are written immediately when the request is received.\n * If `false` (default), logs are written after the response is sent.\n *\n * Note: When `immediate` is `true`, response-related properties\n * (status, responseTime, contentLength) will not be available.\n *\n * @default false\n */\n readonly immediate?: boolean;\n}\n\n/**\n * Get remote address from request.\n */\nfunction getRemoteAddr(req: ExpressRequest): string | undefined {\n return req.ip || req.socket?.remoteAddress;\n}\n\n/**\n * Get content length from response headers.\n */\nfunction getContentLength(res: ExpressResponse): string | undefined {\n const contentLength = res.getHeader(\"content-length\");\n if (contentLength === undefined || contentLength === null) return undefined;\n return String(contentLength);\n}\n\n/**\n * Get referrer from request headers.\n */\nfunction getReferrer(req: ExpressRequest): string | undefined {\n return req.get(\"referrer\") || req.get(\"referer\");\n}\n\n/**\n * Get user agent from request headers.\n */\nfunction getUserAgent(req: ExpressRequest): string | undefined {\n return req.get(\"user-agent\");\n}\n\n/**\n * Build structured log properties from request/response.\n */\nfunction buildProperties(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: req.method,\n url: req.originalUrl || req.url,\n status: res.statusCode,\n responseTime,\n contentLength: getContentLength(res),\n remoteAddr: getRemoteAddr(req),\n userAgent: getUserAgent(req),\n referrer: getReferrer(req),\n httpVersion: req.httpVersion,\n };\n}\n\n/**\n * Combined format (Apache Combined Log Format).\n * Returns all structured properties.\n */\nfunction formatCombined(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): Record<string, unknown> {\n return { ...buildProperties(req, res, responseTime) };\n}\n\n/**\n * Common format (Apache Common Log Format).\n * Like combined but without referrer and userAgent.\n */\nfunction formatCommon(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): Record<string, unknown> {\n const props = buildProperties(req, res, responseTime);\n const { referrer: _referrer, userAgent: _userAgent, ...rest } = props;\n return rest;\n}\n\n/**\n * Dev format (colored output for development).\n * :method :url :status :response-time ms - :res[content-length]\n */\nfunction formatDev(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const contentLength = getContentLength(res) ?? \"-\";\n return `${req.method} ${req.originalUrl || req.url} ${res.statusCode} ${\n responseTime.toFixed(3)\n } ms - ${contentLength}`;\n}\n\n/**\n * Short format.\n * :remote-addr :method :url HTTP/:http-version :status :res[content-length] - :response-time ms\n */\nfunction formatShort(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const remoteAddr = getRemoteAddr(req) ?? \"-\";\n const contentLength = getContentLength(res) ?? \"-\";\n return `${remoteAddr} ${req.method} ${\n req.originalUrl || req.url\n } HTTP/${req.httpVersion} ${res.statusCode} ${contentLength} - ${\n responseTime.toFixed(3)\n } ms`;\n}\n\n/**\n * Tiny format (minimal output).\n * :method :url :status :res[content-length] - :response-time ms\n */\nfunction formatTiny(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const contentLength = getContentLength(res) ?? \"-\";\n return `${req.method} ${\n req.originalUrl || req.url\n } ${res.statusCode} ${contentLength} - ${responseTime.toFixed(3)} ms`;\n}\n\n/**\n * Map of predefined format functions.\n */\nconst predefinedFormats: Record<PredefinedFormat, FormatFunction> = {\n combined: formatCombined,\n common: formatCommon,\n dev: formatDev,\n short: formatShort,\n tiny: formatTiny,\n};\n\n/**\n * Normalize category to array format.\n */\nfunction normalizeCategory(\n category: string | readonly string[],\n): readonly string[] {\n return typeof category === \"string\" ? [category] : category;\n}\n\n/**\n * Creates Express middleware for HTTP request logging using LogTape.\n *\n * This middleware provides Morgan-compatible request logging with LogTape\n * as the backend, supporting structured logging and customizable formats.\n *\n * @example Basic usage\n * ```typescript\n * import express from \"express\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { expressLogger } from \"@logtape/express\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"express\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = express();\n * app.use(expressLogger());\n *\n * app.get(\"/\", (req, res) => {\n * res.json({ hello: \"world\" });\n * });\n *\n * app.listen(3000);\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(expressLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (req, res) => res.statusCode < 400,\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(expressLogger({\n * format: (req, res, responseTime) => ({\n * method: req.method,\n * path: req.path,\n * status: res.statusCode,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the middleware.\n * @returns Express middleware function.\n * @since 1.3.0\n */\nexport function expressLogger(\n options: ExpressLogTapeOptions = {},\n): ExpressMiddleware {\n const category = normalizeCategory(options.category ?? [\"express\"]);\n const logger = getLogger(category);\n const level = options.level ?? \"info\";\n const formatOption = options.format ?? \"combined\";\n const skip = options.skip ?? (() => false);\n const immediate = options.immediate ?? false;\n\n // Resolve format function\n const formatFn: FormatFunction = typeof formatOption === \"string\"\n ? predefinedFormats[formatOption]\n : formatOption;\n\n const logMethod = logger[level].bind(logger);\n\n return (\n req: ExpressRequest,\n res: ExpressResponse,\n next: ExpressNextFunction,\n ): void => {\n const startTime = Date.now();\n\n // For immediate logging, log when request arrives\n if (immediate) {\n if (!skip(req, res)) {\n const result = formatFn(req, res, 0);\n if (typeof result === \"string\") {\n logMethod(result);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n next();\n return;\n }\n\n // Log after response is sent\n const logRequest = (): void => {\n if (skip(req, res)) return;\n\n const responseTime = Date.now() - startTime;\n const result = formatFn(req, res, responseTime);\n\n if (typeof result === \"string\") {\n logMethod(result);\n } else {\n logMethod(\"{method} {url} {status} - {responseTime} ms\", result);\n }\n };\n\n // Listen for response finish event\n res.on(\"finish\", logRequest);\n\n next();\n };\n}\n"],"mappings":";;;;;;AA4JA,SAAS,cAAcA,KAAyC;AAC9D,QAAO,IAAI,MAAM,IAAI,QAAQ;AAC9B;;;;AAKD,SAAS,iBAAiBC,KAA0C;CAClE,MAAM,gBAAgB,IAAI,UAAU,iBAAiB;AACrD,KAAI,4BAA+B,kBAAkB,KAAM;AAC3D,QAAO,OAAO,cAAc;AAC7B;;;;AAKD,SAAS,YAAYD,KAAyC;AAC5D,QAAO,IAAI,IAAI,WAAW,IAAI,IAAI,IAAI,UAAU;AACjD;;;;AAKD,SAAS,aAAaA,KAAyC;AAC7D,QAAO,IAAI,IAAI,aAAa;AAC7B;;;;AAKD,SAAS,gBACPA,KACAC,KACAC,cACsB;AACtB,QAAO;EACL,QAAQ,IAAI;EACZ,KAAK,IAAI,eAAe,IAAI;EAC5B,QAAQ,IAAI;EACZ;EACA,eAAe,iBAAiB,IAAI;EACpC,YAAY,cAAc,IAAI;EAC9B,WAAW,aAAa,IAAI;EAC5B,UAAU,YAAY,IAAI;EAC1B,aAAa,IAAI;CAClB;AACF;;;;;AAMD,SAAS,eACPF,KACAC,KACAC,cACyB;AACzB,QAAO,EAAE,GAAG,gBAAgB,KAAK,KAAK,aAAa,CAAE;AACtD;;;;;AAMD,SAAS,aACPF,KACAC,KACAC,cACyB;CACzB,MAAM,QAAQ,gBAAgB,KAAK,KAAK,aAAa;CACrD,MAAM,EAAE,UAAU,WAAW,WAAW,WAAY,GAAG,MAAM,GAAG;AAChE,QAAO;AACR;;;;;AAMD,SAAS,UACPF,KACAC,KACAC,cACQ;CACR,MAAM,gBAAgB,iBAAiB,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CACLN,KACAC,KACAM,SACS;EACT,MAAM,YAAY,KAAK,KAAK;AAG5B,MAAI,WAAW;AACb,QAAK,KAAK,KAAK,IAAI,EAAE;IACnB,MAAM,SAAS,SAAS,KAAK,KAAK,EAAE;AACpC,eAAW,WAAW,SACpB,WAAU,OAAO;QAEjB,WAAU,kBAAkB,OAAO;GAEtC;AACD,SAAM;AACN;EACD;EAGD,MAAM,aAAa,MAAY;AAC7B,OAAI,KAAK,KAAK,IAAI,CAAE;GAEpB,MAAM,eAAe,KAAK,KAAK,GAAG;GAClC,MAAM,SAAS,SAAS,KAAK,KAAK,aAAa;AAE/C,cAAW,WAAW,SACpB,WAAU,OAAO;OAEjB,WAAU,+CAA+C,OAAO;EAEnE;AAGD,MAAI,GAAG,UAAU,WAAW;AAE5B,QAAM;CACP;AACF"}
|
|
1
|
+
{"version":3,"file":"mod.js","names":["options: boolean | RequestContextOptions | undefined","options: boolean | RequestIdOptions | undefined","value: string","req: ExpressRequest","res: ExpressResponse","options: RequestIdOptions","responseHeader","resolvedRequestId: { property: string; value: string } | undefined","include: readonly RequestContextField[]","context: Record<string, unknown>","value: unknown","options: RequestContextOptions","result: string | Record<string, unknown>","responseTime: number","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","options: ExpressLogTapeOptions","formatFn: FormatFunction","next: ExpressNextFunction","requestContext: Record<string, unknown>","requestContext"],"sources":["../src/mod.ts"],"sourcesContent":["import { getLogger, type LogLevel, withContext } from \"@logtape/logtape\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n// Use minimal type definitions for Express compatibility across Express 4.x and 5.x\n// These are compatible with both versions and avoid strict type checking issues\n\n/**\n * Minimal Express Request interface for compatibility.\n * @since 1.3.0\n */\nexport interface ExpressRequest {\n method: string;\n url: string;\n originalUrl?: string;\n path?: string;\n httpVersion: string;\n ip?: string;\n socket?: { remoteAddress?: string };\n get(header: string): string | undefined;\n}\n\n/**\n * Minimal Express Response interface for compatibility.\n * @since 1.3.0\n */\nexport interface ExpressResponse {\n statusCode: number;\n on(event: string, listener: () => void): void;\n getHeader(name: string): string | number | string[] | undefined;\n setHeader?(name: string, value: string): void;\n}\n\n/**\n * Express NextFunction type.\n * @since 1.3.0\n */\nexport type ExpressNextFunction = (err?: unknown) => void;\n\n/**\n * Express middleware function type.\n * @since 1.3.0\n */\nexport type ExpressMiddleware = (\n req: ExpressRequest,\n res: ExpressResponse,\n next: ExpressNextFunction,\n) => void;\n\n/**\n * Predefined log format names compatible with Morgan.\n * @since 1.3.0\n */\nexport type PredefinedFormat = \"combined\" | \"common\" | \"dev\" | \"short\" | \"tiny\";\n\n/**\n * Custom format function for request logging.\n *\n * @param req The Express request object.\n * @param res The Express response object.\n * @param responseTime The response time in milliseconds.\n * @returns A string message or an object with structured properties.\n * @since 1.3.0\n */\nexport type FormatFunction = (\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n) => string | Record<string, unknown>;\n\n/**\n * Structured log properties for HTTP requests.\n * @since 1.3.0\n */\nexport interface RequestLogProperties {\n /** HTTP request method */\n method: string;\n /** Request URL */\n url: string;\n /** HTTP response status code */\n status: number;\n /** Response time in milliseconds */\n responseTime: number;\n /** Response content-length header value */\n contentLength: string | undefined;\n /** Remote client address */\n remoteAddr: string | undefined;\n /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\n /** HTTP version (e.g., \"1.1\") */\n httpVersion: string;\n}\n\n/**\n * Request fields that can be added to the implicit request context.\n * @since 2.2.0\n */\nexport type RequestContextField =\n | \"requestId\"\n | \"method\"\n | \"url\"\n | \"path\"\n | \"userAgent\"\n | \"remoteAddr\"\n | \"referrer\"\n | \"httpVersion\";\n\n/**\n * Options for extracting, generating, and propagating a request ID.\n * @since 2.2.0\n */\nexport interface RequestIdOptions {\n /**\n * The property name used in implicit context and request log records.\n * @default \"requestId\"\n */\n readonly property?: string;\n\n /**\n * Incoming request headers to inspect in order.\n * @default [\"x-request-id\"]\n */\n readonly headerNames?: readonly string[];\n\n /**\n * Response header that receives the resolved request ID.\n * Set to `false` to disable response header propagation.\n * @default \"x-request-id\"\n */\n readonly responseHeader?: string | false;\n\n /**\n * Generates a request ID when no incoming header is present.\n * @default crypto.randomUUID()\n */\n readonly generate?: () => string;\n\n /**\n * Normalizes an incoming request ID. Return `null` to reject the value and\n * keep looking for another header or generate a new ID.\n */\n readonly normalize?: (value: string) => string | null;\n}\n\n/**\n * Options for request-scoped implicit context.\n * @since 2.2.0\n */\nexport interface RequestContextOptions {\n /**\n * Enables request ID extraction, generation, and response propagation.\n * @default true\n */\n readonly requestId?: boolean | RequestIdOptions;\n\n /**\n * Fields to add to the implicit context.\n * @default [\"requestId\"]\n */\n readonly include?: readonly RequestContextField[];\n\n /**\n * Adds application-specific fields to the implicit request context.\n */\n readonly enrich?: (\n req: ExpressRequest,\n res: ExpressResponse,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n}\n\n/**\n * Options for configuring the Express LogTape middleware.\n * @since 1.3.0\n */\nexport interface ExpressLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"express\"]\n */\n readonly category?: string | readonly string[];\n\n /**\n * The log level to use for request logging.\n * @default \"info\"\n */\n readonly level?: LogLevel;\n\n /**\n * The format for log output.\n * Can be a predefined format name or a custom format function.\n *\n * Predefined formats:\n * - `\"combined\"` - Apache Combined Log Format (structured, default)\n * - `\"common\"` - Apache Common Log Format (structured, no referrer/userAgent)\n * - `\"dev\"` - Concise colored output for development (string)\n * - `\"short\"` - Shorter than common (string)\n * - `\"tiny\"` - Minimal output (string)\n *\n * @default \"combined\"\n */\n readonly format?: PredefinedFormat | FormatFunction;\n\n /**\n * Function to determine whether logging should be skipped.\n * Return `true` to skip logging for a request.\n *\n * @example Skip logging for successful requests\n * ```typescript\n * app.use(expressLogger({\n * skip: (req, res) => res.statusCode < 400,\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (req: ExpressRequest, res: ExpressResponse) => boolean;\n\n /**\n * If `true`, logs are written immediately when the request is received.\n * If `false` (default), logs are written after the response is sent.\n *\n * Note: When `immediate` is `true`, response-related properties\n * (status, responseTime, contentLength) will not be available.\n *\n * @default false\n */\n readonly immediate?: boolean;\n\n /**\n * Enables request-scoped implicit context and request ID correlation.\n *\n * When set to `true`, the middleware reads the `x-request-id` header,\n * generates one when it is absent, writes it to the `x-request-id` response\n * header, and adds `requestId` to all LogTape records emitted while handling\n * the request.\n *\n * @default false\n * @since 2.2.0\n */\n readonly context?: boolean | RequestContextOptions;\n}\n\nconst defaultRequestIdHeader = \"x-request-id\";\n\n/**\n * Normalize request context options.\n */\nfunction normalizeRequestContextOptions(\n options: boolean | RequestContextOptions | undefined,\n): RequestContextOptions | undefined {\n if (options === true) return {};\n if (options === false || options == null) return undefined;\n return options;\n}\n\n/**\n * Normalize request ID options.\n */\nfunction normalizeRequestIdOptions(\n options: boolean | RequestIdOptions | undefined,\n): RequestIdOptions | undefined {\n if (options === false) return undefined;\n if (options === true || options == null) return {};\n return options;\n}\n\n/**\n * Generate a request ID with Web Crypto when possible.\n */\nfunction generateRequestId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Normalize an incoming request ID.\n */\nfunction defaultNormalizeRequestId(value: string): string | null {\n const trimmed = value.trim();\n return trimmed === \"\" ? null : trimmed;\n}\n\n/**\n * Resolve the request ID for a request.\n */\nfunction resolveRequestId(\n req: ExpressRequest,\n res: ExpressResponse,\n options: RequestIdOptions,\n): { property: string; value: string } {\n const property = options.property ?? \"requestId\";\n const normalize = options.normalize ?? defaultNormalizeRequestId;\n const headerNames = options.headerNames ?? [defaultRequestIdHeader];\n for (const headerName of headerNames) {\n const headerValue = req.get(headerName);\n if (headerValue == null) continue;\n const normalized = normalize(headerValue);\n if (normalized != null) {\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n if (responseHeader !== false) res.setHeader?.(responseHeader, normalized);\n return { property, value: normalized };\n }\n }\n const generated = (options.generate ?? generateRequestId)();\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n if (responseHeader !== false) res.setHeader?.(responseHeader, generated);\n return { property, value: generated };\n}\n\n/**\n * Build request context fields from a request.\n */\nfunction buildIncludedContext(\n req: ExpressRequest,\n resolvedRequestId: { property: string; value: string } | undefined,\n include: readonly RequestContextField[],\n): Record<string, unknown> {\n const context: Record<string, unknown> = {};\n for (const field of include) {\n switch (field) {\n case \"requestId\":\n if (resolvedRequestId != null) {\n context[resolvedRequestId.property] = resolvedRequestId.value;\n }\n break;\n case \"method\":\n context.method = req.method;\n break;\n case \"url\":\n context.url = req.originalUrl || req.url;\n break;\n case \"path\":\n context.path = req.path;\n break;\n case \"userAgent\":\n context.userAgent = getUserAgent(req);\n break;\n case \"remoteAddr\":\n context.remoteAddr = getRemoteAddr(req);\n break;\n case \"referrer\":\n context.referrer = getReferrer(req);\n break;\n case \"httpVersion\":\n context.httpVersion = req.httpVersion;\n break;\n }\n }\n return context;\n}\n\n/**\n * Check whether a value is a promise-like object.\n */\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return value != null && typeof value === \"object\" &&\n typeof (value as PromiseLike<T>).then === \"function\";\n}\n\n/**\n * Build the implicit context for a request.\n */\nfunction buildRequestContext(\n req: ExpressRequest,\n res: ExpressResponse,\n options: RequestContextOptions,\n): Record<string, unknown> | Promise<Record<string, unknown>> {\n const requestIdOptions = normalizeRequestIdOptions(options.requestId);\n const resolvedRequestId = requestIdOptions == null\n ? undefined\n : resolveRequestId(req, res, requestIdOptions);\n const include = options.include ??\n (resolvedRequestId == null ? [] : [\"requestId\"] as const);\n const context = buildIncludedContext(req, resolvedRequestId, include);\n if (options.enrich == null) return context;\n const enriched = options.enrich(req, res);\n if (isPromiseLike<Record<string, unknown>>(enriched)) {\n return Promise.resolve(enriched).then((extraContext) => ({\n ...context,\n ...extraContext,\n }));\n }\n return { ...context, ...enriched };\n}\n\n/**\n * Add request context fields to a request log result.\n */\nfunction withRequestLogContext(\n result: string | Record<string, unknown>,\n context: Record<string, unknown>,\n): string | Record<string, unknown> {\n if (typeof result === \"string\") return result;\n return { ...result, ...context };\n}\n\n/**\n * Get remote address from request.\n */\nfunction getRemoteAddr(req: ExpressRequest): string | undefined {\n return req.ip || req.socket?.remoteAddress;\n}\n\n/**\n * Get content length from response headers.\n */\nfunction getContentLength(res: ExpressResponse): string | undefined {\n const contentLength = res.getHeader(\"content-length\");\n if (contentLength === undefined || contentLength === null) return undefined;\n return String(contentLength);\n}\n\n/**\n * Get referrer from request headers.\n */\nfunction getReferrer(req: ExpressRequest): string | undefined {\n return req.get(\"referrer\") || req.get(\"referer\");\n}\n\n/**\n * Get user agent from request headers.\n */\nfunction getUserAgent(req: ExpressRequest): string | undefined {\n return req.get(\"user-agent\");\n}\n\n/**\n * Build structured log properties from request/response.\n */\nfunction buildProperties(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: req.method,\n url: req.originalUrl || req.url,\n status: res.statusCode,\n responseTime,\n contentLength: getContentLength(res),\n remoteAddr: getRemoteAddr(req),\n userAgent: getUserAgent(req),\n referrer: getReferrer(req),\n httpVersion: req.httpVersion,\n };\n}\n\n/**\n * Combined format (Apache Combined Log Format).\n * Returns all structured properties.\n */\nfunction formatCombined(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): Record<string, unknown> {\n return { ...buildProperties(req, res, responseTime) };\n}\n\n/**\n * Common format (Apache Common Log Format).\n * Like combined but without referrer and userAgent.\n */\nfunction formatCommon(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): Record<string, unknown> {\n const props = buildProperties(req, res, responseTime);\n const { referrer: _referrer, userAgent: _userAgent, ...rest } = props;\n return rest;\n}\n\n/**\n * Dev format (colored output for development).\n * :method :url :status :response-time ms - :res[content-length]\n */\nfunction formatDev(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const contentLength = getContentLength(res) ?? \"-\";\n return `${req.method} ${req.originalUrl || req.url} ${res.statusCode} ${\n responseTime.toFixed(3)\n } ms - ${contentLength}`;\n}\n\n/**\n * Short format.\n * :remote-addr :method :url HTTP/:http-version :status :res[content-length] - :response-time ms\n */\nfunction formatShort(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const remoteAddr = getRemoteAddr(req) ?? \"-\";\n const contentLength = getContentLength(res) ?? \"-\";\n return `${remoteAddr} ${req.method} ${\n req.originalUrl || req.url\n } HTTP/${req.httpVersion} ${res.statusCode} ${contentLength} - ${\n responseTime.toFixed(3)\n } ms`;\n}\n\n/**\n * Tiny format (minimal output).\n * :method :url :status :res[content-length] - :response-time ms\n */\nfunction formatTiny(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const contentLength = getContentLength(res) ?? \"-\";\n return `${req.method} ${\n req.originalUrl || req.url\n } ${res.statusCode} ${contentLength} - ${responseTime.toFixed(3)} ms`;\n}\n\n/**\n * Map of predefined format functions.\n */\nconst predefinedFormats: Record<PredefinedFormat, FormatFunction> = {\n combined: formatCombined,\n common: formatCommon,\n dev: formatDev,\n short: formatShort,\n tiny: formatTiny,\n};\n\n/**\n * Normalize category to array format.\n */\nfunction normalizeCategory(\n category: string | readonly string[],\n): readonly string[] {\n return typeof category === \"string\" ? [category] : category;\n}\n\n/**\n * Creates Express middleware for HTTP request logging using LogTape.\n *\n * This middleware provides Morgan-compatible request logging with LogTape\n * as the backend, supporting structured logging and customizable formats.\n *\n * @example Basic usage\n * ```typescript\n * import express from \"express\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { expressLogger } from \"@logtape/express\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"express\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = express();\n * app.use(expressLogger());\n *\n * app.get(\"/\", (req, res) => {\n * res.json({ hello: \"world\" });\n * });\n *\n * app.listen(3000);\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(expressLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (req, res) => res.statusCode < 400,\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(expressLogger({\n * format: (req, res, responseTime) => ({\n * method: req.method,\n * path: req.path,\n * status: res.statusCode,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the middleware.\n * @returns Express middleware function.\n * @since 1.3.0\n */\nexport function expressLogger(\n options: ExpressLogTapeOptions = {},\n): ExpressMiddleware {\n const category = normalizeCategory(options.category ?? [\"express\"]);\n const logger = getLogger(category);\n const level = options.level ?? \"info\";\n const formatOption = options.format ?? \"combined\";\n const skip = options.skip ?? (() => false);\n const immediate = options.immediate ?? false;\n const contextOptions = normalizeRequestContextOptions(options.context);\n\n // Resolve format function\n const formatFn: FormatFunction = typeof formatOption === \"string\"\n ? predefinedFormats[formatOption]\n : formatOption;\n\n const logMethod = logger[level].bind(logger);\n\n return (\n req: ExpressRequest,\n res: ExpressResponse,\n next: ExpressNextFunction,\n ): void => {\n const startTime = Date.now();\n\n const handleRequest = (requestContext: Record<string, unknown>): void => {\n // For immediate logging, log when request arrives\n if (immediate) {\n if (!skip(req, res)) {\n const result = withRequestLogContext(\n formatFn(req, res, 0),\n requestContext,\n );\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n next();\n return;\n }\n\n // Log after response is sent\n const logRequest = (): void => {\n if (skip(req, res)) return;\n\n const responseTime = Date.now() - startTime;\n const result = withRequestLogContext(\n formatFn(req, res, responseTime),\n requestContext,\n );\n\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url} {status} - {responseTime} ms\", result);\n }\n };\n\n // Listen for response finish event\n res.on(\"finish\", logRequest);\n\n next();\n };\n\n if (contextOptions == null) {\n handleRequest({});\n return;\n }\n\n const requestContext = buildRequestContext(req, res, contextOptions);\n if (isPromiseLike<Record<string, unknown>>(requestContext)) {\n Promise.resolve(requestContext).then((resolvedContext) => {\n withContext(resolvedContext, () => handleRequest(resolvedContext));\n }, next);\n return;\n }\n\n withContext(requestContext, () => handleRequest(requestContext));\n };\n}\n"],"mappings":";;;AAoPA,MAAM,yBAAyB;;;;AAK/B,SAAS,+BACPA,SACmC;AACnC,KAAI,YAAY,KAAM,QAAO,CAAE;AAC/B,KAAI,YAAY,SAAS,WAAW,KAAM;AAC1C,QAAO;AACR;;;;AAKD,SAAS,0BACPC,SAC8B;AAC9B,KAAI,YAAY,MAAO;AACvB,KAAI,YAAY,QAAQ,WAAW,KAAM,QAAO,CAAE;AAClD,QAAO;AACR;;;;AAKD,SAAS,oBAA4B;AACnC,YAAW,WAAW,QAAQ,eAAe,WAC3C,QAAO,WAAW,OAAO,YAAY;AAEvC,SAAQ,EAAE,KAAK,KAAK,CAAC,SAAS,GAAG,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,CAAC;AAC1E;;;;AAKD,SAAS,0BAA0BC,OAA8B;CAC/D,MAAM,UAAU,MAAM,MAAM;AAC5B,QAAO,YAAY,KAAK,OAAO;AAChC;;;;AAKD,SAAS,iBACPC,KACAC,KACAC,SACqC;CACrC,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,cAAc,QAAQ,eAAe,CAAC,sBAAuB;AACnE,MAAK,MAAM,cAAc,aAAa;EACpC,MAAM,cAAc,IAAI,IAAI,WAAW;AACvC,MAAI,eAAe,KAAM;EACzB,MAAM,aAAa,UAAU,YAAY;AACzC,MAAI,cAAc,MAAM;GACtB,MAAMC,mBAAiB,QAAQ,kBAAkB;AACjD,OAAIA,qBAAmB,MAAO,KAAI,YAAYA,kBAAgB,WAAW;AACzE,UAAO;IAAE;IAAU,OAAO;GAAY;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c,SACS;EACT,MAAM,YAAY,KAAK,KAAK;EAE5B,MAAM,gBAAgB,CAACC,qBAAkD;AAEvE,OAAI,WAAW;AACb,SAAK,KAAK,KAAK,IAAI,EAAE;KACnB,MAAM,SAAS,sBACb,SAAS,KAAK,KAAK,EAAE,EACrBC,iBACD;AACD,gBAAW,WAAW,SACpB,WAAU,QAAQA,iBAAe;SAEjC,WAAU,kBAAkB,OAAO;IAEtC;AACD,UAAM;AACN;GACD;GAGD,MAAM,aAAa,MAAY;AAC7B,QAAI,KAAK,KAAK,IAAI,CAAE;IAEpB,MAAM,eAAe,KAAK,KAAK,GAAG;IAClC,MAAM,SAAS,sBACb,SAAS,KAAK,KAAK,aAAa,EAChCA,iBACD;AAED,eAAW,WAAW,SACpB,WAAU,QAAQA,iBAAe;QAEjC,WAAU,+CAA+C,OAAO;GAEnE;AAGD,OAAI,GAAG,UAAU,WAAW;AAE5B,SAAM;EACP;AAED,MAAI,kBAAkB,MAAM;AAC1B,iBAAc,CAAE,EAAC;AACjB;EACD;EAED,MAAM,iBAAiB,oBAAoB,KAAK,KAAK,eAAe;AACpE,MAAI,cAAuC,eAAe,EAAE;AAC1D,WAAQ,QAAQ,eAAe,CAAC,KAAK,CAAC,oBAAoB;AACxD,gBAAY,iBAAiB,MAAM,cAAc,gBAAgB,CAAC;GACnE,GAAE,KAAK;AACR;EACD;AAED,cAAY,gBAAgB,MAAM,cAAc,eAAe,CAAC;CACjE;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@logtape/express",
|
|
3
|
-
"version": "2.2.0-dev.
|
|
3
|
+
"version": "2.2.0-dev.686+61fa5e1a",
|
|
4
4
|
"description": "Express adapter for LogTape logging library",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"logging",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
],
|
|
54
54
|
"peerDependencies": {
|
|
55
55
|
"express": "^4.0.0 || ^5.0.0",
|
|
56
|
-
"@logtape/logtape": "^2.2.0-dev.
|
|
56
|
+
"@logtape/logtape": "^2.2.0-dev.686+61fa5e1a"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
59
|
"@alinea/suite": "^0.6.3",
|