@logtape/elysia 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 CHANGED
@@ -66,6 +66,51 @@ app.use(elysiaLogger({
66
66
  skip: (ctx) => ctx.path === "/health", // Skip logging for specific paths
67
67
  logRequest: true, // Log at request start (default: false)
68
68
  scope: "global", // Plugin scope (default: "global")
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 plugin reads the `x-request-id` request header, generates an ID when the
79
+ header is missing, writes the resolved ID to the `x-request-id` response
80
+ header, and adds `requestId` to request and error log records.
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
+ new Elysia()
95
+ .use(elysiaLogger({ context: true }))
96
+ .get("/", () => ({ hello: "world" }));
97
+ ~~~~
98
+
99
+ The context is still established when `skip` suppresses the request log, so
100
+ application logs inside the skipped request can keep the same request ID.
101
+
102
+ You can customize request ID headers and add more request fields:
103
+
104
+ ~~~~ typescript
105
+ app.use(elysiaLogger({
106
+ context: {
107
+ requestId: {
108
+ headerNames: ["x-correlation-id", "x-request-id"],
109
+ responseHeader: "x-request-id",
110
+ },
111
+ include: ["requestId", "method", "path", "userAgent"],
112
+ enrich: (ctx) => ({ route: ctx.path }),
113
+ },
69
114
  }));
70
115
  ~~~~
71
116
 
package/dist/mod.cjs CHANGED
@@ -3,6 +3,71 @@ const elysia = require_rolldown_runtime.__toESM(require("elysia"));
3
3
  const __logtape_logtape = require_rolldown_runtime.__toESM(require("@logtape/logtape"));
4
4
 
5
5
  //#region src/mod.ts
6
+ const defaultRequestIdHeader = "x-request-id";
7
+ /**
8
+ * Normalize request context options.
9
+ */
10
+ function normalizeRequestContextOptions(options) {
11
+ if (options === true) return {};
12
+ if (options === false || options == null) return void 0;
13
+ return options;
14
+ }
15
+ /**
16
+ * Normalize request ID options.
17
+ */
18
+ function normalizeRequestIdOptions(options) {
19
+ if (options === false) return void 0;
20
+ if (options === true || options == null) return {};
21
+ return options;
22
+ }
23
+ /**
24
+ * Generate a request ID with Web Crypto when possible.
25
+ */
26
+ function generateRequestId() {
27
+ if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
28
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
29
+ }
30
+ /**
31
+ * Normalize an incoming request ID.
32
+ */
33
+ function defaultNormalizeRequestId(value) {
34
+ const trimmed = value.trim();
35
+ return trimmed === "" ? null : trimmed;
36
+ }
37
+ /**
38
+ * Resolve a request path from a request URL.
39
+ */
40
+ function getPath(request) {
41
+ return new URL(request.url).pathname;
42
+ }
43
+ /**
44
+ * Resolve the request ID for a request.
45
+ */
46
+ function resolveRequestId(request, options) {
47
+ const property = options.property ?? "requestId";
48
+ const normalize = options.normalize ?? defaultNormalizeRequestId;
49
+ const headerNames = options.headerNames ?? [defaultRequestIdHeader];
50
+ for (const headerName of headerNames) {
51
+ const headerValue = request.headers.get(headerName);
52
+ if (headerValue == null) continue;
53
+ const normalized = normalize(headerValue);
54
+ if (normalized != null) {
55
+ const responseHeader$1 = options.responseHeader ?? defaultRequestIdHeader;
56
+ return {
57
+ property,
58
+ value: normalized,
59
+ responseHeader: responseHeader$1 === false ? void 0 : responseHeader$1
60
+ };
61
+ }
62
+ }
63
+ const generated = (options.generate ?? generateRequestId)();
64
+ const responseHeader = options.responseHeader ?? defaultRequestIdHeader;
65
+ return {
66
+ property,
67
+ value: generated,
68
+ responseHeader: responseHeader === false ? void 0 : responseHeader
69
+ };
70
+ }
6
71
  /**
7
72
  * Get referrer from request headers.
8
73
  */
@@ -27,6 +92,64 @@ function getRemoteAddr(request) {
27
92
  return void 0;
28
93
  }
29
94
  /**
95
+ * Build request context fields from a request.
96
+ */
97
+ function buildIncludedContext(request, resolvedRequestId, include) {
98
+ const context = {};
99
+ for (const field of include) switch (field) {
100
+ case "requestId":
101
+ if (resolvedRequestId != null) context[resolvedRequestId.property] = resolvedRequestId.value;
102
+ break;
103
+ case "method":
104
+ context.method = request.method;
105
+ break;
106
+ case "url":
107
+ context.url = request.url;
108
+ break;
109
+ case "path":
110
+ context.path = getPath(request);
111
+ break;
112
+ case "userAgent":
113
+ context.userAgent = getUserAgent(request);
114
+ break;
115
+ case "remoteAddr":
116
+ context.remoteAddr = getRemoteAddr(request);
117
+ break;
118
+ case "referrer":
119
+ context.referrer = getReferrer(request);
120
+ break;
121
+ }
122
+ return context;
123
+ }
124
+ /**
125
+ * Build the implicit context for a request.
126
+ */
127
+ async function buildRequestContext(request, options) {
128
+ const requestIdOptions = normalizeRequestIdOptions(options.requestId);
129
+ const resolvedRequestId = requestIdOptions == null ? void 0 : resolveRequestId(request, requestIdOptions);
130
+ const include = options.include ?? (resolvedRequestId == null ? [] : ["requestId"]);
131
+ const context = buildIncludedContext(request, resolvedRequestId, include);
132
+ if (options.enrich != null) {
133
+ const set = {
134
+ status: 200,
135
+ headers: {}
136
+ };
137
+ Object.assign(context, await options.enrich({
138
+ request,
139
+ path: getPath(request),
140
+ set
141
+ }));
142
+ }
143
+ const responseHeader = resolvedRequestId?.responseHeader == null ? void 0 : {
144
+ name: resolvedRequestId.responseHeader,
145
+ value: resolvedRequestId.value
146
+ };
147
+ return {
148
+ context,
149
+ responseHeader
150
+ };
151
+ }
152
+ /**
30
153
  * Get content length from response headers.
31
154
  */
32
155
  function getContentLength(headers) {
@@ -51,6 +174,16 @@ function buildProperties(ctx, responseTime) {
51
174
  };
52
175
  }
53
176
  /**
177
+ * Add request context fields to a request log result.
178
+ */
179
+ function withRequestLogContext(result, context) {
180
+ if (typeof result === "string") return result;
181
+ return {
182
+ ...result,
183
+ ...context
184
+ };
185
+ }
186
+ /**
54
187
  * Combined format (Apache Combined Log Format).
55
188
  * Returns all structured properties.
56
189
  */
@@ -188,19 +321,45 @@ function elysiaLogger(options = {}) {
188
321
  const skip = options.skip ?? (() => false);
189
322
  const logRequest = options.logRequest ?? false;
190
323
  const scope = options.scope ?? "global";
324
+ const contextOptions = normalizeRequestContextOptions(options.context);
325
+ const requestContextStates = /* @__PURE__ */ new WeakMap();
326
+ const shouldWrapContext = contextOptions != null && scope !== "local";
191
327
  const formatFn = typeof formatOption === "string" ? predefinedFormats[formatOption] : formatOption;
192
328
  const logMethod = logger[level].bind(logger);
193
329
  const errorLogMethod = logger.error.bind(logger);
194
330
  let plugin = new elysia.Elysia({
195
331
  name: "@logtape/elysia",
196
332
  seed: options
197
- }).state("startTime", 0).onRequest(({ store }) => {
198
- store.startTime = performance.now();
333
+ });
334
+ if (shouldWrapContext) plugin = plugin.wrap((handle) => {
335
+ return async (request) => {
336
+ const startTime = performance.now();
337
+ const requestContext = await buildRequestContext(request, contextOptions);
338
+ requestContextStates.set(request, {
339
+ ...requestContext,
340
+ startTime
341
+ });
342
+ return await (0, __logtape_logtape.withContext)(requestContext.context, () => handle(request));
343
+ };
344
+ });
345
+ plugin = plugin.state("startTime", 0).onRequest(async ({ request, set, store }) => {
346
+ let requestContext = requestContextStates.get(request);
347
+ if (requestContext == null && shouldWrapContext) {
348
+ const startTime = performance.now();
349
+ requestContext = {
350
+ ...await buildRequestContext(request, contextOptions),
351
+ startTime
352
+ };
353
+ requestContextStates.set(request, requestContext);
354
+ }
355
+ store.startTime = requestContext?.startTime ?? performance.now();
356
+ if (requestContext?.responseHeader != null) set.headers[requestContext.responseHeader.name] = requestContext.responseHeader.value;
199
357
  });
200
358
  if (logRequest) plugin = plugin.onRequest((ctx) => {
201
359
  if (!skip(ctx)) {
202
- const result = formatFn(ctx, 0);
203
- if (typeof result === "string") logMethod(result);
360
+ const requestContext = requestContextStates.get(ctx.request)?.context ?? {};
361
+ const result = withRequestLogContext(formatFn(ctx, 0), requestContext);
362
+ if (typeof result === "string") logMethod(result, requestContext);
204
363
  else logMethod("{method} {url}", result);
205
364
  }
206
365
  });
@@ -208,8 +367,9 @@ function elysiaLogger(options = {}) {
208
367
  if (skip(ctx)) return;
209
368
  const store = ctx.store;
210
369
  const responseTime = performance.now() - store.startTime;
211
- const result = formatFn(ctx, responseTime);
212
- if (typeof result === "string") logMethod(result);
370
+ const requestContext = requestContextStates.get(ctx.request)?.context ?? {};
371
+ const result = withRequestLogContext(formatFn(ctx, responseTime), requestContext);
372
+ if (typeof result === "string") logMethod(result, requestContext);
213
373
  else logMethod("{method} {url} {status} - {responseTime} ms", result);
214
374
  });
215
375
  plugin = plugin.onError((ctx) => {
@@ -218,11 +378,13 @@ function elysiaLogger(options = {}) {
218
378
  const elysiaCtx = ctx;
219
379
  if (skip(elysiaCtx)) return;
220
380
  const props = buildProperties(elysiaCtx, responseTime);
381
+ const requestContext = requestContextStates.get(ctx.request)?.context ?? {};
221
382
  const status = getErrorStatus(ctx.code, ctx.error, elysiaCtx.set.status);
222
383
  const error = ctx.error;
223
384
  const errorMessage = error?.message ?? "Unknown error";
224
385
  errorLogMethod("Error: {method} {url} {status} - {responseTime} ms - {errorMessage}", {
225
386
  ...props,
387
+ ...requestContext,
226
388
  status,
227
389
  errorMessage,
228
390
  errorCode: ctx.code
package/dist/mod.d.cts CHANGED
@@ -58,6 +58,63 @@ interface RequestLogProperties {
58
58
  /** Referrer header value */
59
59
  referrer: string | undefined;
60
60
  }
61
+ /**
62
+ * Request fields that can be added to the implicit request context.
63
+ * @since 2.2.0
64
+ */
65
+ type RequestContextField = "requestId" | "method" | "url" | "path" | "userAgent" | "remoteAddr" | "referrer";
66
+ /**
67
+ * Options for extracting, generating, and propagating a request ID.
68
+ * @since 2.2.0
69
+ */
70
+ interface RequestIdOptions {
71
+ /**
72
+ * The property name used in implicit context and request log records.
73
+ * @default "requestId"
74
+ */
75
+ readonly property?: string;
76
+ /**
77
+ * Incoming request headers to inspect in order.
78
+ * @default ["x-request-id"]
79
+ */
80
+ readonly headerNames?: readonly string[];
81
+ /**
82
+ * Response header that receives the resolved request ID.
83
+ * Set to `false` to disable response header propagation.
84
+ * @default "x-request-id"
85
+ */
86
+ readonly responseHeader?: string | false;
87
+ /**
88
+ * Generates a request ID when no incoming header is present.
89
+ * @default crypto.randomUUID()
90
+ */
91
+ readonly generate?: () => string;
92
+ /**
93
+ * Normalizes an incoming request ID. Return `null` to reject the value and
94
+ * keep looking for another header or generate a new ID.
95
+ */
96
+ readonly normalize?: (value: string) => string | null;
97
+ }
98
+ /**
99
+ * Options for request-scoped implicit context.
100
+ * @since 2.2.0
101
+ */
102
+ interface RequestContextOptions {
103
+ /**
104
+ * Enables request ID extraction, generation, and response propagation.
105
+ * @default true
106
+ */
107
+ readonly requestId?: boolean | RequestIdOptions;
108
+ /**
109
+ * Fields to add to the implicit context.
110
+ * @default ["requestId"]
111
+ */
112
+ readonly include?: readonly RequestContextField[];
113
+ /**
114
+ * Adds application-specific fields to the implicit request context.
115
+ */
116
+ readonly enrich?: (ctx: ElysiaContext) => Record<string, unknown> | Promise<Record<string, unknown>>;
117
+ }
61
118
  /**
62
119
  * Options for configuring the Elysia LogTape middleware.
63
120
  * @since 2.0.0
@@ -121,6 +178,18 @@ interface ElysiaLogTapeOptions {
121
178
  * @default "global"
122
179
  */
123
180
  readonly scope?: PluginScope;
181
+ /**
182
+ * Enables request-scoped implicit context and request ID correlation.
183
+ *
184
+ * When set to `true`, the plugin reads the `x-request-id` header, generates
185
+ * one when it is absent, writes it to the `x-request-id` response header,
186
+ * and adds `requestId` to all LogTape records emitted while handling the
187
+ * request.
188
+ *
189
+ * @default false
190
+ * @since 2.2.0
191
+ */
192
+ readonly context?: boolean | RequestContextOptions;
124
193
  }
125
194
  /**
126
195
  * Creates Elysia plugin for HTTP request logging using LogTape.
@@ -177,5 +246,5 @@ interface ElysiaLogTapeOptions {
177
246
  declare function elysiaLogger(options?: ElysiaLogTapeOptions): Elysia<any>;
178
247
  //# sourceMappingURL=mod.d.ts.map
179
248
  //#endregion
180
- export { ElysiaContext, ElysiaLogTapeOptions, FormatFunction, LogLevel, PluginScope, PredefinedFormat, RequestLogProperties, elysiaLogger };
249
+ export { ElysiaContext, ElysiaLogTapeOptions, FormatFunction, LogLevel, PluginScope, PredefinedFormat, RequestContextField, RequestContextOptions, RequestIdOptions, RequestLogProperties, elysiaLogger };
181
250
  //# sourceMappingURL=mod.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"mod.d.cts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;;AASA;;;AAKa,UALI,aAAA,CAKJ;EAAM,OAAA,EAJR,OAIQ;EAQP,IAAA,EAAA,MAAA;EAMA,GAAA,EAAA;IAUA,MAAA,EAAA,MAAc;IAAA,OAAA,EAxBb,MAwBa,CAAA,MAAA,EAAA,MAAA,GAAA,SAAA,CAAA;EAAA,CAAA;;AAGN;AAMpB;AAyBA;;AAWmB,KA7DP,WAAA,GA6DO,QAAA,GAAA,QAAA,GAAA,OAAA;;;;;AAoDW,KA3GlB,gBAAA,GA2GkB,UAAA,GAAA,QAAA,GAAA,KAAA,GAAA,OAAA,GAAA,MAAA;AAmP9B;;;;AAAwE;;;;KApV5D,cAAA,SACL,iDAEO;;;;;UAMG,oBAAA;;;;;;;;;;;;;;;;;;;;;;;;UAyBA,oBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;oBAeC,mBAAmB;;;;;;;;;;;;;;wBAef;;;;;;;;;;;;;;;;;;;;mBAsBL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmPH,YAAA,WAAsB,uBAA4B"}
1
+ {"version":3,"file":"mod.d.cts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;;AASA;;;AAKa,UALI,aAAA,CAKJ;EAAM,OAAA,EAJR,OAIQ;EAQP,IAAA,EAAA,MAAA;EAMA,GAAA,EAAA;IAUA,MAAA,EAAA,MAAc;IAAA,OAAA,EAxBb,MAwBa,CAAA,MAAA,EAAA,MAAA,GAAA,SAAA,CAAA;EAAA,CAAA;;AAGN;AAMpB;AAyBA;AAaA;AAqCiB,KApGL,WAAA,GAoGK,QAAqB,GAAA,QAAA,GAAA,OAAA;;;;;AAkB/B,KAhHK,gBAAA,GAgHL,UAAA,GAAA,QAAA,GAAA,KAAA,GAAA,OAAA,GAAA,MAAA;;;AAAiC;AAOxC;;;;;AAyCwB,KAtJZ,cAAA,GAsJY,CAAA,GAAA,EArJjB,aAqJiB,EAAA,YAAA,EAAA,MAAA,EAAA,GAAA,MAAA,GAnJV,MAmJU,CAAA,MAAA,EAAA,OAAA,CAAA;;;AAmC4B;AA0apD;AAA4B,UA1lBX,oBAAA,CA0lBW;EAAA;EAAmC,MAAG,EAAA,MAAA;EAAM;;;;;;;;;;;;;;;;;;;;;KAjkB5D,mBAAA;;;;;UAaK,gBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAqCA,qBAAA;;;;;iCAKgB;;;;;8BAMH;;;;0BAMrB,kBACF,0BAA0B,QAAQ;;;;;;UAOxB,oBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;oBAeC,mBAAmB;;;;;;;;;;;;;;wBAef;;;;;;;;;;;;;;;;;;;;mBAsBL;;;;;;;;;;;;+BAaY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0af,YAAA,WAAsB,uBAA4B"}
package/dist/mod.d.ts CHANGED
@@ -58,6 +58,63 @@ interface RequestLogProperties {
58
58
  /** Referrer header value */
59
59
  referrer: string | undefined;
60
60
  }
61
+ /**
62
+ * Request fields that can be added to the implicit request context.
63
+ * @since 2.2.0
64
+ */
65
+ type RequestContextField = "requestId" | "method" | "url" | "path" | "userAgent" | "remoteAddr" | "referrer";
66
+ /**
67
+ * Options for extracting, generating, and propagating a request ID.
68
+ * @since 2.2.0
69
+ */
70
+ interface RequestIdOptions {
71
+ /**
72
+ * The property name used in implicit context and request log records.
73
+ * @default "requestId"
74
+ */
75
+ readonly property?: string;
76
+ /**
77
+ * Incoming request headers to inspect in order.
78
+ * @default ["x-request-id"]
79
+ */
80
+ readonly headerNames?: readonly string[];
81
+ /**
82
+ * Response header that receives the resolved request ID.
83
+ * Set to `false` to disable response header propagation.
84
+ * @default "x-request-id"
85
+ */
86
+ readonly responseHeader?: string | false;
87
+ /**
88
+ * Generates a request ID when no incoming header is present.
89
+ * @default crypto.randomUUID()
90
+ */
91
+ readonly generate?: () => string;
92
+ /**
93
+ * Normalizes an incoming request ID. Return `null` to reject the value and
94
+ * keep looking for another header or generate a new ID.
95
+ */
96
+ readonly normalize?: (value: string) => string | null;
97
+ }
98
+ /**
99
+ * Options for request-scoped implicit context.
100
+ * @since 2.2.0
101
+ */
102
+ interface RequestContextOptions {
103
+ /**
104
+ * Enables request ID extraction, generation, and response propagation.
105
+ * @default true
106
+ */
107
+ readonly requestId?: boolean | RequestIdOptions;
108
+ /**
109
+ * Fields to add to the implicit context.
110
+ * @default ["requestId"]
111
+ */
112
+ readonly include?: readonly RequestContextField[];
113
+ /**
114
+ * Adds application-specific fields to the implicit request context.
115
+ */
116
+ readonly enrich?: (ctx: ElysiaContext) => Record<string, unknown> | Promise<Record<string, unknown>>;
117
+ }
61
118
  /**
62
119
  * Options for configuring the Elysia LogTape middleware.
63
120
  * @since 2.0.0
@@ -121,6 +178,18 @@ interface ElysiaLogTapeOptions {
121
178
  * @default "global"
122
179
  */
123
180
  readonly scope?: PluginScope;
181
+ /**
182
+ * Enables request-scoped implicit context and request ID correlation.
183
+ *
184
+ * When set to `true`, the plugin reads the `x-request-id` header, generates
185
+ * one when it is absent, writes it to the `x-request-id` response header,
186
+ * and adds `requestId` to all LogTape records emitted while handling the
187
+ * request.
188
+ *
189
+ * @default false
190
+ * @since 2.2.0
191
+ */
192
+ readonly context?: boolean | RequestContextOptions;
124
193
  }
125
194
  /**
126
195
  * Creates Elysia plugin for HTTP request logging using LogTape.
@@ -177,5 +246,5 @@ interface ElysiaLogTapeOptions {
177
246
  declare function elysiaLogger(options?: ElysiaLogTapeOptions): Elysia<any>;
178
247
  //# sourceMappingURL=mod.d.ts.map
179
248
  //#endregion
180
- export { ElysiaContext, ElysiaLogTapeOptions, FormatFunction, LogLevel, PluginScope, PredefinedFormat, RequestLogProperties, elysiaLogger };
249
+ export { ElysiaContext, ElysiaLogTapeOptions, FormatFunction, LogLevel, PluginScope, PredefinedFormat, RequestContextField, RequestContextOptions, RequestIdOptions, RequestLogProperties, elysiaLogger };
181
250
  //# 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":";;;;;;AASA;;;AAKa,UALI,aAAA,CAKJ;EAAM,OAAA,EAJR,OAIQ;EAQP,IAAA,EAAA,MAAA;EAMA,GAAA,EAAA;IAUA,MAAA,EAAA,MAAc;IAAA,OAAA,EAxBb,MAwBa,CAAA,MAAA,EAAA,MAAA,GAAA,SAAA,CAAA;EAAA,CAAA;;AAGN;AAMpB;AAyBA;;AAWmB,KA7DP,WAAA,GA6DO,QAAA,GAAA,QAAA,GAAA,OAAA;;;;;AAoDW,KA3GlB,gBAAA,GA2GkB,UAAA,GAAA,QAAA,GAAA,KAAA,GAAA,OAAA,GAAA,MAAA;AAmP9B;;;;AAAwE;;;;KApV5D,cAAA,SACL,iDAEO;;;;;UAMG,oBAAA;;;;;;;;;;;;;;;;;;;;;;;;UAyBA,oBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;oBAeC,mBAAmB;;;;;;;;;;;;;;wBAef;;;;;;;;;;;;;;;;;;;;mBAsBL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmPH,YAAA,WAAsB,uBAA4B"}
1
+ {"version":3,"file":"mod.d.ts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;;AASA;;;AAKa,UALI,aAAA,CAKJ;EAAM,OAAA,EAJR,OAIQ;EAQP,IAAA,EAAA,MAAA;EAMA,GAAA,EAAA;IAUA,MAAA,EAAA,MAAc;IAAA,OAAA,EAxBb,MAwBa,CAAA,MAAA,EAAA,MAAA,GAAA,SAAA,CAAA;EAAA,CAAA;;AAGN;AAMpB;AAyBA;AAaA;AAqCiB,KApGL,WAAA,GAoGK,QAAqB,GAAA,QAAA,GAAA,OAAA;;;;;AAkB/B,KAhHK,gBAAA,GAgHL,UAAA,GAAA,QAAA,GAAA,KAAA,GAAA,OAAA,GAAA,MAAA;;;AAAiC;AAOxC;;;;;AAyCwB,KAtJZ,cAAA,GAsJY,CAAA,GAAA,EArJjB,aAqJiB,EAAA,YAAA,EAAA,MAAA,EAAA,GAAA,MAAA,GAnJV,MAmJU,CAAA,MAAA,EAAA,OAAA,CAAA;;;AAmC4B;AA0apD;AAA4B,UA1lBX,oBAAA,CA0lBW;EAAA;EAAmC,MAAG,EAAA,MAAA;EAAM;;;;;;;;;;;;;;;;;;;;;KAjkB5D,mBAAA;;;;;UAaK,gBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAqCA,qBAAA;;;;;iCAKgB;;;;;8BAMH;;;;0BAMrB,kBACF,0BAA0B,QAAQ;;;;;;UAOxB,oBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;oBAeC,mBAAmB;;;;;;;;;;;;;;wBAef;;;;;;;;;;;;;;;;;;;;mBAsBL;;;;;;;;;;;;+BAaY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0af,YAAA,WAAsB,uBAA4B"}
package/dist/mod.js CHANGED
@@ -1,7 +1,72 @@
1
1
  import { Elysia } from "elysia";
2
- import { getLogger } from "@logtape/logtape";
2
+ import { getLogger, withContext } from "@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 a request path from a request URL.
38
+ */
39
+ function getPath(request) {
40
+ return new URL(request.url).pathname;
41
+ }
42
+ /**
43
+ * Resolve the request ID for a request.
44
+ */
45
+ function resolveRequestId(request, options) {
46
+ const property = options.property ?? "requestId";
47
+ const normalize = options.normalize ?? defaultNormalizeRequestId;
48
+ const headerNames = options.headerNames ?? [defaultRequestIdHeader];
49
+ for (const headerName of headerNames) {
50
+ const headerValue = request.headers.get(headerName);
51
+ if (headerValue == null) continue;
52
+ const normalized = normalize(headerValue);
53
+ if (normalized != null) {
54
+ const responseHeader$1 = options.responseHeader ?? defaultRequestIdHeader;
55
+ return {
56
+ property,
57
+ value: normalized,
58
+ responseHeader: responseHeader$1 === false ? void 0 : responseHeader$1
59
+ };
60
+ }
61
+ }
62
+ const generated = (options.generate ?? generateRequestId)();
63
+ const responseHeader = options.responseHeader ?? defaultRequestIdHeader;
64
+ return {
65
+ property,
66
+ value: generated,
67
+ responseHeader: responseHeader === false ? void 0 : responseHeader
68
+ };
69
+ }
5
70
  /**
6
71
  * Get referrer from request headers.
7
72
  */
@@ -26,6 +91,64 @@ function getRemoteAddr(request) {
26
91
  return void 0;
27
92
  }
28
93
  /**
94
+ * Build request context fields from a request.
95
+ */
96
+ function buildIncludedContext(request, resolvedRequestId, include) {
97
+ const context = {};
98
+ for (const field of include) switch (field) {
99
+ case "requestId":
100
+ if (resolvedRequestId != null) context[resolvedRequestId.property] = resolvedRequestId.value;
101
+ break;
102
+ case "method":
103
+ context.method = request.method;
104
+ break;
105
+ case "url":
106
+ context.url = request.url;
107
+ break;
108
+ case "path":
109
+ context.path = getPath(request);
110
+ break;
111
+ case "userAgent":
112
+ context.userAgent = getUserAgent(request);
113
+ break;
114
+ case "remoteAddr":
115
+ context.remoteAddr = getRemoteAddr(request);
116
+ break;
117
+ case "referrer":
118
+ context.referrer = getReferrer(request);
119
+ break;
120
+ }
121
+ return context;
122
+ }
123
+ /**
124
+ * Build the implicit context for a request.
125
+ */
126
+ async function buildRequestContext(request, options) {
127
+ const requestIdOptions = normalizeRequestIdOptions(options.requestId);
128
+ const resolvedRequestId = requestIdOptions == null ? void 0 : resolveRequestId(request, requestIdOptions);
129
+ const include = options.include ?? (resolvedRequestId == null ? [] : ["requestId"]);
130
+ const context = buildIncludedContext(request, resolvedRequestId, include);
131
+ if (options.enrich != null) {
132
+ const set = {
133
+ status: 200,
134
+ headers: {}
135
+ };
136
+ Object.assign(context, await options.enrich({
137
+ request,
138
+ path: getPath(request),
139
+ set
140
+ }));
141
+ }
142
+ const responseHeader = resolvedRequestId?.responseHeader == null ? void 0 : {
143
+ name: resolvedRequestId.responseHeader,
144
+ value: resolvedRequestId.value
145
+ };
146
+ return {
147
+ context,
148
+ responseHeader
149
+ };
150
+ }
151
+ /**
29
152
  * Get content length from response headers.
30
153
  */
31
154
  function getContentLength(headers) {
@@ -50,6 +173,16 @@ function buildProperties(ctx, responseTime) {
50
173
  };
51
174
  }
52
175
  /**
176
+ * Add request context fields to a request log result.
177
+ */
178
+ function withRequestLogContext(result, context) {
179
+ if (typeof result === "string") return result;
180
+ return {
181
+ ...result,
182
+ ...context
183
+ };
184
+ }
185
+ /**
53
186
  * Combined format (Apache Combined Log Format).
54
187
  * Returns all structured properties.
55
188
  */
@@ -187,19 +320,45 @@ function elysiaLogger(options = {}) {
187
320
  const skip = options.skip ?? (() => false);
188
321
  const logRequest = options.logRequest ?? false;
189
322
  const scope = options.scope ?? "global";
323
+ const contextOptions = normalizeRequestContextOptions(options.context);
324
+ const requestContextStates = /* @__PURE__ */ new WeakMap();
325
+ const shouldWrapContext = contextOptions != null && scope !== "local";
190
326
  const formatFn = typeof formatOption === "string" ? predefinedFormats[formatOption] : formatOption;
191
327
  const logMethod = logger[level].bind(logger);
192
328
  const errorLogMethod = logger.error.bind(logger);
193
329
  let plugin = new Elysia({
194
330
  name: "@logtape/elysia",
195
331
  seed: options
196
- }).state("startTime", 0).onRequest(({ store }) => {
197
- store.startTime = performance.now();
332
+ });
333
+ if (shouldWrapContext) plugin = plugin.wrap((handle) => {
334
+ return async (request) => {
335
+ const startTime = performance.now();
336
+ const requestContext = await buildRequestContext(request, contextOptions);
337
+ requestContextStates.set(request, {
338
+ ...requestContext,
339
+ startTime
340
+ });
341
+ return await withContext(requestContext.context, () => handle(request));
342
+ };
343
+ });
344
+ plugin = plugin.state("startTime", 0).onRequest(async ({ request, set, store }) => {
345
+ let requestContext = requestContextStates.get(request);
346
+ if (requestContext == null && shouldWrapContext) {
347
+ const startTime = performance.now();
348
+ requestContext = {
349
+ ...await buildRequestContext(request, contextOptions),
350
+ startTime
351
+ };
352
+ requestContextStates.set(request, requestContext);
353
+ }
354
+ store.startTime = requestContext?.startTime ?? performance.now();
355
+ if (requestContext?.responseHeader != null) set.headers[requestContext.responseHeader.name] = requestContext.responseHeader.value;
198
356
  });
199
357
  if (logRequest) plugin = plugin.onRequest((ctx) => {
200
358
  if (!skip(ctx)) {
201
- const result = formatFn(ctx, 0);
202
- if (typeof result === "string") logMethod(result);
359
+ const requestContext = requestContextStates.get(ctx.request)?.context ?? {};
360
+ const result = withRequestLogContext(formatFn(ctx, 0), requestContext);
361
+ if (typeof result === "string") logMethod(result, requestContext);
203
362
  else logMethod("{method} {url}", result);
204
363
  }
205
364
  });
@@ -207,8 +366,9 @@ function elysiaLogger(options = {}) {
207
366
  if (skip(ctx)) return;
208
367
  const store = ctx.store;
209
368
  const responseTime = performance.now() - store.startTime;
210
- const result = formatFn(ctx, responseTime);
211
- if (typeof result === "string") logMethod(result);
369
+ const requestContext = requestContextStates.get(ctx.request)?.context ?? {};
370
+ const result = withRequestLogContext(formatFn(ctx, responseTime), requestContext);
371
+ if (typeof result === "string") logMethod(result, requestContext);
212
372
  else logMethod("{method} {url} {status} - {responseTime} ms", result);
213
373
  });
214
374
  plugin = plugin.onError((ctx) => {
@@ -217,11 +377,13 @@ function elysiaLogger(options = {}) {
217
377
  const elysiaCtx = ctx;
218
378
  if (skip(elysiaCtx)) return;
219
379
  const props = buildProperties(elysiaCtx, responseTime);
380
+ const requestContext = requestContextStates.get(ctx.request)?.context ?? {};
220
381
  const status = getErrorStatus(ctx.code, ctx.error, elysiaCtx.set.status);
221
382
  const error = ctx.error;
222
383
  const errorMessage = error?.message ?? "Unknown error";
223
384
  errorLogMethod("Error: {method} {url} {status} - {responseTime} ms - {errorMessage}", {
224
385
  ...props,
386
+ ...requestContext,
225
387
  status,
226
388
  errorMessage,
227
389
  errorCode: ctx.code
package/dist/mod.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mod.js","names":["request: Request","headers: Record<string, string | undefined>","ctx: ElysiaContext","responseTime: number","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","errorCodeToStatus: Record<string, number>","code: string | number","error: unknown","setStatus: number","options: ElysiaLogTapeOptions","formatFn: FormatFunction"],"sources":["../src/mod.ts"],"sourcesContent":["import { Elysia } from \"elysia\";\nimport { getLogger, type LogLevel } from \"@logtape/logtape\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n/**\n * Minimal Elysia Context interface for compatibility.\n * @since 2.0.0\n */\nexport interface ElysiaContext {\n request: Request;\n path: string;\n set: {\n status: number;\n headers: Record<string, string | undefined>;\n };\n}\n\n/**\n * Plugin scope options for controlling hook propagation.\n * @since 2.0.0\n */\nexport type PluginScope = \"global\" | \"scoped\" | \"local\";\n\n/**\n * Predefined log format names compatible with Morgan.\n * @since 2.0.0\n */\nexport type PredefinedFormat = \"combined\" | \"common\" | \"dev\" | \"short\" | \"tiny\";\n\n/**\n * Custom format function for request logging.\n *\n * @param ctx The Elysia context object.\n * @param responseTime The response time in milliseconds.\n * @returns A string message or an object with structured properties.\n * @since 2.0.0\n */\nexport type FormatFunction = (\n ctx: ElysiaContext,\n responseTime: number,\n) => string | Record<string, unknown>;\n\n/**\n * Structured log properties for HTTP requests.\n * @since 2.0.0\n */\nexport interface RequestLogProperties {\n /** HTTP request method */\n method: string;\n /** Request URL */\n url: string;\n /** Request path */\n path: 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 (from X-Forwarded-For header) */\n remoteAddr: string | undefined;\n /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\n}\n\n/**\n * Options for configuring the Elysia LogTape middleware.\n * @since 2.0.0\n */\nexport interface ElysiaLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"elysia\"]\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 health check endpoint\n * ```typescript\n * app.use(elysiaLogger({\n * skip: (ctx) => ctx.path === \"/health\",\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (ctx: ElysiaContext) => 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 `logRequest` is `true`, response-related properties\n * (status, responseTime, contentLength) will not be available.\n *\n * @default false\n */\n readonly logRequest?: boolean;\n\n /**\n * The plugin scope for controlling how lifecycle hooks are propagated.\n *\n * - `\"global\"` - Hooks apply to all routes in the application\n * - `\"scoped\"` - Hooks apply to the parent instance where the plugin is used\n * - `\"local\"` - Hooks only apply within the plugin itself\n *\n * @default \"global\"\n */\n readonly scope?: PluginScope;\n}\n\n/**\n * Get referrer from request headers.\n */\nfunction getReferrer(request: Request): string | undefined {\n return request.headers.get(\"referrer\") ??\n request.headers.get(\"referer\") ??\n undefined;\n}\n\n/**\n * Get user agent from request headers.\n */\nfunction getUserAgent(request: Request): string | undefined {\n return request.headers.get(\"user-agent\") ?? undefined;\n}\n\n/**\n * Get remote address from X-Forwarded-For header.\n */\nfunction getRemoteAddr(request: Request): string | undefined {\n const forwarded = request.headers.get(\"x-forwarded-for\");\n if (forwarded) {\n // X-Forwarded-For can contain multiple IPs, take the first one\n const firstIp = forwarded.split(\",\")[0].trim();\n return firstIp || undefined;\n }\n return undefined;\n}\n\n/**\n * Get content length from response headers.\n */\nfunction getContentLength(\n headers: Record<string, string | undefined>,\n): string | undefined {\n const contentLength = headers[\"content-length\"];\n if (contentLength === undefined || contentLength === null) return undefined;\n return contentLength;\n}\n\n/**\n * Build structured log properties from context.\n */\nfunction buildProperties(\n ctx: ElysiaContext,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: ctx.request.method,\n url: ctx.request.url,\n path: ctx.path,\n status: ctx.set.status,\n responseTime,\n contentLength: getContentLength(ctx.set.headers),\n remoteAddr: getRemoteAddr(ctx.request),\n userAgent: getUserAgent(ctx.request),\n referrer: getReferrer(ctx.request),\n };\n}\n\n/**\n * Combined format (Apache Combined Log Format).\n * Returns all structured properties.\n */\nfunction formatCombined(\n ctx: ElysiaContext,\n responseTime: number,\n): Record<string, unknown> {\n return { ...buildProperties(ctx, responseTime) };\n}\n\n/**\n * Common format (Apache Common Log Format).\n * Like combined but without referrer and userAgent.\n */\nfunction formatCommon(\n ctx: ElysiaContext,\n responseTime: number,\n): Record<string, unknown> {\n const props = buildProperties(ctx, responseTime);\n const { referrer: _referrer, userAgent: _userAgent, ...rest } = props;\n return rest;\n}\n\n/**\n * Dev format (colored output for development).\n * :method :path :status :response-time ms - :res[content-length]\n */\nfunction formatDev(ctx: ElysiaContext, responseTime: number): string {\n const contentLength = getContentLength(ctx.set.headers) ?? \"-\";\n return `${ctx.request.method} ${ctx.path} ${ctx.set.status} ${\n responseTime.toFixed(3)\n } ms - ${contentLength}`;\n}\n\n/**\n * Short format.\n * :remote-addr :method :url :status :res[content-length] - :response-time ms\n */\nfunction formatShort(ctx: ElysiaContext, responseTime: number): string {\n const remoteAddr = getRemoteAddr(ctx.request) ?? \"-\";\n const contentLength = getContentLength(ctx.set.headers) ?? \"-\";\n return `${remoteAddr} ${ctx.request.method} ${ctx.request.url} ${ctx.set.status} ${contentLength} - ${\n responseTime.toFixed(3)\n } ms`;\n}\n\n/**\n * Tiny format (minimal output).\n * :method :path :status :res[content-length] - :response-time ms\n */\nfunction formatTiny(ctx: ElysiaContext, responseTime: number): string {\n const contentLength = getContentLength(ctx.set.headers) ?? \"-\";\n return `${ctx.request.method} ${ctx.path} ${ctx.set.status} ${contentLength} - ${\n responseTime.toFixed(3)\n } 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 * Mapping of Elysia error codes to HTTP status codes.\n */\nconst errorCodeToStatus: Record<string, number> = {\n NOT_FOUND: 404,\n VALIDATION: 422,\n PARSE: 400,\n INTERNAL_SERVER_ERROR: 500,\n INVALID_COOKIE_SIGNATURE: 400,\n UNKNOWN: 500,\n};\n\n/**\n * Get the HTTP status code from an error context.\n * Checks error.status first, then falls back to error code mapping.\n */\nfunction getErrorStatus(\n code: string | number,\n error: unknown,\n setStatus: number,\n): number {\n // If code is already a number, use it as status\n if (typeof code === \"number\") {\n return code;\n }\n // Check if error has a status property (Elysia custom errors)\n if (\n error != null &&\n typeof error === \"object\" &&\n \"status\" in error &&\n typeof error.status === \"number\"\n ) {\n return error.status;\n }\n // Fall back to error code mapping\n if (code in errorCodeToStatus) {\n return errorCodeToStatus[code];\n }\n // Use set.status as last resort\n return setStatus;\n}\n\n/**\n * Internal store type for timing.\n */\ninterface LoggerStore {\n startTime: number;\n}\n\n/**\n * Creates Elysia plugin for HTTP request logging using LogTape.\n *\n * This plugin 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 { Elysia } from \"elysia\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { elysiaLogger } from \"@logtape/elysia\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"elysia\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = new Elysia()\n * .use(elysiaLogger())\n * .get(\"/\", () => ({ hello: \"world\" }))\n * .listen(3000);\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(elysiaLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (ctx) => ctx.path === \"/health\",\n * scope: \"scoped\",\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(elysiaLogger({\n * format: (ctx, responseTime) => ({\n * method: ctx.request.method,\n * path: ctx.path,\n * status: ctx.set.status,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the plugin.\n * @returns Elysia plugin instance.\n * @since 2.0.0\n */\n// deno-lint-ignore no-explicit-any\nexport function elysiaLogger(options: ElysiaLogTapeOptions = {}): Elysia<any> {\n const category = normalizeCategory(options.category ?? [\"elysia\"]);\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 logRequest = options.logRequest ?? false;\n const scope = options.scope ?? \"global\";\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 const errorLogMethod = logger.error.bind(logger);\n\n let plugin = new Elysia({\n name: \"@logtape/elysia\",\n seed: options,\n })\n .state(\"startTime\", 0)\n .onRequest(({ store }) => {\n (store as LoggerStore).startTime = performance.now();\n });\n\n if (logRequest) {\n // Log immediately when request arrives\n plugin = plugin.onRequest((ctx) => {\n if (!skip(ctx as unknown as ElysiaContext)) {\n const result = formatFn(ctx as unknown as ElysiaContext, 0);\n if (typeof result === \"string\") {\n logMethod(result);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n });\n } else {\n // Log after handler completes\n plugin = plugin.onAfterHandle((ctx) => {\n if (skip(ctx as unknown as ElysiaContext)) return;\n\n const store = ctx.store as LoggerStore;\n const responseTime = performance.now() - store.startTime;\n const result = formatFn(ctx as unknown as ElysiaContext, responseTime);\n\n if (typeof result === \"string\") {\n logMethod(result);\n } else {\n logMethod(\"{method} {url} {status} - {responseTime} ms\", result);\n }\n });\n }\n\n // Add error logging\n plugin = plugin.onError((ctx) => {\n const store = ctx.store as LoggerStore;\n const responseTime = performance.now() - store.startTime;\n const elysiaCtx = ctx as unknown as ElysiaContext;\n\n if (skip(elysiaCtx)) return;\n\n const props = buildProperties(elysiaCtx, responseTime);\n // Get the correct HTTP status code from error context\n const status = getErrorStatus(ctx.code, ctx.error, elysiaCtx.set.status);\n // Extract error message safely\n const error = ctx.error as { message?: string } | undefined;\n const errorMessage = error?.message ?? \"Unknown error\";\n errorLogMethod(\n \"Error: {method} {url} {status} - {responseTime} ms - {errorMessage}\",\n {\n ...props,\n status,\n errorMessage,\n errorCode: ctx.code,\n },\n );\n });\n\n // Apply scope\n if (scope === \"global\") {\n // deno-lint-ignore no-explicit-any\n return plugin.as(\"global\") as unknown as Elysia<any>;\n } else if (scope === \"scoped\") {\n // deno-lint-ignore no-explicit-any\n return plugin.as(\"scoped\") as unknown as Elysia<any>;\n }\n\n // deno-lint-ignore no-explicit-any\n return plugin as unknown as Elysia<any>;\n}\n"],"mappings":";;;;;;;AA6IA,SAAS,YAAYA,SAAsC;AACzD,QAAO,QAAQ,QAAQ,IAAI,WAAW,IACpC,QAAQ,QAAQ,IAAI,UAAU;AAEjC;;;;AAKD,SAAS,aAAaA,SAAsC;AAC1D,QAAO,QAAQ,QAAQ,IAAI,aAAa;AACzC;;;;AAKD,SAAS,cAAcA,SAAsC;CAC3D,MAAM,YAAY,QAAQ,QAAQ,IAAI,kBAAkB;AACxD,KAAI,WAAW;EAEb,MAAM,UAAU,UAAU,MAAM,IAAI,CAAC,GAAG,MAAM;AAC9C,SAAO;CACR;AACD;AACD;;;;AAKD,SAAS,iBACPC,SACoB;CACpB,MAAM,gBAAgB,QAAQ;AAC9B,KAAI,4BAA+B,kBAAkB,KAAM;AAC3D,QAAO;AACR;;;;AAKD,SAAS,gBACPC,KACAC,cACsB;AACtB,QAAO;EACL,QAAQ,IAAI,QAAQ;EACpB,KAAK,IAAI,QAAQ;EACjB,MAAM,IAAI;EACV,QAAQ,IAAI,IAAI;EAChB;EACA,eAAe,iBAAiB,IAAI,IAAI,QAAQ;EAChD,YAAY,cAAc,IAAI,QAAQ;EACtC,WAAW,aAAa,IAAI,QAAQ;E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ClB,MAAM,eAAe,YAAY,KAAK,GAAG,MAAM;EAC/C,MAAM,SAAS,SAAS,KAAiC,aAAa;AAEtE,aAAW,WAAW,SACpB,WAAU,OAAO;MAEjB,WAAU,+CAA+C,OAAO;CAEnE,EAAC;AAIJ,UAAS,OAAO,QAAQ,CAAC,QAAQ;EAC/B,MAAM,QAAQ,IAAI;EAClB,MAAM,eAAe,YAAY,KAAK,GAAG,MAAM;EAC/C,MAAM,YAAY;AAElB,MAAI,KAAK,UAAU,CAAE;EAErB,MAAM,QAAQ,gBAAgB,WAAW,aAAa;EAEtD,MAAM,SAAS,eAAe,IAAI,MAAM,IAAI,OAAO,UAAU,IAAI,OAAO;EAExE,MAAM,QAAQ,IAAI;EAClB,MAAM,eAAe,OAAO,WAAW;AACvC,iBACE,uEACA;GACE,GAAG;GACH;GACA;GACA,WAAW,IAAI;EAChB,EACF;CACF,EAAC;AAGF,KAAI,UAAU,SAEZ,QAAO,OAAO,GAAG,SAAS;UACjB,UAAU,SAEnB,QAAO,OAAO,GAAG,SAAS;AAI5B,QAAO;AACR"}
1
+ {"version":3,"file":"mod.js","names":["options: boolean | RequestContextOptions | undefined","options: boolean | RequestIdOptions | undefined","value: string","request: Request","options: RequestIdOptions","responseHeader","resolvedRequestId:\n | { readonly property: string; readonly value: string }\n | undefined","include: readonly RequestContextField[]","context: Record<string, unknown>","options: RequestContextOptions","headers: Record<string, string | undefined>","ctx: ElysiaContext","responseTime: number","result: string | Record<string, unknown>","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","errorCodeToStatus: Record<string, number>","code: string | number","error: unknown","setStatus: number","options: ElysiaLogTapeOptions","formatFn: FormatFunction","plugin: Elysia<any, any, any, any, any, any, any>"],"sources":["../src/mod.ts"],"sourcesContent":["import { Elysia } from \"elysia\";\nimport { getLogger, type LogLevel, withContext } from \"@logtape/logtape\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n/**\n * Minimal Elysia Context interface for compatibility.\n * @since 2.0.0\n */\nexport interface ElysiaContext {\n request: Request;\n path: string;\n set: {\n status: number;\n headers: Record<string, string | undefined>;\n };\n}\n\n/**\n * Plugin scope options for controlling hook propagation.\n * @since 2.0.0\n */\nexport type PluginScope = \"global\" | \"scoped\" | \"local\";\n\n/**\n * Predefined log format names compatible with Morgan.\n * @since 2.0.0\n */\nexport type PredefinedFormat = \"combined\" | \"common\" | \"dev\" | \"short\" | \"tiny\";\n\n/**\n * Custom format function for request logging.\n *\n * @param ctx The Elysia context object.\n * @param responseTime The response time in milliseconds.\n * @returns A string message or an object with structured properties.\n * @since 2.0.0\n */\nexport type FormatFunction = (\n ctx: ElysiaContext,\n responseTime: number,\n) => string | Record<string, unknown>;\n\n/**\n * Structured log properties for HTTP requests.\n * @since 2.0.0\n */\nexport interface RequestLogProperties {\n /** HTTP request method */\n method: string;\n /** Request URL */\n url: string;\n /** Request path */\n path: 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 (from X-Forwarded-For header) */\n remoteAddr: string | undefined;\n /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\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\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 ctx: ElysiaContext,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n}\n\n/**\n * Options for configuring the Elysia LogTape middleware.\n * @since 2.0.0\n */\nexport interface ElysiaLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"elysia\"]\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 health check endpoint\n * ```typescript\n * app.use(elysiaLogger({\n * skip: (ctx) => ctx.path === \"/health\",\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (ctx: ElysiaContext) => 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 `logRequest` is `true`, response-related properties\n * (status, responseTime, contentLength) will not be available.\n *\n * @default false\n */\n readonly logRequest?: boolean;\n\n /**\n * The plugin scope for controlling how lifecycle hooks are propagated.\n *\n * - `\"global\"` - Hooks apply to all routes in the application\n * - `\"scoped\"` - Hooks apply to the parent instance where the plugin is used\n * - `\"local\"` - Hooks only apply within the plugin itself\n *\n * @default \"global\"\n */\n readonly scope?: PluginScope;\n\n /**\n * Enables request-scoped implicit context and request ID correlation.\n *\n * When set to `true`, the plugin reads the `x-request-id` header, generates\n * one when it is absent, writes it to the `x-request-id` response header,\n * and adds `requestId` to all LogTape records emitted while handling the\n * 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 * Per-request context state stored outside Elysia's shared store.\n */\ninterface ElysiaRequestContextState {\n readonly context: Record<string, unknown>;\n readonly startTime?: number;\n readonly responseHeader?: {\n readonly name: string;\n readonly value: string;\n };\n}\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 a request path from a request URL.\n */\nfunction getPath(request: Request): string {\n return new URL(request.url).pathname;\n}\n\n/**\n * Resolve the request ID for a request.\n */\nfunction resolveRequestId(\n request: Request,\n options: RequestIdOptions,\n): {\n readonly property: string;\n readonly value: string;\n readonly responseHeader?: string;\n} {\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 = request.headers.get(headerName);\n if (headerValue == null) continue;\n const normalized = normalize(headerValue);\n if (normalized != null) {\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n return {\n property,\n value: normalized,\n responseHeader: responseHeader === false ? undefined : responseHeader,\n };\n }\n }\n const generated = (options.generate ?? generateRequestId)();\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n return {\n property,\n value: generated,\n responseHeader: responseHeader === false ? undefined : responseHeader,\n };\n}\n\n/**\n * Get referrer from request headers.\n */\nfunction getReferrer(request: Request): string | undefined {\n return request.headers.get(\"referrer\") ??\n request.headers.get(\"referer\") ??\n undefined;\n}\n\n/**\n * Get user agent from request headers.\n */\nfunction getUserAgent(request: Request): string | undefined {\n return request.headers.get(\"user-agent\") ?? undefined;\n}\n\n/**\n * Get remote address from X-Forwarded-For header.\n */\nfunction getRemoteAddr(request: Request): string | undefined {\n const forwarded = request.headers.get(\"x-forwarded-for\");\n if (forwarded) {\n // X-Forwarded-For can contain multiple IPs, take the first one\n const firstIp = forwarded.split(\",\")[0].trim();\n return firstIp || undefined;\n }\n return undefined;\n}\n\n/**\n * Build request context fields from a request.\n */\nfunction buildIncludedContext(\n request: Request,\n resolvedRequestId:\n | { readonly property: string; readonly value: string }\n | 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 = request.method;\n break;\n case \"url\":\n context.url = request.url;\n break;\n case \"path\":\n context.path = getPath(request);\n break;\n case \"userAgent\":\n context.userAgent = getUserAgent(request);\n break;\n case \"remoteAddr\":\n context.remoteAddr = getRemoteAddr(request);\n break;\n case \"referrer\":\n context.referrer = getReferrer(request);\n break;\n }\n }\n return context;\n}\n\n/**\n * Build the implicit context for a request.\n */\nasync function buildRequestContext(\n request: Request,\n options: RequestContextOptions,\n): Promise<ElysiaRequestContextState> {\n const requestIdOptions = normalizeRequestIdOptions(options.requestId);\n const resolvedRequestId = requestIdOptions == null\n ? undefined\n : resolveRequestId(request, requestIdOptions);\n const include = options.include ??\n (resolvedRequestId == null ? [] : [\"requestId\"] as const);\n const context = buildIncludedContext(request, resolvedRequestId, include);\n if (options.enrich != null) {\n const set = { status: 200, headers: {} };\n Object.assign(\n context,\n await options.enrich({\n request,\n path: getPath(request),\n set,\n }),\n );\n }\n const responseHeader = resolvedRequestId?.responseHeader == null\n ? undefined\n : {\n name: resolvedRequestId.responseHeader,\n value: resolvedRequestId.value,\n };\n return { context, responseHeader };\n}\n\n/**\n * Get content length from response headers.\n */\nfunction getContentLength(\n headers: Record<string, string | undefined>,\n): string | undefined {\n const contentLength = headers[\"content-length\"];\n if (contentLength === undefined || contentLength === null) return undefined;\n return contentLength;\n}\n\n/**\n * Build structured log properties from context.\n */\nfunction buildProperties(\n ctx: ElysiaContext,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: ctx.request.method,\n url: ctx.request.url,\n path: ctx.path,\n status: ctx.set.status,\n responseTime,\n contentLength: getContentLength(ctx.set.headers),\n remoteAddr: getRemoteAddr(ctx.request),\n userAgent: getUserAgent(ctx.request),\n referrer: getReferrer(ctx.request),\n };\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 * Combined format (Apache Combined Log Format).\n * Returns all structured properties.\n */\nfunction formatCombined(\n ctx: ElysiaContext,\n responseTime: number,\n): Record<string, unknown> {\n return { ...buildProperties(ctx, responseTime) };\n}\n\n/**\n * Common format (Apache Common Log Format).\n * Like combined but without referrer and userAgent.\n */\nfunction formatCommon(\n ctx: ElysiaContext,\n responseTime: number,\n): Record<string, unknown> {\n const props = buildProperties(ctx, responseTime);\n const { referrer: _referrer, userAgent: _userAgent, ...rest } = props;\n return rest;\n}\n\n/**\n * Dev format (colored output for development).\n * :method :path :status :response-time ms - :res[content-length]\n */\nfunction formatDev(ctx: ElysiaContext, responseTime: number): string {\n const contentLength = getContentLength(ctx.set.headers) ?? \"-\";\n return `${ctx.request.method} ${ctx.path} ${ctx.set.status} ${\n responseTime.toFixed(3)\n } ms - ${contentLength}`;\n}\n\n/**\n * Short format.\n * :remote-addr :method :url :status :res[content-length] - :response-time ms\n */\nfunction formatShort(ctx: ElysiaContext, responseTime: number): string {\n const remoteAddr = getRemoteAddr(ctx.request) ?? \"-\";\n const contentLength = getContentLength(ctx.set.headers) ?? \"-\";\n return `${remoteAddr} ${ctx.request.method} ${ctx.request.url} ${ctx.set.status} ${contentLength} - ${\n responseTime.toFixed(3)\n } ms`;\n}\n\n/**\n * Tiny format (minimal output).\n * :method :path :status :res[content-length] - :response-time ms\n */\nfunction formatTiny(ctx: ElysiaContext, responseTime: number): string {\n const contentLength = getContentLength(ctx.set.headers) ?? \"-\";\n return `${ctx.request.method} ${ctx.path} ${ctx.set.status} ${contentLength} - ${\n responseTime.toFixed(3)\n } 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 * Mapping of Elysia error codes to HTTP status codes.\n */\nconst errorCodeToStatus: Record<string, number> = {\n NOT_FOUND: 404,\n VALIDATION: 422,\n PARSE: 400,\n INTERNAL_SERVER_ERROR: 500,\n INVALID_COOKIE_SIGNATURE: 400,\n UNKNOWN: 500,\n};\n\n/**\n * Get the HTTP status code from an error context.\n * Checks error.status first, then falls back to error code mapping.\n */\nfunction getErrorStatus(\n code: string | number,\n error: unknown,\n setStatus: number,\n): number {\n // If code is already a number, use it as status\n if (typeof code === \"number\") {\n return code;\n }\n // Check if error has a status property (Elysia custom errors)\n if (\n error != null &&\n typeof error === \"object\" &&\n \"status\" in error &&\n typeof error.status === \"number\"\n ) {\n return error.status;\n }\n // Fall back to error code mapping\n if (code in errorCodeToStatus) {\n return errorCodeToStatus[code];\n }\n // Use set.status as last resort\n return setStatus;\n}\n\n/**\n * Internal store type for timing.\n */\ninterface LoggerStore {\n startTime: number;\n}\n\n/**\n * Creates Elysia plugin for HTTP request logging using LogTape.\n *\n * This plugin 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 { Elysia } from \"elysia\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { elysiaLogger } from \"@logtape/elysia\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"elysia\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = new Elysia()\n * .use(elysiaLogger())\n * .get(\"/\", () => ({ hello: \"world\" }))\n * .listen(3000);\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(elysiaLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (ctx) => ctx.path === \"/health\",\n * scope: \"scoped\",\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(elysiaLogger({\n * format: (ctx, responseTime) => ({\n * method: ctx.request.method,\n * path: ctx.path,\n * status: ctx.set.status,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the plugin.\n * @returns Elysia plugin instance.\n * @since 2.0.0\n */\n// deno-lint-ignore no-explicit-any\nexport function elysiaLogger(options: ElysiaLogTapeOptions = {}): Elysia<any> {\n const category = normalizeCategory(options.category ?? [\"elysia\"]);\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 logRequest = options.logRequest ?? false;\n const scope = options.scope ?? \"global\";\n const contextOptions = normalizeRequestContextOptions(options.context);\n const requestContextStates = new WeakMap<\n Request,\n ElysiaRequestContextState\n >();\n const shouldWrapContext = contextOptions != null && scope !== \"local\";\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 const errorLogMethod = logger.error.bind(logger);\n\n // deno-lint-ignore no-explicit-any\n let plugin: Elysia<any, any, any, any, any, any, any> = new Elysia({\n name: \"@logtape/elysia\",\n seed: options,\n });\n\n if (shouldWrapContext) {\n // Elysia lifecycle hooks cannot wrap downstream handlers, so use wrap()\n // to keep AsyncLocalStorage active for the whole route execution.\n plugin = plugin.wrap((handle) => {\n return async (request: Request) => {\n const startTime = performance.now();\n const requestContext = await buildRequestContext(\n request,\n contextOptions,\n );\n requestContextStates.set(request, {\n ...requestContext,\n startTime,\n });\n return await withContext(\n requestContext.context,\n () => handle(request),\n );\n };\n });\n }\n\n plugin = plugin\n .state(\"startTime\", 0)\n .onRequest(async ({ request, set, store }) => {\n let requestContext = requestContextStates.get(request);\n if (requestContext == null && shouldWrapContext) {\n const startTime = performance.now();\n requestContext = {\n ...await buildRequestContext(request, contextOptions),\n startTime,\n };\n requestContextStates.set(request, requestContext);\n }\n (store as LoggerStore).startTime = requestContext?.startTime ??\n performance.now();\n if (requestContext?.responseHeader != null) {\n set.headers[requestContext.responseHeader.name] =\n requestContext.responseHeader.value;\n }\n });\n\n if (logRequest) {\n // Log immediately when request arrives\n plugin = plugin.onRequest((ctx) => {\n if (!skip(ctx as unknown as ElysiaContext)) {\n const requestContext = requestContextStates.get(ctx.request)?.context ??\n {};\n const result = withRequestLogContext(\n formatFn(ctx as unknown as ElysiaContext, 0),\n requestContext,\n );\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n });\n } else {\n // Log after handler completes\n plugin = plugin.onAfterHandle((ctx) => {\n if (skip(ctx as unknown as ElysiaContext)) return;\n\n const store = ctx.store as LoggerStore;\n const responseTime = performance.now() - store.startTime;\n const requestContext = requestContextStates.get(ctx.request)?.context ??\n {};\n const result = withRequestLogContext(\n formatFn(ctx as unknown as ElysiaContext, 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\n // Add error logging\n plugin = plugin.onError((ctx) => {\n const store = ctx.store as LoggerStore;\n const responseTime = performance.now() - store.startTime;\n const elysiaCtx = ctx as unknown as ElysiaContext;\n\n if (skip(elysiaCtx)) return;\n\n const props = buildProperties(elysiaCtx, responseTime);\n const requestContext = requestContextStates.get(ctx.request)?.context ?? {};\n // Get the correct HTTP status code from error context\n const status = getErrorStatus(ctx.code, ctx.error, elysiaCtx.set.status);\n // Extract error message safely\n const error = ctx.error as { message?: string } | undefined;\n const errorMessage = error?.message ?? \"Unknown error\";\n errorLogMethod(\n \"Error: {method} {url} {status} - {responseTime} ms - {errorMessage}\",\n {\n ...props,\n ...requestContext,\n status,\n errorMessage,\n errorCode: ctx.code,\n },\n );\n });\n\n // Apply scope\n if (scope === \"global\") {\n // deno-lint-ignore no-explicit-any\n return plugin.as(\"global\") as unknown as Elysia<any>;\n } else if (scope === \"scoped\") {\n // deno-lint-ignore no-explicit-any\n return plugin.as(\"scoped\") as unknown as Elysia<any>;\n }\n\n // deno-lint-ignore no-explicit-any\n return plugin as unknown as Elysia<any>;\n}\n"],"mappings":";;;;AAkOA,MAAM,yBAAyB;;;;AAiB/B,SAAS,+BACPA,SACmC;AACnC,KAAI,YAAY,KAAM,QAAO,CAAE;AAC/B,KAAI,YAAY,SAAS,WAAW,KAAM;AAC1C,QAAO;AACR;;;;AAKD,SAAS,0BACPC,SA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AI,KAAK,IAAgC,CAAE;EAE3C,MAAM,QAAQ,IAAI;EAClB,MAAM,eAAe,YAAY,KAAK,GAAG,MAAM;EAC/C,MAAM,iBAAiB,qBAAqB,IAAI,IAAI,QAAQ,EAAE,WAC5D,CAAE;EACJ,MAAM,SAAS,sBACb,SAAS,KAAiC,aAAa,EACvD,eACD;AAED,aAAW,WAAW,SACpB,WAAU,QAAQ,eAAe;MAEjC,WAAU,+CAA+C,OAAO;CAEnE,EAAC;AAIJ,UAAS,OAAO,QAAQ,CAAC,QAAQ;EAC/B,MAAM,QAAQ,IAAI;EAClB,MAAM,eAAe,YAAY,KAAK,GAAG,MAAM;EAC/C,MAAM,YAAY;AAElB,MAAI,KAAK,UAAU,CAAE;EAErB,MAAM,QAAQ,gBAAgB,WAAW,aAAa;EACtD,MAAM,iBAAiB,qBAAqB,IAAI,IAAI,QAAQ,EAAE,WAAW,CAAE;EAE3E,MAAM,SAAS,eAAe,IAAI,MAAM,IAAI,OAAO,UAAU,IAAI,OAAO;EAExE,MAAM,QAAQ,IAAI;EAClB,MAAM,eAAe,OAAO,WAAW;AACvC,iBACE,uEACA;GACE,GAAG;GACH,GAAG;GACH;GACA;GACA,WAAW,IAAI;EAChB,EACF;CACF,EAAC;AAGF,KAAI,UAAU,SAEZ,QAAO,OAAO,GAAG,SAAS;UACjB,UAAU,SAEnB,QAAO,OAAO,GAAG,SAAS;AAI5B,QAAO;AACR"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logtape/elysia",
3
- "version": "2.2.0-dev.684+ae3a262a",
3
+ "version": "2.2.0-dev.686+61fa5e1a",
4
4
  "description": "Elysia adapter for LogTape logging library",
5
5
  "keywords": [
6
6
  "logging",
@@ -54,7 +54,7 @@
54
54
  ],
55
55
  "peerDependencies": {
56
56
  "elysia": "^1.4.0",
57
- "@logtape/logtape": "^2.2.0-dev.684+ae3a262a"
57
+ "@logtape/logtape": "^2.2.0-dev.686+61fa5e1a"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@alinea/suite": "^0.6.3",