@logtape/elysia 2.2.0-dev.700 → 2.2.0-dev.708

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mod.cjs CHANGED
@@ -274,54 +274,127 @@ const elysiaRouteMethods = [
274
274
  "post",
275
275
  "put"
276
276
  ];
277
- function getElysiaRouteEntries(plugin) {
277
+ const elysiaRouteHookKeys = [
278
+ "afterHandle",
279
+ "afterResponse",
280
+ "beforeHandle",
281
+ "derive",
282
+ "error",
283
+ "mapResponse",
284
+ "parse",
285
+ "resolve",
286
+ "transform"
287
+ ];
288
+ const elysiaPluginLifecycleHookTypes = [
289
+ "afterHandle",
290
+ "afterResponse",
291
+ "beforeHandle",
292
+ "derive",
293
+ "error",
294
+ "mapResponse",
295
+ "resolve",
296
+ "transform"
297
+ ];
298
+ function getElysiaRouteEntries(plugin, visited = /* @__PURE__ */ new Set()) {
278
299
  if (plugin == null || typeof plugin !== "object") return [];
300
+ if (visited.has(plugin)) return [];
301
+ visited.add(plugin);
279
302
  const routePlugin = plugin;
280
303
  const history = routePlugin.router?.history;
281
304
  const entries = Array.isArray(history) ? history : history == null ? [] : Object.values(history);
282
- return entries.concat(getElysiaRouteEntries(routePlugin.default));
305
+ return entries.concat(getElysiaRouteEntries(routePlugin.default, visited));
283
306
  }
284
- /**
285
- * Wrap routes registered on a local plugin with implicit LogTape context.
286
- */
287
- function wrapLocalRouteHandlers(plugin, buildAndStoreRequestContext, applyRequestContextToSet) {
307
+ function createElysiaRequestWrappers(buildAndStoreRequestContext, applyRequestContextToSet) {
288
308
  const wrappedHandlers = /* @__PURE__ */ new WeakSet();
289
309
  const wrappedHandlerCache = /* @__PURE__ */ new WeakMap();
290
- const wrapHandler = (handler) => {
291
- if (typeof handler !== "function") return handler;
292
- const routeHandler = handler;
293
- if (wrappedHandlers.has(routeHandler)) return handler;
294
- const cached = wrappedHandlerCache.get(routeHandler);
310
+ const getRouteContext = (value) => {
311
+ if (value == null || typeof value !== "object") return void 0;
312
+ const context = value;
313
+ if (!(context.request instanceof Request)) return void 0;
314
+ return value;
315
+ };
316
+ const wrapRequestCallback = (callback) => {
317
+ if (typeof callback !== "function") return callback;
318
+ const requestCallback = callback;
319
+ if (wrappedHandlers.has(requestCallback)) return callback;
320
+ const cached = wrappedHandlerCache.get(requestCallback);
295
321
  if (cached != null) return cached;
296
- const wrapped = async function(ctx) {
322
+ const wrapped = async function(...args) {
323
+ const ctx = getRouteContext(args[0]);
324
+ if (ctx == null) return await requestCallback.apply(this, args);
297
325
  const requestContext = await buildAndStoreRequestContext(ctx.request);
298
326
  ctx.store.startTime = requestContext?.startTime ?? performance.now();
299
327
  applyRequestContextToSet(ctx.set, requestContext);
300
- return await (0, __logtape_logtape.withContext)(requestContext?.context ?? {}, () => routeHandler.call(this, ctx));
328
+ return await (0, __logtape_logtape.withContext)(requestContext?.context ?? {}, () => requestCallback.apply(this, args));
301
329
  };
302
330
  wrappedHandlers.add(wrapped);
303
- wrappedHandlerCache.set(routeHandler, wrapped);
331
+ wrappedHandlerCache.set(requestCallback, wrapped);
304
332
  return wrapped;
305
333
  };
334
+ const wrapRouteHookValue = (value) => {
335
+ if (Array.isArray(value)) return value.map(wrapRouteHookValue);
336
+ if (typeof value === "function") return wrapRequestCallback(value);
337
+ if (value == null || typeof value !== "object") return value;
338
+ const hookContainer = value;
339
+ if (typeof hookContainer.fn !== "function") return value;
340
+ return {
341
+ ...hookContainer,
342
+ fn: wrapRequestCallback(hookContainer.fn)
343
+ };
344
+ };
345
+ const wrapRouteHooks = (hooks) => {
346
+ if (hooks == null || typeof hooks !== "object") return hooks;
347
+ const routeHooks = hooks;
348
+ let changed = false;
349
+ const wrappedHooks = { ...routeHooks };
350
+ for (const key of elysiaRouteHookKeys) {
351
+ const value = routeHooks[key];
352
+ const wrappedValue = wrapRouteHookValue(value);
353
+ if (wrappedValue === value) continue;
354
+ wrappedHooks[key] = wrappedValue;
355
+ changed = true;
356
+ }
357
+ return changed ? wrappedHooks : hooks;
358
+ };
359
+ return {
360
+ wrapRequestCallback,
361
+ wrapRouteHookValue,
362
+ wrapRouteHooks
363
+ };
364
+ }
365
+ /**
366
+ * Wrap routes registered on a local plugin with implicit LogTape context.
367
+ */
368
+ function wrapLocalRouteHandlers(plugin, buildAndStoreRequestContext, applyRequestContextToSet) {
369
+ const { wrapRequestCallback, wrapRouteHooks } = createElysiaRequestWrappers(buildAndStoreRequestContext, applyRequestContextToSet);
306
370
  const wrapRouteEntries = (routePlugin) => {
307
371
  const restore = [];
308
372
  for (const route$1 of getElysiaRouteEntries(routePlugin)) {
309
373
  const handler = route$1.handler;
310
- const wrappedHandler = wrapHandler(handler);
311
- if (wrappedHandler === handler) continue;
312
- route$1.handler = wrappedHandler;
313
- restore.push(() => {
314
- route$1.handler = handler;
315
- });
374
+ const wrappedHandler = wrapRequestCallback(handler);
375
+ if (wrappedHandler !== handler) {
376
+ route$1.handler = wrappedHandler;
377
+ restore.push(() => {
378
+ route$1.handler = handler;
379
+ });
380
+ }
381
+ const hooks = route$1.hooks;
382
+ const wrappedHooks = wrapRouteHooks(hooks);
383
+ if (wrappedHooks !== hooks) {
384
+ route$1.hooks = wrappedHooks;
385
+ restore.push(() => {
386
+ route$1.hooks = hooks;
387
+ });
388
+ }
316
389
  }
317
390
  return restore;
318
391
  };
319
392
  for (const method of elysiaRouteMethods) {
320
393
  const register = plugin[method].bind(plugin);
321
- plugin[method] = (path, handler, hook) => register(path, wrapHandler(handler), hook);
394
+ plugin[method] = (path, handler, hook) => register(path, wrapRequestCallback(handler), wrapRouteHooks(hook));
322
395
  }
323
396
  const route = plugin.route.bind(plugin);
324
- plugin.route = (method, path, handler, hook) => route(method, path, wrapHandler(handler), hook);
397
+ plugin.route = (method, path, handler, hook) => route(method, path, wrapRequestCallback(handler), wrapRouteHooks(hook));
325
398
  const use = plugin.use.bind(plugin);
326
399
  plugin.use = (childPlugin, ...options) => {
327
400
  const restore = wrapRouteEntries(childPlugin);
@@ -333,6 +406,21 @@ function wrapLocalRouteHandlers(plugin, buildAndStoreRequestContext, applyReques
333
406
  };
334
407
  }
335
408
  /**
409
+ * Wrap local plugin lifecycle hooks registered by downstream code.
410
+ */
411
+ function wrapLocalLifecycleHooks(plugin, buildAndStoreRequestContext, applyRequestContextToSet) {
412
+ const { wrapRouteHookValue } = createElysiaRequestWrappers(buildAndStoreRequestContext, applyRequestContextToSet);
413
+ const isLifecycleHookType = (value) => typeof value === "string" && elysiaPluginLifecycleHookTypes.includes(value);
414
+ const wrapLifecycleHookArgs = (args) => {
415
+ const wrappedArgs = [...args];
416
+ if (isLifecycleHookType(args[0]) && args.length > 1) wrappedArgs[1] = wrapRouteHookValue(args[1]);
417
+ else if (isLifecycleHookType(args[1]) && args.length > 2) wrappedArgs[2] = wrapRouteHookValue(args[2]);
418
+ return wrappedArgs;
419
+ };
420
+ const on = plugin.on.bind(plugin);
421
+ plugin.on = (...args) => on(...wrapLifecycleHookArgs(args));
422
+ }
423
+ /**
336
424
  * Creates Elysia plugin for HTTP request logging using LogTape.
337
425
  *
338
426
  * This plugin provides Morgan-compatible request logging with LogTape
@@ -418,6 +506,10 @@ function elysiaLogger(options = {}) {
418
506
  Object.assign(set.headers, requestContext.set.headers);
419
507
  }
420
508
  };
509
+ const applyRequestContextToRequest = (store, set, requestContext) => {
510
+ store.startTime = requestContext?.startTime ?? performance.now();
511
+ applyRequestContextToSet(set, requestContext);
512
+ };
421
513
  let plugin = new elysia.Elysia({
422
514
  name: "@logtape/elysia",
423
515
  seed: options
@@ -429,11 +521,12 @@ function elysiaLogger(options = {}) {
429
521
  return await (0, __logtape_logtape.withContext)(requestContext?.context ?? {}, () => handle(request));
430
522
  };
431
523
  });
432
- plugin = plugin.state("startTime", 0).onRequest(async ({ request, set, store }) => {
433
- let requestContext = requestContextStates.get(request);
434
- if (requestContext == null && shouldWrapAllRoutes) requestContext = await buildAndStoreRequestContext(request);
435
- store.startTime = requestContext?.startTime ?? performance.now();
436
- applyRequestContextToSet(set, requestContext);
524
+ plugin = plugin.state("startTime", 0).onRequest(({ request, set, store }) => {
525
+ const requestContext = requestContextStates.get(request);
526
+ if (requestContext == null && shouldWrapAllRoutes) return buildAndStoreRequestContext(request).then((resolvedContext) => {
527
+ applyRequestContextToRequest(store, set, resolvedContext);
528
+ });
529
+ applyRequestContextToRequest(store, set, requestContext);
437
530
  });
438
531
  if (scope === "local" && (contextOptions != null || logRequest)) plugin = plugin.onBeforeHandle(async (ctx) => {
439
532
  const requestContext = await buildAndStoreRequestContext(ctx.request);
@@ -482,6 +575,7 @@ function elysiaLogger(options = {}) {
482
575
  errorCode: ctx.code
483
576
  });
484
577
  });
578
+ if (shouldWrapContext && scope === "local") wrapLocalLifecycleHooks(plugin, buildAndStoreRequestContext, applyRequestContextToSet);
485
579
  if (scope === "global") return plugin.as("global");
486
580
  else if (scope === "scoped") return plugin.as("scoped");
487
581
  return plugin;
@@ -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;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;AA4kBpD;AAA4B,UA5vBX,oBAA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ef;;;;;;;;;;;;;;;;;;;;mBAsBL;;;;;;;;;;;;+BAaY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA2tBf,YAAA,WAAsB,uBAA4B"}
package/dist/mod.js CHANGED
@@ -273,54 +273,127 @@ const elysiaRouteMethods = [
273
273
  "post",
274
274
  "put"
275
275
  ];
276
- function getElysiaRouteEntries(plugin) {
276
+ const elysiaRouteHookKeys = [
277
+ "afterHandle",
278
+ "afterResponse",
279
+ "beforeHandle",
280
+ "derive",
281
+ "error",
282
+ "mapResponse",
283
+ "parse",
284
+ "resolve",
285
+ "transform"
286
+ ];
287
+ const elysiaPluginLifecycleHookTypes = [
288
+ "afterHandle",
289
+ "afterResponse",
290
+ "beforeHandle",
291
+ "derive",
292
+ "error",
293
+ "mapResponse",
294
+ "resolve",
295
+ "transform"
296
+ ];
297
+ function getElysiaRouteEntries(plugin, visited = /* @__PURE__ */ new Set()) {
277
298
  if (plugin == null || typeof plugin !== "object") return [];
299
+ if (visited.has(plugin)) return [];
300
+ visited.add(plugin);
278
301
  const routePlugin = plugin;
279
302
  const history = routePlugin.router?.history;
280
303
  const entries = Array.isArray(history) ? history : history == null ? [] : Object.values(history);
281
- return entries.concat(getElysiaRouteEntries(routePlugin.default));
304
+ return entries.concat(getElysiaRouteEntries(routePlugin.default, visited));
282
305
  }
283
- /**
284
- * Wrap routes registered on a local plugin with implicit LogTape context.
285
- */
286
- function wrapLocalRouteHandlers(plugin, buildAndStoreRequestContext, applyRequestContextToSet) {
306
+ function createElysiaRequestWrappers(buildAndStoreRequestContext, applyRequestContextToSet) {
287
307
  const wrappedHandlers = /* @__PURE__ */ new WeakSet();
288
308
  const wrappedHandlerCache = /* @__PURE__ */ new WeakMap();
289
- const wrapHandler = (handler) => {
290
- if (typeof handler !== "function") return handler;
291
- const routeHandler = handler;
292
- if (wrappedHandlers.has(routeHandler)) return handler;
293
- const cached = wrappedHandlerCache.get(routeHandler);
309
+ const getRouteContext = (value) => {
310
+ if (value == null || typeof value !== "object") return void 0;
311
+ const context = value;
312
+ if (!(context.request instanceof Request)) return void 0;
313
+ return value;
314
+ };
315
+ const wrapRequestCallback = (callback) => {
316
+ if (typeof callback !== "function") return callback;
317
+ const requestCallback = callback;
318
+ if (wrappedHandlers.has(requestCallback)) return callback;
319
+ const cached = wrappedHandlerCache.get(requestCallback);
294
320
  if (cached != null) return cached;
295
- const wrapped = async function(ctx) {
321
+ const wrapped = async function(...args) {
322
+ const ctx = getRouteContext(args[0]);
323
+ if (ctx == null) return await requestCallback.apply(this, args);
296
324
  const requestContext = await buildAndStoreRequestContext(ctx.request);
297
325
  ctx.store.startTime = requestContext?.startTime ?? performance.now();
298
326
  applyRequestContextToSet(ctx.set, requestContext);
299
- return await withContext(requestContext?.context ?? {}, () => routeHandler.call(this, ctx));
327
+ return await withContext(requestContext?.context ?? {}, () => requestCallback.apply(this, args));
300
328
  };
301
329
  wrappedHandlers.add(wrapped);
302
- wrappedHandlerCache.set(routeHandler, wrapped);
330
+ wrappedHandlerCache.set(requestCallback, wrapped);
303
331
  return wrapped;
304
332
  };
333
+ const wrapRouteHookValue = (value) => {
334
+ if (Array.isArray(value)) return value.map(wrapRouteHookValue);
335
+ if (typeof value === "function") return wrapRequestCallback(value);
336
+ if (value == null || typeof value !== "object") return value;
337
+ const hookContainer = value;
338
+ if (typeof hookContainer.fn !== "function") return value;
339
+ return {
340
+ ...hookContainer,
341
+ fn: wrapRequestCallback(hookContainer.fn)
342
+ };
343
+ };
344
+ const wrapRouteHooks = (hooks) => {
345
+ if (hooks == null || typeof hooks !== "object") return hooks;
346
+ const routeHooks = hooks;
347
+ let changed = false;
348
+ const wrappedHooks = { ...routeHooks };
349
+ for (const key of elysiaRouteHookKeys) {
350
+ const value = routeHooks[key];
351
+ const wrappedValue = wrapRouteHookValue(value);
352
+ if (wrappedValue === value) continue;
353
+ wrappedHooks[key] = wrappedValue;
354
+ changed = true;
355
+ }
356
+ return changed ? wrappedHooks : hooks;
357
+ };
358
+ return {
359
+ wrapRequestCallback,
360
+ wrapRouteHookValue,
361
+ wrapRouteHooks
362
+ };
363
+ }
364
+ /**
365
+ * Wrap routes registered on a local plugin with implicit LogTape context.
366
+ */
367
+ function wrapLocalRouteHandlers(plugin, buildAndStoreRequestContext, applyRequestContextToSet) {
368
+ const { wrapRequestCallback, wrapRouteHooks } = createElysiaRequestWrappers(buildAndStoreRequestContext, applyRequestContextToSet);
305
369
  const wrapRouteEntries = (routePlugin) => {
306
370
  const restore = [];
307
371
  for (const route$1 of getElysiaRouteEntries(routePlugin)) {
308
372
  const handler = route$1.handler;
309
- const wrappedHandler = wrapHandler(handler);
310
- if (wrappedHandler === handler) continue;
311
- route$1.handler = wrappedHandler;
312
- restore.push(() => {
313
- route$1.handler = handler;
314
- });
373
+ const wrappedHandler = wrapRequestCallback(handler);
374
+ if (wrappedHandler !== handler) {
375
+ route$1.handler = wrappedHandler;
376
+ restore.push(() => {
377
+ route$1.handler = handler;
378
+ });
379
+ }
380
+ const hooks = route$1.hooks;
381
+ const wrappedHooks = wrapRouteHooks(hooks);
382
+ if (wrappedHooks !== hooks) {
383
+ route$1.hooks = wrappedHooks;
384
+ restore.push(() => {
385
+ route$1.hooks = hooks;
386
+ });
387
+ }
315
388
  }
316
389
  return restore;
317
390
  };
318
391
  for (const method of elysiaRouteMethods) {
319
392
  const register = plugin[method].bind(plugin);
320
- plugin[method] = (path, handler, hook) => register(path, wrapHandler(handler), hook);
393
+ plugin[method] = (path, handler, hook) => register(path, wrapRequestCallback(handler), wrapRouteHooks(hook));
321
394
  }
322
395
  const route = plugin.route.bind(plugin);
323
- plugin.route = (method, path, handler, hook) => route(method, path, wrapHandler(handler), hook);
396
+ plugin.route = (method, path, handler, hook) => route(method, path, wrapRequestCallback(handler), wrapRouteHooks(hook));
324
397
  const use = plugin.use.bind(plugin);
325
398
  plugin.use = (childPlugin, ...options) => {
326
399
  const restore = wrapRouteEntries(childPlugin);
@@ -332,6 +405,21 @@ function wrapLocalRouteHandlers(plugin, buildAndStoreRequestContext, applyReques
332
405
  };
333
406
  }
334
407
  /**
408
+ * Wrap local plugin lifecycle hooks registered by downstream code.
409
+ */
410
+ function wrapLocalLifecycleHooks(plugin, buildAndStoreRequestContext, applyRequestContextToSet) {
411
+ const { wrapRouteHookValue } = createElysiaRequestWrappers(buildAndStoreRequestContext, applyRequestContextToSet);
412
+ const isLifecycleHookType = (value) => typeof value === "string" && elysiaPluginLifecycleHookTypes.includes(value);
413
+ const wrapLifecycleHookArgs = (args) => {
414
+ const wrappedArgs = [...args];
415
+ if (isLifecycleHookType(args[0]) && args.length > 1) wrappedArgs[1] = wrapRouteHookValue(args[1]);
416
+ else if (isLifecycleHookType(args[1]) && args.length > 2) wrappedArgs[2] = wrapRouteHookValue(args[2]);
417
+ return wrappedArgs;
418
+ };
419
+ const on = plugin.on.bind(plugin);
420
+ plugin.on = (...args) => on(...wrapLifecycleHookArgs(args));
421
+ }
422
+ /**
335
423
  * Creates Elysia plugin for HTTP request logging using LogTape.
336
424
  *
337
425
  * This plugin provides Morgan-compatible request logging with LogTape
@@ -417,6 +505,10 @@ function elysiaLogger(options = {}) {
417
505
  Object.assign(set.headers, requestContext.set.headers);
418
506
  }
419
507
  };
508
+ const applyRequestContextToRequest = (store, set, requestContext) => {
509
+ store.startTime = requestContext?.startTime ?? performance.now();
510
+ applyRequestContextToSet(set, requestContext);
511
+ };
420
512
  let plugin = new Elysia({
421
513
  name: "@logtape/elysia",
422
514
  seed: options
@@ -428,11 +520,12 @@ function elysiaLogger(options = {}) {
428
520
  return await withContext(requestContext?.context ?? {}, () => handle(request));
429
521
  };
430
522
  });
431
- plugin = plugin.state("startTime", 0).onRequest(async ({ request, set, store }) => {
432
- let requestContext = requestContextStates.get(request);
433
- if (requestContext == null && shouldWrapAllRoutes) requestContext = await buildAndStoreRequestContext(request);
434
- store.startTime = requestContext?.startTime ?? performance.now();
435
- applyRequestContextToSet(set, requestContext);
523
+ plugin = plugin.state("startTime", 0).onRequest(({ request, set, store }) => {
524
+ const requestContext = requestContextStates.get(request);
525
+ if (requestContext == null && shouldWrapAllRoutes) return buildAndStoreRequestContext(request).then((resolvedContext) => {
526
+ applyRequestContextToRequest(store, set, resolvedContext);
527
+ });
528
+ applyRequestContextToRequest(store, set, requestContext);
436
529
  });
437
530
  if (scope === "local" && (contextOptions != null || logRequest)) plugin = plugin.onBeforeHandle(async (ctx) => {
438
531
  const requestContext = await buildAndStoreRequestContext(ctx.request);
@@ -481,6 +574,7 @@ function elysiaLogger(options = {}) {
481
574
  errorCode: ctx.code
482
575
  });
483
576
  });
577
+ if (shouldWrapContext && scope === "local") wrapLocalLifecycleHooks(plugin, buildAndStoreRequestContext, applyRequestContextToSet);
484
578
  if (scope === "global") return plugin.as("global");
485
579
  else if (scope === "scoped") return plugin.as("scoped");
486
580
  return plugin;
package/dist/mod.js.map CHANGED
@@ -1 +1 @@
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","set: ElysiaContext[\"set\"] | undefined","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","elysiaRouteMethods: readonly ElysiaRouteMethod[]","plugin: unknown","plugin: ElysiaRoutePlugin","buildAndStoreRequestContext: (\n request: Request,\n ) => Promise<ElysiaRequestContextState | undefined>","applyRequestContextToSet: (\n set: ElysiaContext[\"set\"],\n requestContext: ElysiaRequestContextState | undefined,\n ) => void","handler: unknown","ctx: ElysiaRouteContext","routePlugin: unknown","restore: (() => void)[]","route","path: string","hook?: unknown","method: string","childPlugin: unknown","options: ElysiaLogTapeOptions","formatFn: FormatFunction","set: ElysiaContext[\"set\"]","requestContext: ElysiaRequestContextState | undefined","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 readonly set?: ElysiaContext[\"set\"];\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, \"http://localhost\").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 let set: ElysiaContext[\"set\"] | undefined;\n if (options.enrich != null) {\n 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, set };\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\ntype ElysiaRouteContext = ElysiaContext & {\n readonly store: LoggerStore;\n};\n\ntype ElysiaRouteHandler = (\n this: unknown,\n context: ElysiaRouteContext,\n) => unknown;\n\ntype ElysiaRouteRegistrar = (\n path: string,\n handler: unknown,\n hook?: unknown,\n) => unknown;\n\ntype ElysiaUseRegistrar = (\n plugin: unknown,\n ...options: unknown[]\n) => unknown;\n\ntype ElysiaRouteMethod =\n | \"all\"\n | \"connect\"\n | \"delete\"\n | \"get\"\n | \"head\"\n | \"options\"\n | \"patch\"\n | \"post\"\n | \"put\";\n\nconst elysiaRouteMethods: readonly ElysiaRouteMethod[] = [\n \"all\",\n \"connect\",\n \"delete\",\n \"get\",\n \"head\",\n \"options\",\n \"patch\",\n \"post\",\n \"put\",\n];\n\ntype ElysiaRoutePlugin = Record<ElysiaRouteMethod, ElysiaRouteRegistrar> & {\n readonly router?: {\n readonly history?: Record<string, ElysiaRouteEntry> | ElysiaRouteEntry[];\n };\n route: (\n method: string,\n path: string,\n handler: unknown,\n hook?: unknown,\n ) => unknown;\n use: ElysiaUseRegistrar;\n};\n\ninterface ElysiaRouteEntry {\n handler?: unknown;\n}\n\nfunction getElysiaRouteEntries(plugin: unknown): ElysiaRouteEntry[] {\n if (plugin == null || typeof plugin !== \"object\") return [];\n const routePlugin = plugin as {\n readonly default?: unknown;\n readonly router?: {\n readonly history?: Record<string, ElysiaRouteEntry> | ElysiaRouteEntry[];\n };\n };\n const history = routePlugin.router?.history;\n const entries = Array.isArray(history)\n ? history\n : history == null\n ? []\n : Object.values(history);\n return entries.concat(getElysiaRouteEntries(routePlugin.default));\n}\n\n/**\n * Wrap routes registered on a local plugin with implicit LogTape context.\n */\nfunction wrapLocalRouteHandlers(\n plugin: ElysiaRoutePlugin,\n buildAndStoreRequestContext: (\n request: Request,\n ) => Promise<ElysiaRequestContextState | undefined>,\n applyRequestContextToSet: (\n set: ElysiaContext[\"set\"],\n requestContext: ElysiaRequestContextState | undefined,\n ) => void,\n): void {\n const wrappedHandlers = new WeakSet<ElysiaRouteHandler>();\n const wrappedHandlerCache = new WeakMap<\n ElysiaRouteHandler,\n ElysiaRouteHandler\n >();\n const wrapHandler = (handler: unknown): unknown => {\n if (typeof handler !== \"function\") return handler;\n const routeHandler = handler as ElysiaRouteHandler;\n if (wrappedHandlers.has(routeHandler)) return handler;\n const cached = wrappedHandlerCache.get(routeHandler);\n if (cached != null) return cached;\n const wrapped = async function (\n this: unknown,\n ctx: ElysiaRouteContext,\n ): Promise<unknown> {\n const requestContext = await buildAndStoreRequestContext(ctx.request);\n ctx.store.startTime = requestContext?.startTime ??\n performance.now();\n applyRequestContextToSet(ctx.set, requestContext);\n return await withContext(\n requestContext?.context ?? {},\n () => routeHandler.call(this, ctx),\n );\n };\n wrappedHandlers.add(wrapped);\n wrappedHandlerCache.set(routeHandler, wrapped);\n return wrapped;\n };\n\n const wrapRouteEntries = (routePlugin: unknown): (() => void)[] => {\n const restore: (() => void)[] = [];\n for (const route of getElysiaRouteEntries(routePlugin)) {\n const handler = route.handler;\n const wrappedHandler = wrapHandler(handler);\n if (wrappedHandler === handler) continue;\n route.handler = wrappedHandler;\n restore.push(() => {\n route.handler = handler;\n });\n }\n return restore;\n };\n\n for (const method of elysiaRouteMethods) {\n const register = plugin[method].bind(plugin);\n plugin[method] = ((path: string, handler: unknown, hook?: unknown) =>\n register(path, wrapHandler(handler), hook)) as ElysiaRouteRegistrar;\n }\n\n const route = plugin.route.bind(plugin);\n plugin.route = ((\n method: string,\n path: string,\n handler: unknown,\n hook?: unknown,\n ) => route(method, path, wrapHandler(handler), hook)) as ElysiaRoutePlugin[\n \"route\"\n ];\n\n const use = plugin.use.bind(plugin);\n plugin.use = ((childPlugin: unknown, ...options: unknown[]) => {\n const restore = wrapRouteEntries(childPlugin);\n try {\n return use(childPlugin, ...options);\n } finally {\n for (const restoreRouteHandler of restore) restoreRouteHandler();\n }\n }) as ElysiaUseRegistrar;\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;\n const shouldWrapAllRoutes = 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 const buildAndStoreRequestContext = async (\n request: Request,\n ): Promise<ElysiaRequestContextState | undefined> => {\n if (contextOptions == null) return undefined;\n const existingContext = requestContextStates.get(request);\n if (existingContext != null) return existingContext;\n const startTime = performance.now();\n const requestContext = {\n ...await buildRequestContext(request, contextOptions),\n startTime,\n };\n requestContextStates.set(request, requestContext);\n return requestContext;\n };\n\n const applyRequestContextToSet = (\n set: ElysiaContext[\"set\"],\n requestContext: ElysiaRequestContextState | undefined,\n ): void => {\n if (requestContext?.responseHeader != null) {\n set.headers[requestContext.responseHeader.name] =\n requestContext.responseHeader.value;\n }\n if (requestContext?.set != null) {\n if (requestContext.set.status !== 200) {\n set.status = requestContext.set.status;\n }\n Object.assign(set.headers, requestContext.set.headers);\n }\n };\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 && scope === \"local\") {\n wrapLocalRouteHandlers(\n plugin as unknown as ElysiaRoutePlugin,\n buildAndStoreRequestContext,\n applyRequestContextToSet,\n );\n } else 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 requestContext = await buildAndStoreRequestContext(request);\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 && shouldWrapAllRoutes) {\n requestContext = await buildAndStoreRequestContext(request);\n }\n (store as LoggerStore).startTime = requestContext?.startTime ??\n performance.now();\n applyRequestContextToSet(set, requestContext);\n });\n\n if (scope === \"local\" && (contextOptions != null || logRequest)) {\n plugin = plugin.onBeforeHandle(async (ctx) => {\n const requestContext = await buildAndStoreRequestContext(ctx.request);\n (ctx.store as LoggerStore).startTime = requestContext?.startTime ??\n performance.now();\n applyRequestContextToSet(ctx.set, requestContext);\n if (logRequest && !skip(ctx as unknown as ElysiaContext)) {\n const context = requestContext?.context ?? {};\n const result = withRequestLogContext(\n formatFn(ctx as unknown as ElysiaContext, 0),\n context,\n );\n if (typeof result === \"string\") {\n logMethod(result, context);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n });\n }\n\n if (logRequest) {\n // Log immediately when request arrives\n if (scope !== \"local\") {\n plugin = plugin.onRequest((ctx) => {\n if (!skip(ctx as unknown as ElysiaContext)) {\n const requestContext =\n 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 }\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;;;;AAkB/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,SAA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,WAAW,SACpB,WAAU,QAAQ,eAAe;QAEjC,WAAU,kBAAkB,OAAO;GAEtC;EACF,EAAC;CACH,MAGD,UAAS,OAAO,cAAc,CAAC,QAAQ;AACrC,MAAI,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"}
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","set: ElysiaContext[\"set\"] | undefined","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","elysiaRouteMethods: readonly ElysiaRouteMethod[]","plugin: unknown","buildAndStoreRequestContext: (\n request: Request,\n ) => Promise<ElysiaRequestContextState | undefined>","applyRequestContextToSet: (\n set: ElysiaContext[\"set\"],\n requestContext: ElysiaRequestContextState | undefined,\n ) => void","value: unknown","callback: unknown","hooks: unknown","plugin: ElysiaRoutePlugin","routePlugin: unknown","restore: (() => void)[]","route","path: string","handler: unknown","hook?: unknown","method: string","childPlugin: unknown","args: readonly unknown[]","options: ElysiaLogTapeOptions","formatFn: FormatFunction","set: ElysiaContext[\"set\"]","requestContext: ElysiaRequestContextState | undefined","store: LoggerStore","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 readonly set?: ElysiaContext[\"set\"];\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, \"http://localhost\").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 let set: ElysiaContext[\"set\"] | undefined;\n if (options.enrich != null) {\n 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, set };\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\ntype ElysiaRouteContext = ElysiaContext & {\n readonly store: LoggerStore;\n};\n\ntype ElysiaRequestCallback = (\n this: unknown,\n ...args: unknown[]\n) => unknown;\n\ntype ElysiaRouteRegistrar = (\n path: string,\n handler: unknown,\n hook?: unknown,\n) => unknown;\n\ntype ElysiaUseRegistrar = (\n plugin: unknown,\n ...options: unknown[]\n) => unknown;\n\ntype ElysiaOnRegistrar = (...args: unknown[]) => unknown;\n\ntype ElysiaRouteMethod =\n | \"all\"\n | \"connect\"\n | \"delete\"\n | \"get\"\n | \"head\"\n | \"options\"\n | \"patch\"\n | \"post\"\n | \"put\";\n\nconst elysiaRouteMethods: readonly ElysiaRouteMethod[] = [\n \"all\",\n \"connect\",\n \"delete\",\n \"get\",\n \"head\",\n \"options\",\n \"patch\",\n \"post\",\n \"put\",\n];\n\nconst elysiaRouteHookKeys = [\n \"afterHandle\",\n \"afterResponse\",\n \"beforeHandle\",\n \"derive\",\n \"error\",\n \"mapResponse\",\n \"parse\",\n \"resolve\",\n \"transform\",\n] as const;\n\nconst elysiaPluginLifecycleHookTypes = [\n \"afterHandle\",\n \"afterResponse\",\n \"beforeHandle\",\n \"derive\",\n \"error\",\n \"mapResponse\",\n \"resolve\",\n \"transform\",\n] as const;\n\ntype ElysiaRoutePlugin = Record<ElysiaRouteMethod, ElysiaRouteRegistrar> & {\n readonly router?: {\n readonly history?: Record<string, ElysiaRouteEntry> | ElysiaRouteEntry[];\n };\n on: ElysiaOnRegistrar;\n route: (\n method: string,\n path: string,\n handler: unknown,\n hook?: unknown,\n ) => unknown;\n use: ElysiaUseRegistrar;\n};\n\ninterface ElysiaRouteEntry {\n handler?: unknown;\n hooks?: unknown;\n}\n\nfunction getElysiaRouteEntries(\n plugin: unknown,\n visited = new Set<object>(),\n): ElysiaRouteEntry[] {\n if (plugin == null || typeof plugin !== \"object\") return [];\n if (visited.has(plugin)) return [];\n visited.add(plugin);\n const routePlugin = plugin as {\n readonly default?: unknown;\n readonly router?: {\n readonly history?: Record<string, ElysiaRouteEntry> | ElysiaRouteEntry[];\n };\n };\n const history = routePlugin.router?.history;\n const entries = Array.isArray(history)\n ? history\n : history == null\n ? []\n : Object.values(history);\n return entries.concat(getElysiaRouteEntries(routePlugin.default, visited));\n}\n\nfunction createElysiaRequestWrappers(\n buildAndStoreRequestContext: (\n request: Request,\n ) => Promise<ElysiaRequestContextState | undefined>,\n applyRequestContextToSet: (\n set: ElysiaContext[\"set\"],\n requestContext: ElysiaRequestContextState | undefined,\n ) => void,\n) {\n const wrappedHandlers = new WeakSet<ElysiaRequestCallback>();\n const wrappedHandlerCache = new WeakMap<\n ElysiaRequestCallback,\n ElysiaRequestCallback\n >();\n\n const getRouteContext = (\n value: unknown,\n ): ElysiaRouteContext | undefined => {\n if (value == null || typeof value !== \"object\") return undefined;\n const context = value as { readonly request?: unknown };\n if (!(context.request instanceof Request)) return undefined;\n return value as ElysiaRouteContext;\n };\n\n const wrapRequestCallback = (callback: unknown): unknown => {\n if (typeof callback !== \"function\") return callback;\n const requestCallback = callback as ElysiaRequestCallback;\n if (wrappedHandlers.has(requestCallback)) return callback;\n const cached = wrappedHandlerCache.get(requestCallback);\n if (cached != null) return cached;\n const wrapped = async function (\n this: unknown,\n ...args: unknown[]\n ): Promise<unknown> {\n const ctx = getRouteContext(args[0]);\n if (ctx == null) return await requestCallback.apply(this, args);\n const requestContext = await buildAndStoreRequestContext(ctx.request);\n ctx.store.startTime = requestContext?.startTime ??\n performance.now();\n applyRequestContextToSet(ctx.set, requestContext);\n return await withContext(\n requestContext?.context ?? {},\n () => requestCallback.apply(this, args),\n );\n };\n wrappedHandlers.add(wrapped);\n wrappedHandlerCache.set(requestCallback, wrapped);\n return wrapped;\n };\n\n const wrapRouteHookValue = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(wrapRouteHookValue);\n if (typeof value === \"function\") return wrapRequestCallback(value);\n if (value == null || typeof value !== \"object\") return value;\n const hookContainer = value as { readonly fn?: unknown };\n if (typeof hookContainer.fn !== \"function\") return value;\n return {\n ...hookContainer,\n fn: wrapRequestCallback(hookContainer.fn),\n };\n };\n\n const wrapRouteHooks = (hooks: unknown): unknown => {\n if (hooks == null || typeof hooks !== \"object\") return hooks;\n const routeHooks = hooks as Record<string, unknown>;\n let changed = false;\n const wrappedHooks = { ...routeHooks };\n for (const key of elysiaRouteHookKeys) {\n const value = routeHooks[key];\n const wrappedValue = wrapRouteHookValue(value);\n if (wrappedValue === value) continue;\n wrappedHooks[key] = wrappedValue;\n changed = true;\n }\n return changed ? wrappedHooks : hooks;\n };\n\n return { wrapRequestCallback, wrapRouteHookValue, wrapRouteHooks };\n}\n\n/**\n * Wrap routes registered on a local plugin with implicit LogTape context.\n */\nfunction wrapLocalRouteHandlers(\n plugin: ElysiaRoutePlugin,\n buildAndStoreRequestContext: (\n request: Request,\n ) => Promise<ElysiaRequestContextState | undefined>,\n applyRequestContextToSet: (\n set: ElysiaContext[\"set\"],\n requestContext: ElysiaRequestContextState | undefined,\n ) => void,\n): void {\n const { wrapRequestCallback, wrapRouteHooks } = createElysiaRequestWrappers(\n buildAndStoreRequestContext,\n applyRequestContextToSet,\n );\n\n const wrapRouteEntries = (routePlugin: unknown): (() => void)[] => {\n const restore: (() => void)[] = [];\n for (const route of getElysiaRouteEntries(routePlugin)) {\n const handler = route.handler;\n const wrappedHandler = wrapRequestCallback(handler);\n if (wrappedHandler !== handler) {\n route.handler = wrappedHandler;\n restore.push(() => {\n route.handler = handler;\n });\n }\n const hooks = route.hooks;\n const wrappedHooks = wrapRouteHooks(hooks);\n if (wrappedHooks !== hooks) {\n route.hooks = wrappedHooks;\n restore.push(() => {\n route.hooks = hooks;\n });\n }\n }\n return restore;\n };\n\n for (const method of elysiaRouteMethods) {\n const register = plugin[method].bind(plugin);\n plugin[method] = ((path: string, handler: unknown, hook?: unknown) =>\n register(\n path,\n wrapRequestCallback(handler),\n wrapRouteHooks(hook),\n )) as ElysiaRouteRegistrar;\n }\n\n const route = plugin.route.bind(plugin);\n plugin.route = ((\n method: string,\n path: string,\n handler: unknown,\n hook?: unknown,\n ) =>\n route(\n method,\n path,\n wrapRequestCallback(handler),\n wrapRouteHooks(hook),\n )) as ElysiaRoutePlugin[\"route\"];\n\n const use = plugin.use.bind(plugin);\n plugin.use = ((childPlugin: unknown, ...options: unknown[]) => {\n const restore = wrapRouteEntries(childPlugin);\n try {\n return use(childPlugin, ...options);\n } finally {\n for (const restoreRouteHandler of restore) restoreRouteHandler();\n }\n }) as ElysiaUseRegistrar;\n}\n\n/**\n * Wrap local plugin lifecycle hooks registered by downstream code.\n */\nfunction wrapLocalLifecycleHooks(\n plugin: ElysiaRoutePlugin,\n buildAndStoreRequestContext: (\n request: Request,\n ) => Promise<ElysiaRequestContextState | undefined>,\n applyRequestContextToSet: (\n set: ElysiaContext[\"set\"],\n requestContext: ElysiaRequestContextState | undefined,\n ) => void,\n): void {\n const { wrapRouteHookValue } = createElysiaRequestWrappers(\n buildAndStoreRequestContext,\n applyRequestContextToSet,\n );\n\n const isLifecycleHookType = (value: unknown): boolean =>\n typeof value === \"string\" &&\n (elysiaPluginLifecycleHookTypes as readonly string[]).includes(value);\n\n const wrapLifecycleHookArgs = (args: readonly unknown[]): unknown[] => {\n const wrappedArgs = [...args];\n if (isLifecycleHookType(args[0]) && args.length > 1) {\n wrappedArgs[1] = wrapRouteHookValue(args[1]);\n } else if (isLifecycleHookType(args[1]) && args.length > 2) {\n wrappedArgs[2] = wrapRouteHookValue(args[2]);\n }\n return wrappedArgs;\n };\n\n const on = plugin.on.bind(plugin);\n plugin.on =\n ((...args: unknown[]) =>\n on(...wrapLifecycleHookArgs(args))) as ElysiaOnRegistrar;\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;\n const shouldWrapAllRoutes = 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 const buildAndStoreRequestContext = async (\n request: Request,\n ): Promise<ElysiaRequestContextState | undefined> => {\n if (contextOptions == null) return undefined;\n const existingContext = requestContextStates.get(request);\n if (existingContext != null) return existingContext;\n const startTime = performance.now();\n const requestContext = {\n ...await buildRequestContext(request, contextOptions),\n startTime,\n };\n requestContextStates.set(request, requestContext);\n return requestContext;\n };\n\n const applyRequestContextToSet = (\n set: ElysiaContext[\"set\"],\n requestContext: ElysiaRequestContextState | undefined,\n ): void => {\n if (requestContext?.responseHeader != null) {\n set.headers[requestContext.responseHeader.name] =\n requestContext.responseHeader.value;\n }\n if (requestContext?.set != null) {\n if (requestContext.set.status !== 200) {\n set.status = requestContext.set.status;\n }\n Object.assign(set.headers, requestContext.set.headers);\n }\n };\n\n const applyRequestContextToRequest = (\n store: LoggerStore,\n set: ElysiaContext[\"set\"],\n requestContext: ElysiaRequestContextState | undefined,\n ): void => {\n store.startTime = requestContext?.startTime ?? performance.now();\n applyRequestContextToSet(set, requestContext);\n };\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 && scope === \"local\") {\n wrapLocalRouteHandlers(\n plugin as unknown as ElysiaRoutePlugin,\n buildAndStoreRequestContext,\n applyRequestContextToSet,\n );\n } else 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 requestContext = await buildAndStoreRequestContext(request);\n return await withContext(\n requestContext?.context ?? {},\n () => handle(request),\n );\n };\n });\n }\n\n plugin = plugin\n .state(\"startTime\", 0)\n .onRequest(({ request, set, store }) => {\n const requestContext = requestContextStates.get(request);\n if (requestContext == null && shouldWrapAllRoutes) {\n return buildAndStoreRequestContext(request).then((resolvedContext) => {\n applyRequestContextToRequest(\n store as LoggerStore,\n set,\n resolvedContext,\n );\n });\n }\n applyRequestContextToRequest(store as LoggerStore, set, requestContext);\n });\n\n if (scope === \"local\" && (contextOptions != null || logRequest)) {\n plugin = plugin.onBeforeHandle(async (ctx) => {\n const requestContext = await buildAndStoreRequestContext(ctx.request);\n (ctx.store as LoggerStore).startTime = requestContext?.startTime ??\n performance.now();\n applyRequestContextToSet(ctx.set, requestContext);\n if (logRequest && !skip(ctx as unknown as ElysiaContext)) {\n const context = requestContext?.context ?? {};\n const result = withRequestLogContext(\n formatFn(ctx as unknown as ElysiaContext, 0),\n context,\n );\n if (typeof result === \"string\") {\n logMethod(result, context);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n });\n }\n\n if (logRequest) {\n // Log immediately when request arrives\n if (scope !== \"local\") {\n plugin = plugin.onRequest((ctx) => {\n if (!skip(ctx as unknown as ElysiaContext)) {\n const requestContext =\n 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 }\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 if (shouldWrapContext && scope === \"local\") {\n wrapLocalLifecycleHooks(\n plugin as unknown as ElysiaRoutePlugin,\n buildAndStoreRequestContext,\n applyRequestContextToSet,\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;;;;AAkB/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,QAAQC,SAA0B;AACzC,QAAO,IAAI,IAAI,QAAQ,KAAK,oBAAoB;AACjD;;;;AAKD,SAAS,iBACPA,SACAC,SAKA;CACA,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,cAAc,QAAQ,eAAe,CAAC,sBAAuB;AACnE,MAAK,MAAM,cAAc,aAAa;EACpC,MAAM,cAAc,QAAQ,QAAQ,IAAI,WAAW;AACnD,MAAI,eAAe,KAAM;E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,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.700+748dd292",
3
+ "version": "2.2.0-dev.708+280ccb86",
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.700+748dd292"
57
+ "@logtape/logtape": "^2.2.0-dev.708+280ccb86"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@alinea/suite": "^0.6.3",