@logtape/koa 2.2.0-dev.761 → 2.2.0-dev.767

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
@@ -119,11 +119,18 @@ app.use(koaLogger({
119
119
  Predefined formats
120
120
  ------------------
121
121
 
122
- - `"combined"` - Apache Combined Log Format with all properties (default)
123
- - `"common"` - Apache Common Log Format (without referrer/userAgent)
124
- - `"dev"` - Concise output for development
125
- - `"short"` - Shorter format with remote address
126
- - `"tiny"` - Minimal output
122
+ The middleware supports structured presets and text presets:
123
+
124
+ - `"structured-combined"`: Structured request properties (default)
125
+ - `"structured-common"`: Structured request properties without
126
+ `referrer`/`userAgent`
127
+ - `"combined"`: Deprecated alias for `"structured-combined"`
128
+ - `"common"`: Deprecated alias for `"structured-common"`
129
+ - `"morgan-combined"`: Morgan-compatible Apache combined access log output
130
+ - `"morgan-common"`: Morgan-compatible Apache common access log output
131
+ - `"dev"`: Concise output for development
132
+ - `"short"`: Shorter format with remote address
133
+ - `"tiny"`: Minimal output
127
134
 
128
135
 
129
136
  Custom format
package/dist/mod.cjs CHANGED
@@ -160,16 +160,66 @@ function withRequestLogContext(result, context) {
160
160
  ...context
161
161
  };
162
162
  }
163
+ const clfMonths = [
164
+ "Jan",
165
+ "Feb",
166
+ "Mar",
167
+ "Apr",
168
+ "May",
169
+ "Jun",
170
+ "Jul",
171
+ "Aug",
172
+ "Sep",
173
+ "Oct",
174
+ "Nov",
175
+ "Dec"
176
+ ];
177
+ function pad2(value) {
178
+ return value.toString().padStart(2, "0");
179
+ }
180
+ function formatClfDate(timestamp = Date.now()) {
181
+ const date = new Date(timestamp);
182
+ return `${pad2(date.getUTCDate())}/${clfMonths[date.getUTCMonth()]}/${date.getUTCFullYear()}:${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}:${pad2(date.getUTCSeconds())} +0000`;
183
+ }
184
+ function escapeAccessLogValue(value, escapeSpaces) {
185
+ const escaped = String(value).replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
186
+ return escapeSpaces ? escaped.replace(/ /g, "\\x20") : escaped;
187
+ }
188
+ function formatAccessLogToken(value) {
189
+ if (value == null || value === "") return "-";
190
+ return escapeAccessLogValue(value, true);
191
+ }
192
+ function formatAccessLogQuotedToken(value) {
193
+ if (value == null || value === "") return "\"-\"";
194
+ return `"${escapeAccessLogValue(value, false)}"`;
195
+ }
196
+ function getRemoteUser(ctx) {
197
+ const authorization = ctx.get("authorization");
198
+ if (authorization === "") return void 0;
199
+ const match = /^Basic\s+(.+)$/i.exec(authorization);
200
+ if (match == null || typeof globalThis.atob !== "function") return void 0;
201
+ try {
202
+ const decoded = globalThis.atob(match[1]);
203
+ const colonIndex = decoded.indexOf(":");
204
+ const user = colonIndex < 0 ? decoded : decoded.slice(0, colonIndex);
205
+ return user === "" ? void 0 : user;
206
+ } catch {
207
+ return void 0;
208
+ }
209
+ }
210
+ function getHttpVersion(ctx) {
211
+ return ctx.req?.httpVersion;
212
+ }
163
213
  /**
164
- * Combined format (Apache Combined Log Format).
214
+ * Structured combined format.
165
215
  * Returns all structured properties.
166
216
  */
167
217
  function formatCombined(ctx, responseTime) {
168
218
  return { ...buildProperties(ctx, responseTime) };
169
219
  }
170
220
  /**
171
- * Common format (Apache Common Log Format).
172
- * Like combined but without referrer and userAgent.
221
+ * Structured common format.
222
+ * Like structured combined but without referrer and userAgent.
173
223
  */
174
224
  function formatCommon(ctx, responseTime) {
175
225
  const props = buildProperties(ctx, responseTime);
@@ -177,6 +227,23 @@ function formatCommon(ctx, responseTime) {
177
227
  return rest;
178
228
  }
179
229
  /**
230
+ * Morgan combined format.
231
+ * :remote-addr - :remote-user [:date[clf]]
232
+ * ":method :url HTTP/:http-version" :status :res[content-length]
233
+ * ":referrer" ":user-agent"
234
+ */
235
+ function formatMorganCombined(ctx) {
236
+ return `${formatAccessLogToken(getRemoteAddr(ctx))} - ${formatAccessLogToken(getRemoteUser(ctx))} [${formatClfDate()}] "${formatAccessLogToken(ctx.method)} ${formatAccessLogToken(ctx.url)} HTTP/${formatAccessLogToken(getHttpVersion(ctx))}" ${formatAccessLogToken(ctx.status)} ${formatAccessLogToken(getContentLength(ctx))} ${formatAccessLogQuotedToken(getReferrer(ctx))} ${formatAccessLogQuotedToken(getUserAgent(ctx))}`;
237
+ }
238
+ /**
239
+ * Morgan common format.
240
+ * :remote-addr - :remote-user [:date[clf]]
241
+ * ":method :url HTTP/:http-version" :status :res[content-length]
242
+ */
243
+ function formatMorganCommon(ctx) {
244
+ return `${formatAccessLogToken(getRemoteAddr(ctx))} - ${formatAccessLogToken(getRemoteUser(ctx))} [${formatClfDate()}] "${formatAccessLogToken(ctx.method)} ${formatAccessLogToken(ctx.url)} HTTP/${formatAccessLogToken(getHttpVersion(ctx))}" ${formatAccessLogToken(ctx.status)} ${formatAccessLogToken(getContentLength(ctx))}`;
245
+ }
246
+ /**
180
247
  * Dev format (colored output for development).
181
248
  * :method :path :status :response-time ms - :res[content-length]
182
249
  */
@@ -207,6 +274,10 @@ function formatTiny(ctx, responseTime) {
207
274
  const predefinedFormats = {
208
275
  combined: formatCombined,
209
276
  common: formatCommon,
277
+ "structured-combined": formatCombined,
278
+ "structured-common": formatCommon,
279
+ "morgan-combined": formatMorganCombined,
280
+ "morgan-common": formatMorganCommon,
210
281
  dev: formatDev,
211
282
  short: formatShort,
212
283
  tiny: formatTiny
@@ -277,7 +348,7 @@ function koaLogger(options = {}) {
277
348
  const category = normalizeCategory(options.category ?? ["koa"]);
278
349
  const logger = (0, __logtape_logtape.getLogger)(category);
279
350
  const level = options.level ?? "info";
280
- const formatOption = options.format ?? "combined";
351
+ const formatOption = options.format ?? "structured-combined";
281
352
  const skip = options.skip ?? (() => false);
282
353
  const logRequest = options.logRequest ?? false;
283
354
  const contextOptions = normalizeRequestContextOptions(options.context);
package/dist/mod.d.cts CHANGED
@@ -25,6 +25,10 @@ interface KoaContext {
25
25
  response: {
26
26
  length?: number;
27
27
  };
28
+ /** Node.js request object, when available. */
29
+ req?: {
30
+ httpVersion?: string;
31
+ };
28
32
  /**
29
33
  * Get a request header field value (case-insensitive).
30
34
  * @param field The header field name.
@@ -44,10 +48,17 @@ interface KoaContext {
44
48
  */
45
49
  type KoaMiddleware = (ctx: KoaContext, next: () => Promise<void>) => Promise<void>;
46
50
  /**
47
- * Predefined log format names compatible with Morgan.
51
+ * Predefined log format names.
48
52
  * @since 1.3.0
49
53
  */
50
- type PredefinedFormat = "combined" | "common" | "dev" | "short" | "tiny";
54
+ type PredefinedFormat =
55
+ /**
56
+ * @deprecated Use `"structured-combined"` instead.
57
+ */
58
+ "combined"
59
+ /**
60
+ * @deprecated Use `"structured-common"` instead.
61
+ */ | "common" | "structured-combined" | "structured-common" | "morgan-combined" | "morgan-common" | "dev" | "short" | "tiny";
51
62
  /**
52
63
  * Custom format function for request logging.
53
64
  *
@@ -157,14 +168,21 @@ interface KoaLogTapeOptions {
157
168
  * The format for log output.
158
169
  * Can be a predefined format name or a custom format function.
159
170
  *
160
- * Predefined formats:
161
- * - `"combined"` - Apache Combined Log Format (structured, default)
162
- * - `"common"` - Apache Common Log Format (structured, no referrer/userAgent)
171
+ * Structured formats:
172
+ * - `"structured-combined"` - Structured request properties (default)
173
+ * - `"structured-common"` - Structured request properties without
174
+ * referrer/userAgent
175
+ * - `"combined"` - Deprecated alias for `"structured-combined"`
176
+ * - `"common"` - Deprecated alias for `"structured-common"`
177
+ *
178
+ * Text formats:
179
+ * - `"morgan-combined"` - Morgan-compatible combined access log (string)
180
+ * - `"morgan-common"` - Morgan-compatible common access log (string)
163
181
  * - `"dev"` - Concise colored output for development (string)
164
182
  * - `"short"` - Shorter than common (string)
165
183
  * - `"tiny"` - Minimal output (string)
166
184
  *
167
- * @default "combined"
185
+ * @default "structured-combined"
168
186
  */
169
187
  readonly format?: PredefinedFormat | FormatFunction;
170
188
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"mod.d.cts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;AAYA;AAiCA;;;;;AAGY;AAMA,UA1CK,UAAA,CA0CW;EAUhB;EAAc,MAAA,EAAA,MAAA;EAAA;EACT,GAEH,EAAA,MAAA;EAAM;EAMH,IAAA,EAAA,MAAA;EAyBL;EAaK,MAAA,EAAA,MAAA;EAqCA;EAAqB,EAAA,EAAA,MAAA;EAAA;EAKW,QAMnB,EAAA;IAMrB,MAAA,CAAA,EAAA,MAAA;EAAU,CAAA;EACN;;AAA2B;AAOxC;;EAAkC,GAWf,CAAA,KAAA,EAAA,MAAA,CAAA,EAAA,MAAA;EAAQ;;;;AAsDyB;EAkVpC,GAAA,EAAA,KAAA,EAAS,MAAA,EAAA,KAAA,EAAA,MAAA,CAAA,EAAA,IAAA;;;;AAET;;KArhBJ,aAAA,SACL,wBACO,kBACT;;;;;KAMO,gBAAA;;;;;;;;;KAUA,cAAA,SACL,8CAEO;;;;;UAMG,oBAAA;;;;;;;;;;;;;;;;;;;;;;;;KAyBL,mBAAA;;;;;UAaK,gBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAqCA,qBAAA;;;;;iCAKgB;;;;;8BAMH;;;;0BAMrB,eACF,0BAA0B,QAAQ;;;;;;UAOxB,iBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;oBAeC,mBAAmB;;;;;;;;;;;;;;wBAef;;;;;;;;;;;;;;;;;;;;;;+BAwBO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAkVf,SAAA,WACL,oBACR"}
1
+ {"version":3,"file":"mod.d.cts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;AAYA;AAqCA;;;;;AAGY;AAMA,UA9CK,UAAA,CA8CW;EAyBhB;EAAc,MAAA,EAAA,MAAA;EAAA;EACT,GAEH,EAAA,MAAA;EAAM;EAMH,IAAA,EAAA,MAAA;EAyBL;EAaK,MAAA,EAAA,MAAA;EAqCA;EAAqB,EAAA,EAAA,MAAA;EAAA;EAKW,QAMnB,EAAA;IAMrB,MAAA,CAAA,EAAA,MAAA;EAAU,CAAA;EACN;EAAkC,GAAd,CAAA,EAAA;IAAO,WAAA,CAAA,EAAA,MAAA;EAOvB,CAAA;EAAiB;;;;;EAgDA,GAwBH,CAAA,KAAA,EAAA,MAAA,CAAA,EAAA,MAAA;EAAqB;AA4bpD;;;;EAEgB,GAAA,EAAA,KAAA,EAAA,MAAA,EAAA,KAAA,EAAA,MAAA,CAAA,EAAA,IAAA;;;;;;KArpBJ,aAAA,SACL,wBACO,kBACT;;;;;KAMO,gBAAA;;;;;;;;;;;;;;;;KAyBA,cAAA,SACL,8CAEO;;;;;UAMG,oBAAA;;;;;;;;;;;;;;;;;;;;;;;;KAyBL,mBAAA;;;;;UAaK,gBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAqCA,qBAAA;;;;;iCAKgB;;;;;8BAMH;;;;0BAMrB,eACF,0BAA0B,QAAQ;;;;;;UAOxB,iBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;;;;;;;;oBAsBC,mBAAmB;;;;;;;;;;;;;;wBAef;;;;;;;;;;;;;;;;;;;;;;+BAwBO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA4bf,SAAA,WACL,oBACR"}
package/dist/mod.d.ts CHANGED
@@ -25,6 +25,10 @@ interface KoaContext {
25
25
  response: {
26
26
  length?: number;
27
27
  };
28
+ /** Node.js request object, when available. */
29
+ req?: {
30
+ httpVersion?: string;
31
+ };
28
32
  /**
29
33
  * Get a request header field value (case-insensitive).
30
34
  * @param field The header field name.
@@ -44,10 +48,17 @@ interface KoaContext {
44
48
  */
45
49
  type KoaMiddleware = (ctx: KoaContext, next: () => Promise<void>) => Promise<void>;
46
50
  /**
47
- * Predefined log format names compatible with Morgan.
51
+ * Predefined log format names.
48
52
  * @since 1.3.0
49
53
  */
50
- type PredefinedFormat = "combined" | "common" | "dev" | "short" | "tiny";
54
+ type PredefinedFormat =
55
+ /**
56
+ * @deprecated Use `"structured-combined"` instead.
57
+ */
58
+ "combined"
59
+ /**
60
+ * @deprecated Use `"structured-common"` instead.
61
+ */ | "common" | "structured-combined" | "structured-common" | "morgan-combined" | "morgan-common" | "dev" | "short" | "tiny";
51
62
  /**
52
63
  * Custom format function for request logging.
53
64
  *
@@ -157,14 +168,21 @@ interface KoaLogTapeOptions {
157
168
  * The format for log output.
158
169
  * Can be a predefined format name or a custom format function.
159
170
  *
160
- * Predefined formats:
161
- * - `"combined"` - Apache Combined Log Format (structured, default)
162
- * - `"common"` - Apache Common Log Format (structured, no referrer/userAgent)
171
+ * Structured formats:
172
+ * - `"structured-combined"` - Structured request properties (default)
173
+ * - `"structured-common"` - Structured request properties without
174
+ * referrer/userAgent
175
+ * - `"combined"` - Deprecated alias for `"structured-combined"`
176
+ * - `"common"` - Deprecated alias for `"structured-common"`
177
+ *
178
+ * Text formats:
179
+ * - `"morgan-combined"` - Morgan-compatible combined access log (string)
180
+ * - `"morgan-common"` - Morgan-compatible common access log (string)
163
181
  * - `"dev"` - Concise colored output for development (string)
164
182
  * - `"short"` - Shorter than common (string)
165
183
  * - `"tiny"` - Minimal output (string)
166
184
  *
167
- * @default "combined"
185
+ * @default "structured-combined"
168
186
  */
169
187
  readonly format?: PredefinedFormat | FormatFunction;
170
188
  /**
package/dist/mod.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mod.d.ts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;AAYA;AAiCA;;;;;AAGY;AAMA,UA1CK,UAAA,CA0CW;EAUhB;EAAc,MAAA,EAAA,MAAA;EAAA;EACT,GAEH,EAAA,MAAA;EAAM;EAMH,IAAA,EAAA,MAAA;EAyBL;EAaK,MAAA,EAAA,MAAA;EAqCA;EAAqB,EAAA,EAAA,MAAA;EAAA;EA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qB;AA4bpD;;;;EAEgB,GAAA,EAAA,KAAA,EAAA,MAAA,EAAA,KAAA,EAAA,MAAA,CAAA,EAAA,IAAA;;;;;;KArpBJ,aAAA,SACL,wBACO,kBACT;;;;;KAMO,gBAAA;;;;;;;;;;;;;;;;KAyBA,cAAA,SACL,8CAEO;;;;;UAMG,oBAAA;;;;;;;;;;;;;;;;;;;;;;;;KAyBL,mBAAA;;;;;UAaK,gBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAqCA,qBAAA;;;;;iCAKgB;;;;;8BAMH;;;;0BAMrB,eACF,0BAA0B,QAAQ;;;;;;UAOxB,iBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;;;;;;;;oBAsBC,mBAAmB;;;;;;;;;;;;;;wBAef;;;;;;;;;;;;;;;;;;;;;;+BAwBO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA4bf,SAAA,WACL,oBACR"}
package/dist/mod.js CHANGED
@@ -159,16 +159,66 @@ function withRequestLogContext(result, context) {
159
159
  ...context
160
160
  };
161
161
  }
162
+ const clfMonths = [
163
+ "Jan",
164
+ "Feb",
165
+ "Mar",
166
+ "Apr",
167
+ "May",
168
+ "Jun",
169
+ "Jul",
170
+ "Aug",
171
+ "Sep",
172
+ "Oct",
173
+ "Nov",
174
+ "Dec"
175
+ ];
176
+ function pad2(value) {
177
+ return value.toString().padStart(2, "0");
178
+ }
179
+ function formatClfDate(timestamp = Date.now()) {
180
+ const date = new Date(timestamp);
181
+ return `${pad2(date.getUTCDate())}/${clfMonths[date.getUTCMonth()]}/${date.getUTCFullYear()}:${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}:${pad2(date.getUTCSeconds())} +0000`;
182
+ }
183
+ function escapeAccessLogValue(value, escapeSpaces) {
184
+ const escaped = String(value).replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
185
+ return escapeSpaces ? escaped.replace(/ /g, "\\x20") : escaped;
186
+ }
187
+ function formatAccessLogToken(value) {
188
+ if (value == null || value === "") return "-";
189
+ return escapeAccessLogValue(value, true);
190
+ }
191
+ function formatAccessLogQuotedToken(value) {
192
+ if (value == null || value === "") return "\"-\"";
193
+ return `"${escapeAccessLogValue(value, false)}"`;
194
+ }
195
+ function getRemoteUser(ctx) {
196
+ const authorization = ctx.get("authorization");
197
+ if (authorization === "") return void 0;
198
+ const match = /^Basic\s+(.+)$/i.exec(authorization);
199
+ if (match == null || typeof globalThis.atob !== "function") return void 0;
200
+ try {
201
+ const decoded = globalThis.atob(match[1]);
202
+ const colonIndex = decoded.indexOf(":");
203
+ const user = colonIndex < 0 ? decoded : decoded.slice(0, colonIndex);
204
+ return user === "" ? void 0 : user;
205
+ } catch {
206
+ return void 0;
207
+ }
208
+ }
209
+ function getHttpVersion(ctx) {
210
+ return ctx.req?.httpVersion;
211
+ }
162
212
  /**
163
- * Combined format (Apache Combined Log Format).
213
+ * Structured combined format.
164
214
  * Returns all structured properties.
165
215
  */
166
216
  function formatCombined(ctx, responseTime) {
167
217
  return { ...buildProperties(ctx, responseTime) };
168
218
  }
169
219
  /**
170
- * Common format (Apache Common Log Format).
171
- * Like combined but without referrer and userAgent.
220
+ * Structured common format.
221
+ * Like structured combined but without referrer and userAgent.
172
222
  */
173
223
  function formatCommon(ctx, responseTime) {
174
224
  const props = buildProperties(ctx, responseTime);
@@ -176,6 +226,23 @@ function formatCommon(ctx, responseTime) {
176
226
  return rest;
177
227
  }
178
228
  /**
229
+ * Morgan combined format.
230
+ * :remote-addr - :remote-user [:date[clf]]
231
+ * ":method :url HTTP/:http-version" :status :res[content-length]
232
+ * ":referrer" ":user-agent"
233
+ */
234
+ function formatMorganCombined(ctx) {
235
+ return `${formatAccessLogToken(getRemoteAddr(ctx))} - ${formatAccessLogToken(getRemoteUser(ctx))} [${formatClfDate()}] "${formatAccessLogToken(ctx.method)} ${formatAccessLogToken(ctx.url)} HTTP/${formatAccessLogToken(getHttpVersion(ctx))}" ${formatAccessLogToken(ctx.status)} ${formatAccessLogToken(getContentLength(ctx))} ${formatAccessLogQuotedToken(getReferrer(ctx))} ${formatAccessLogQuotedToken(getUserAgent(ctx))}`;
236
+ }
237
+ /**
238
+ * Morgan common format.
239
+ * :remote-addr - :remote-user [:date[clf]]
240
+ * ":method :url HTTP/:http-version" :status :res[content-length]
241
+ */
242
+ function formatMorganCommon(ctx) {
243
+ return `${formatAccessLogToken(getRemoteAddr(ctx))} - ${formatAccessLogToken(getRemoteUser(ctx))} [${formatClfDate()}] "${formatAccessLogToken(ctx.method)} ${formatAccessLogToken(ctx.url)} HTTP/${formatAccessLogToken(getHttpVersion(ctx))}" ${formatAccessLogToken(ctx.status)} ${formatAccessLogToken(getContentLength(ctx))}`;
244
+ }
245
+ /**
179
246
  * Dev format (colored output for development).
180
247
  * :method :path :status :response-time ms - :res[content-length]
181
248
  */
@@ -206,6 +273,10 @@ function formatTiny(ctx, responseTime) {
206
273
  const predefinedFormats = {
207
274
  combined: formatCombined,
208
275
  common: formatCommon,
276
+ "structured-combined": formatCombined,
277
+ "structured-common": formatCommon,
278
+ "morgan-combined": formatMorganCombined,
279
+ "morgan-common": formatMorganCommon,
209
280
  dev: formatDev,
210
281
  short: formatShort,
211
282
  tiny: formatTiny
@@ -276,7 +347,7 @@ function koaLogger(options = {}) {
276
347
  const category = normalizeCategory(options.category ?? ["koa"]);
277
348
  const logger = getLogger(category);
278
349
  const level = options.level ?? "info";
279
- const formatOption = options.format ?? "combined";
350
+ const formatOption = options.format ?? "structured-combined";
280
351
  const skip = options.skip ?? (() => false);
281
352
  const logRequest = options.logRequest ?? false;
282
353
  const contextOptions = normalizeRequestContextOptions(options.context);
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","ctx: KoaContext","options: RequestIdOptions","responseHeader","responseTime: number","resolvedRequestId: { property: string; value: string } | undefined","include: readonly RequestContextField[]","context: Record<string, unknown>","options: RequestContextOptions","result: string | Record<string, unknown>","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","options: KoaLogTapeOptions","formatFn: FormatFunction","next: () => Promise<void>","requestContext: Record<string, unknown>","result","requestContext"],"sources":["../src/mod.ts"],"sourcesContent":["import { getLogger, type LogLevel, withContext } from \"@logtape/logtape\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n/**\n * Minimal Koa Context interface for compatibility across Koa 2.x and 3.x.\n *\n * This interface includes common aliases available on the Koa context object.\n * See https://koajs.com/#context for the full API.\n *\n * @since 1.3.0\n */\nexport interface KoaContext {\n /** HTTP request method (alias for ctx.request.method) */\n method: string;\n /** Request URL (alias for ctx.request.url) */\n url: string;\n /** Request pathname (alias for ctx.request.path) */\n path: string;\n /** HTTP response status code (alias for ctx.response.status) */\n status: number;\n /** Remote client IP address (alias for ctx.request.ip) */\n ip: string;\n /** Koa Response object */\n response: {\n length?: number;\n };\n /**\n * Get a request header field value (case-insensitive).\n * @param field The header field name.\n * @returns The header value, or an empty string if not present.\n */\n get(field: string): string;\n /**\n * Set a response header field value.\n * @param field The header field name.\n * @param value The header field value.\n */\n set?(field: string, value: string): void;\n}\n\n/**\n * Koa middleware function type.\n * @since 1.3.0\n */\nexport type KoaMiddleware = (\n ctx: KoaContext,\n next: () => Promise<void>,\n) => Promise<void>;\n\n/**\n * Predefined log format names compatible with Morgan.\n * @since 1.3.0\n */\nexport type PredefinedFormat = \"combined\" | \"common\" | \"dev\" | \"short\" | \"tiny\";\n\n/**\n * Custom format function for request logging.\n *\n * @param ctx The Koa context object.\n * @param responseTime The response time in milliseconds.\n * @returns A string message or an object with structured properties.\n * @since 1.3.0\n */\nexport type FormatFunction = (\n ctx: KoaContext,\n responseTime: number,\n) => string | Record<string, unknown>;\n\n/**\n * Structured log properties for HTTP requests.\n * @since 1.3.0\n */\nexport interface RequestLogProperties {\n /** HTTP request method */\n method: string;\n /** Request URL */\n url: string;\n /** 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 */\n contentLength: number | undefined;\n /** Remote client address */\n remoteAddr: string | undefined;\n /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\n}\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: KoaContext,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n}\n\n/**\n * Options for configuring the Koa LogTape middleware.\n * @since 1.3.0\n */\nexport interface KoaLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"koa\"]\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(koaLogger({\n * skip: (ctx) => ctx.path === \"/health\",\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (ctx: KoaContext) => 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 * Enables request-scoped implicit context and request ID correlation.\n *\n * When set to `true`, the middleware reads the `x-request-id` header,\n * generates one when it is absent, writes it to the `x-request-id` response\n * header, and adds `requestId` to all LogTape records emitted while handling\n * the request.\n *\n * @default false\n * @since 2.2.0\n */\n readonly context?: boolean | RequestContextOptions;\n}\n\nconst defaultRequestIdHeader = \"x-request-id\";\n\n/**\n * Normalize request context options.\n */\nfunction normalizeRequestContextOptions(\n options: boolean | RequestContextOptions | undefined,\n): RequestContextOptions | undefined {\n if (options === true) return {};\n if (options === false || options == null) return undefined;\n return options;\n}\n\n/**\n * Normalize request ID options.\n */\nfunction normalizeRequestIdOptions(\n options: boolean | RequestIdOptions | undefined,\n): RequestIdOptions | undefined {\n if (options === false) return undefined;\n if (options === true || options == null) return {};\n return options;\n}\n\n/**\n * Generate a request ID with Web Crypto when possible.\n */\nfunction generateRequestId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Normalize an incoming request ID.\n */\nfunction defaultNormalizeRequestId(value: string): string | null {\n const trimmed = value.trim();\n return trimmed === \"\" ? null : trimmed;\n}\n\n/**\n * Resolve the request ID for a request.\n */\nfunction resolveRequestId(\n ctx: KoaContext,\n options: RequestIdOptions,\n): { property: string; value: string } {\n const property = options.property ?? \"requestId\";\n const normalize = options.normalize ?? defaultNormalizeRequestId;\n const headerNames = options.headerNames ?? [defaultRequestIdHeader];\n for (const headerName of headerNames) {\n const headerValue = ctx.get(headerName);\n if (headerValue === \"\") continue;\n const normalized = normalize(headerValue);\n if (normalized != null) {\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n if (responseHeader !== false) ctx.set?.(responseHeader, normalized);\n return { property, value: normalized };\n }\n }\n const generated = (options.generate ?? generateRequestId)();\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n if (responseHeader !== false) ctx.set?.(responseHeader, generated);\n return { property, value: generated };\n}\n\n/**\n * Get referrer from request headers.\n * Returns undefined if the header is not present or empty.\n */\nfunction getReferrer(ctx: KoaContext): string | undefined {\n const referrer = ctx.get(\"referrer\") || ctx.get(\"referer\");\n return referrer !== \"\" ? referrer : undefined;\n}\n\n/**\n * Get user agent from request headers.\n * Returns undefined if the header is not present or empty.\n */\nfunction getUserAgent(ctx: KoaContext): string | undefined {\n const userAgent = ctx.get(\"user-agent\");\n return userAgent !== \"\" ? userAgent : undefined;\n}\n\n/**\n * Get remote address from context.\n * Returns undefined if not available.\n */\nfunction getRemoteAddr(ctx: KoaContext): string | undefined {\n return ctx.ip !== \"\" ? ctx.ip : undefined;\n}\n\n/**\n * Get content length from response.\n */\nfunction getContentLength(ctx: KoaContext): number | undefined {\n return ctx.response.length;\n}\n\n/**\n * Build structured log properties from context.\n */\nfunction buildProperties(\n ctx: KoaContext,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: ctx.method,\n url: ctx.url,\n path: ctx.path,\n status: ctx.status,\n responseTime,\n contentLength: getContentLength(ctx),\n remoteAddr: getRemoteAddr(ctx),\n userAgent: getUserAgent(ctx),\n referrer: getReferrer(ctx),\n };\n}\n\n/**\n * Build request context fields from a request.\n */\nfunction buildIncludedContext(\n ctx: KoaContext,\n resolvedRequestId: { property: string; value: string } | undefined,\n include: readonly RequestContextField[],\n): Record<string, unknown> {\n const context: Record<string, unknown> = {};\n for (const field of include) {\n switch (field) {\n case \"requestId\":\n if (resolvedRequestId != null) {\n context[resolvedRequestId.property] = resolvedRequestId.value;\n }\n break;\n case \"method\":\n context.method = ctx.method;\n break;\n case \"url\":\n context.url = ctx.url;\n break;\n case \"path\":\n context.path = ctx.path;\n break;\n case \"userAgent\":\n context.userAgent = getUserAgent(ctx);\n break;\n case \"remoteAddr\":\n context.remoteAddr = getRemoteAddr(ctx);\n break;\n case \"referrer\":\n context.referrer = getReferrer(ctx);\n break;\n }\n }\n return context;\n}\n\n/**\n * Build the implicit context for a request.\n */\nasync function buildRequestContext(\n ctx: KoaContext,\n options: RequestContextOptions,\n): Promise<Record<string, unknown>> {\n const requestIdOptions = normalizeRequestIdOptions(options.requestId);\n const resolvedRequestId = requestIdOptions == null\n ? undefined\n : resolveRequestId(ctx, requestIdOptions);\n const include = options.include ??\n (resolvedRequestId == null ? [] : [\"requestId\"] as const);\n const context = buildIncludedContext(ctx, resolvedRequestId, include);\n if (options.enrich == null) return context;\n return {\n ...context,\n ...await options.enrich(ctx),\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: KoaContext,\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: KoaContext,\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(\n ctx: KoaContext,\n responseTime: number,\n): string {\n const contentLength = getContentLength(ctx) ?? \"-\";\n return `${ctx.method} ${ctx.path} ${ctx.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(\n ctx: KoaContext,\n responseTime: number,\n): string {\n const remoteAddr = getRemoteAddr(ctx) ?? \"-\";\n const contentLength = getContentLength(ctx) ?? \"-\";\n return `${remoteAddr} ${ctx.method} ${ctx.url} ${ctx.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(\n ctx: KoaContext,\n responseTime: number,\n): string {\n const contentLength = getContentLength(ctx) ?? \"-\";\n return `${ctx.method} ${ctx.path} ${ctx.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 * Creates Koa middleware for HTTP request logging using LogTape.\n *\n * This middleware provides Morgan-compatible request logging with LogTape\n * as the backend, supporting structured logging and customizable formats.\n * It serves as an alternative to koa-logger with structured logging support.\n *\n * @example Basic usage\n * ```typescript\n * import Koa from \"koa\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { koaLogger } from \"@logtape/koa\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"koa\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = new Koa();\n * app.use(koaLogger());\n *\n * app.use((ctx) => {\n * ctx.body = { hello: \"world\" };\n * });\n *\n * app.listen(3000);\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(koaLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (ctx) => ctx.path === \"/health\",\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(koaLogger({\n * format: (ctx, responseTime) => ({\n * method: ctx.method,\n * path: ctx.path,\n * status: ctx.status,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the middleware.\n * @returns Koa middleware function.\n * @since 1.3.0\n */\nexport function koaLogger(\n options: KoaLogTapeOptions = {},\n): KoaMiddleware {\n const category = normalizeCategory(options.category ?? [\"koa\"]);\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 contextOptions = normalizeRequestContextOptions(options.context);\n\n // Resolve format function\n const formatFn: FormatFunction = typeof formatOption === \"string\"\n ? predefinedFormats[formatOption]\n : formatOption;\n\n const logMethod = logger[level].bind(logger);\n\n return async (ctx: KoaContext, next: () => Promise<void>): Promise<void> => {\n const startTime = Date.now();\n\n const handleRequest = async (\n requestContext: Record<string, unknown>,\n ): Promise<void> => {\n // For immediate logging, log when request arrives\n if (logRequest) {\n if (!skip(ctx)) {\n const result = withRequestLogContext(\n formatFn(ctx, 0),\n requestContext,\n );\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n await next();\n return;\n }\n\n // Log after response is sent\n await next();\n\n if (skip(ctx)) return;\n\n const responseTime = Date.now() - startTime;\n const result = withRequestLogContext(\n formatFn(ctx, 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 if (contextOptions == null) {\n await handleRequest({});\n return;\n }\n\n const requestContext = await buildRequestContext(ctx, contextOptions);\n await withContext(requestContext, () => handleRequest(requestContext));\n };\n}\n"],"mappings":";;;AAiPA,MAAM,yBAAyB;;;;AAK/B,SAAS,+BACPA,SACmC;AACnC,KAAI,YAAY,KAAM,QAAO,CAAE;AAC/B,KAAI,YAAY,SAAS,WAAW,KAAM;AAC1C,QAAO;AACR;;;;AAKD,SAAS,0BACPC,SAC8B;AAC9B,KAAI,YAAY,MAAO;AACvB,KAAI,YAAY,QAAQ,WAAW,KAAM,QAAO,CAAE;AAClD,QAAO;AACR;;;;AAKD,SAAS,oBAA4B;AACnC,YAAW,WAAW,QAAQ,eAAe,WAC3C,QAAO,WAAW,OAAO,YAAY;AAEvC,SAAQ,EAAE,KAAK,KAAK,CAAC,SAAS,GAAG,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,CAAC;AAC1E;;;;AAKD,SAAS,0BAA0BC,OAA8B;CAC/D,MAAM,UAAU,MAAM,MAAM;AAC5B,QAAO,YAAY,KAAK,OAAO;AAChC;;;;AAKD,SAAS,iBACPC,KACAC,SACqC;CACrC,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,cAAc,QAAQ,eAAe,CAAC,sBAAuB;AACnE,MAAK,MAAM,cAAc,aAAa;EACpC,MAAM,cAAc,IAAI,IAAI,WAAW;AACvC,MAAI,gBAAgB,GAAI;EACxB,MAAM,aAAa,UAAU,YAAY;AACzC,MAAI,cAAc,MAAM;GACtB,MAAMC,mBAAiB,QAAQ,kBAAkB;AACjD,OAAIA,qBAAmB,MA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,KAAK,GAAG;GAClC,MAAM,SAAS,sBACb,SAAS,KAAK,aAAa,EAC3BC,iBACD;AAED,cAAW,WAAW,SACpB,WAAU,QAAQA,iBAAe;OAEjC,WAAU,+CAA+C,OAAO;EAEnE;AAED,MAAI,kBAAkB,MAAM;AAC1B,SAAM,cAAc,CAAE,EAAC;AACvB;EACD;EAED,MAAM,iBAAiB,MAAM,oBAAoB,KAAK,eAAe;AACrE,QAAM,YAAY,gBAAgB,MAAM,cAAc,eAAe,CAAC;CACvE;AACF"}
1
+ {"version":3,"file":"mod.js","names":["options: boolean | RequestContextOptions | undefined","options: boolean | RequestIdOptions | undefined","value: string","ctx: KoaContext","options: RequestIdOptions","responseHeader","responseTime: number","resolvedRequestId: { property: string; value: string } | undefined","include: readonly RequestContextField[]","context: Record<string, unknown>","options: RequestContextOptions","result: string | Record<string, unknown>","value: number","timestamp: number","value: unknown","escapeSpaces: boolean","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","options: KoaLogTapeOptions","formatFn: FormatFunction","next: () => Promise<void>","requestContext: Record<string, unknown>","result","requestContext"],"sources":["../src/mod.ts"],"sourcesContent":["import { getLogger, type LogLevel, withContext } from \"@logtape/logtape\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n/**\n * Minimal Koa Context interface for compatibility across Koa 2.x and 3.x.\n *\n * This interface includes common aliases available on the Koa context object.\n * See https://koajs.com/#context for the full API.\n *\n * @since 1.3.0\n */\nexport interface KoaContext {\n /** HTTP request method (alias for ctx.request.method) */\n method: string;\n /** Request URL (alias for ctx.request.url) */\n url: string;\n /** Request pathname (alias for ctx.request.path) */\n path: string;\n /** HTTP response status code (alias for ctx.response.status) */\n status: number;\n /** Remote client IP address (alias for ctx.request.ip) */\n ip: string;\n /** Koa Response object */\n response: {\n length?: number;\n };\n /** Node.js request object, when available. */\n req?: {\n httpVersion?: string;\n };\n /**\n * Get a request header field value (case-insensitive).\n * @param field The header field name.\n * @returns The header value, or an empty string if not present.\n */\n get(field: string): string;\n /**\n * Set a response header field value.\n * @param field The header field name.\n * @param value The header field value.\n */\n set?(field: string, value: string): void;\n}\n\n/**\n * Koa middleware function type.\n * @since 1.3.0\n */\nexport type KoaMiddleware = (\n ctx: KoaContext,\n next: () => Promise<void>,\n) => Promise<void>;\n\n/**\n * Predefined log format names.\n * @since 1.3.0\n */\nexport type PredefinedFormat =\n /**\n * @deprecated Use `\"structured-combined\"` instead.\n */\n | \"combined\"\n /**\n * @deprecated Use `\"structured-common\"` instead.\n */\n | \"common\"\n | \"structured-combined\"\n | \"structured-common\"\n | \"morgan-combined\"\n | \"morgan-common\"\n | \"dev\"\n | \"short\"\n | \"tiny\";\n\n/**\n * Custom format function for request logging.\n *\n * @param ctx The Koa context object.\n * @param responseTime The response time in milliseconds.\n * @returns A string message or an object with structured properties.\n * @since 1.3.0\n */\nexport type FormatFunction = (\n ctx: KoaContext,\n responseTime: number,\n) => string | Record<string, unknown>;\n\n/**\n * Structured log properties for HTTP requests.\n * @since 1.3.0\n */\nexport interface RequestLogProperties {\n /** HTTP request method */\n method: string;\n /** Request URL */\n url: string;\n /** 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 */\n contentLength: number | undefined;\n /** Remote client address */\n remoteAddr: string | undefined;\n /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\n}\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: KoaContext,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n}\n\n/**\n * Options for configuring the Koa LogTape middleware.\n * @since 1.3.0\n */\nexport interface KoaLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"koa\"]\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 * Structured formats:\n * - `\"structured-combined\"` - Structured request properties (default)\n * - `\"structured-common\"` - Structured request properties without\n * referrer/userAgent\n * - `\"combined\"` - Deprecated alias for `\"structured-combined\"`\n * - `\"common\"` - Deprecated alias for `\"structured-common\"`\n *\n * Text formats:\n * - `\"morgan-combined\"` - Morgan-compatible combined access log (string)\n * - `\"morgan-common\"` - Morgan-compatible common access log (string)\n * - `\"dev\"` - Concise colored output for development (string)\n * - `\"short\"` - Shorter than common (string)\n * - `\"tiny\"` - Minimal output (string)\n *\n * @default \"structured-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(koaLogger({\n * skip: (ctx) => ctx.path === \"/health\",\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (ctx: KoaContext) => 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 * Enables request-scoped implicit context and request ID correlation.\n *\n * When set to `true`, the middleware reads the `x-request-id` header,\n * generates one when it is absent, writes it to the `x-request-id` response\n * header, and adds `requestId` to all LogTape records emitted while handling\n * the request.\n *\n * @default false\n * @since 2.2.0\n */\n readonly context?: boolean | RequestContextOptions;\n}\n\nconst defaultRequestIdHeader = \"x-request-id\";\n\n/**\n * Normalize request context options.\n */\nfunction normalizeRequestContextOptions(\n options: boolean | RequestContextOptions | undefined,\n): RequestContextOptions | undefined {\n if (options === true) return {};\n if (options === false || options == null) return undefined;\n return options;\n}\n\n/**\n * Normalize request ID options.\n */\nfunction normalizeRequestIdOptions(\n options: boolean | RequestIdOptions | undefined,\n): RequestIdOptions | undefined {\n if (options === false) return undefined;\n if (options === true || options == null) return {};\n return options;\n}\n\n/**\n * Generate a request ID with Web Crypto when possible.\n */\nfunction generateRequestId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Normalize an incoming request ID.\n */\nfunction defaultNormalizeRequestId(value: string): string | null {\n const trimmed = value.trim();\n return trimmed === \"\" ? null : trimmed;\n}\n\n/**\n * Resolve the request ID for a request.\n */\nfunction resolveRequestId(\n ctx: KoaContext,\n options: RequestIdOptions,\n): { property: string; value: string } {\n const property = options.property ?? \"requestId\";\n const normalize = options.normalize ?? defaultNormalizeRequestId;\n const headerNames = options.headerNames ?? [defaultRequestIdHeader];\n for (const headerName of headerNames) {\n const headerValue = ctx.get(headerName);\n if (headerValue === \"\") continue;\n const normalized = normalize(headerValue);\n if (normalized != null) {\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n if (responseHeader !== false) ctx.set?.(responseHeader, normalized);\n return { property, value: normalized };\n }\n }\n const generated = (options.generate ?? generateRequestId)();\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n if (responseHeader !== false) ctx.set?.(responseHeader, generated);\n return { property, value: generated };\n}\n\n/**\n * Get referrer from request headers.\n * Returns undefined if the header is not present or empty.\n */\nfunction getReferrer(ctx: KoaContext): string | undefined {\n const referrer = ctx.get(\"referrer\") || ctx.get(\"referer\");\n return referrer !== \"\" ? referrer : undefined;\n}\n\n/**\n * Get user agent from request headers.\n * Returns undefined if the header is not present or empty.\n */\nfunction getUserAgent(ctx: KoaContext): string | undefined {\n const userAgent = ctx.get(\"user-agent\");\n return userAgent !== \"\" ? userAgent : undefined;\n}\n\n/**\n * Get remote address from context.\n * Returns undefined if not available.\n */\nfunction getRemoteAddr(ctx: KoaContext): string | undefined {\n return ctx.ip !== \"\" ? ctx.ip : undefined;\n}\n\n/**\n * Get content length from response.\n */\nfunction getContentLength(ctx: KoaContext): number | undefined {\n return ctx.response.length;\n}\n\n/**\n * Build structured log properties from context.\n */\nfunction buildProperties(\n ctx: KoaContext,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: ctx.method,\n url: ctx.url,\n path: ctx.path,\n status: ctx.status,\n responseTime,\n contentLength: getContentLength(ctx),\n remoteAddr: getRemoteAddr(ctx),\n userAgent: getUserAgent(ctx),\n referrer: getReferrer(ctx),\n };\n}\n\n/**\n * Build request context fields from a request.\n */\nfunction buildIncludedContext(\n ctx: KoaContext,\n resolvedRequestId: { property: string; value: string } | undefined,\n include: readonly RequestContextField[],\n): Record<string, unknown> {\n const context: Record<string, unknown> = {};\n for (const field of include) {\n switch (field) {\n case \"requestId\":\n if (resolvedRequestId != null) {\n context[resolvedRequestId.property] = resolvedRequestId.value;\n }\n break;\n case \"method\":\n context.method = ctx.method;\n break;\n case \"url\":\n context.url = ctx.url;\n break;\n case \"path\":\n context.path = ctx.path;\n break;\n case \"userAgent\":\n context.userAgent = getUserAgent(ctx);\n break;\n case \"remoteAddr\":\n context.remoteAddr = getRemoteAddr(ctx);\n break;\n case \"referrer\":\n context.referrer = getReferrer(ctx);\n break;\n }\n }\n return context;\n}\n\n/**\n * Build the implicit context for a request.\n */\nasync function buildRequestContext(\n ctx: KoaContext,\n options: RequestContextOptions,\n): Promise<Record<string, unknown>> {\n const requestIdOptions = normalizeRequestIdOptions(options.requestId);\n const resolvedRequestId = requestIdOptions == null\n ? undefined\n : resolveRequestId(ctx, requestIdOptions);\n const include = options.include ??\n (resolvedRequestId == null ? [] : [\"requestId\"] as const);\n const context = buildIncludedContext(ctx, resolvedRequestId, include);\n if (options.enrich == null) return context;\n return {\n ...context,\n ...await options.enrich(ctx),\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\nconst clfMonths = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n] as const;\n\nfunction pad2(value: number): string {\n return value.toString().padStart(2, \"0\");\n}\n\nfunction formatClfDate(timestamp: number = Date.now()): string {\n const date = new Date(timestamp);\n return `${pad2(date.getUTCDate())}/${\n clfMonths[date.getUTCMonth()]\n }/${date.getUTCFullYear()}:${pad2(date.getUTCHours())}:${\n pad2(date.getUTCMinutes())\n }:${pad2(date.getUTCSeconds())} +0000`;\n}\n\nfunction escapeAccessLogValue(value: unknown, escapeSpaces: boolean): string {\n const escaped = String(value)\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\r/g, \"\\\\r\")\n .replace(/\\n/g, \"\\\\n\")\n .replace(/\\t/g, \"\\\\t\");\n return escapeSpaces ? escaped.replace(/ /g, \"\\\\x20\") : escaped;\n}\n\nfunction formatAccessLogToken(value: unknown): string {\n if (value == null || value === \"\") return \"-\";\n return escapeAccessLogValue(value, true);\n}\n\nfunction formatAccessLogQuotedToken(value: unknown): string {\n if (value == null || value === \"\") return '\"-\"';\n return `\"${escapeAccessLogValue(value, false)}\"`;\n}\n\nfunction getRemoteUser(ctx: KoaContext): string | undefined {\n const authorization = ctx.get(\"authorization\");\n if (authorization === \"\") return undefined;\n const match = /^Basic\\s+(.+)$/i.exec(authorization);\n if (match == null || typeof globalThis.atob !== \"function\") {\n return undefined;\n }\n try {\n const decoded = globalThis.atob(match[1]);\n const colonIndex = decoded.indexOf(\":\");\n const user = colonIndex < 0 ? decoded : decoded.slice(0, colonIndex);\n return user === \"\" ? undefined : user;\n } catch {\n return undefined;\n }\n}\n\nfunction getHttpVersion(ctx: KoaContext): string | undefined {\n return ctx.req?.httpVersion;\n}\n\n/**\n * Structured combined format.\n * Returns all structured properties.\n */\nfunction formatCombined(\n ctx: KoaContext,\n responseTime: number,\n): Record<string, unknown> {\n return { ...buildProperties(ctx, responseTime) };\n}\n\n/**\n * Structured common format.\n * Like structured combined but without referrer and userAgent.\n */\nfunction formatCommon(\n ctx: KoaContext,\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 * Morgan combined format.\n * :remote-addr - :remote-user [:date[clf]]\n * \":method :url HTTP/:http-version\" :status :res[content-length]\n * \":referrer\" \":user-agent\"\n */\nfunction formatMorganCombined(ctx: KoaContext): string {\n return `${formatAccessLogToken(getRemoteAddr(ctx))} - ${\n formatAccessLogToken(getRemoteUser(ctx))\n } [${formatClfDate()}] \"${formatAccessLogToken(ctx.method)} ${\n formatAccessLogToken(ctx.url)\n } HTTP/${formatAccessLogToken(getHttpVersion(ctx))}\" ${\n formatAccessLogToken(ctx.status)\n } ${formatAccessLogToken(getContentLength(ctx))} ${\n formatAccessLogQuotedToken(getReferrer(ctx))\n } ${formatAccessLogQuotedToken(getUserAgent(ctx))}`;\n}\n\n/**\n * Morgan common format.\n * :remote-addr - :remote-user [:date[clf]]\n * \":method :url HTTP/:http-version\" :status :res[content-length]\n */\nfunction formatMorganCommon(ctx: KoaContext): string {\n return `${formatAccessLogToken(getRemoteAddr(ctx))} - ${\n formatAccessLogToken(getRemoteUser(ctx))\n } [${formatClfDate()}] \"${formatAccessLogToken(ctx.method)} ${\n formatAccessLogToken(ctx.url)\n } HTTP/${formatAccessLogToken(getHttpVersion(ctx))}\" ${\n formatAccessLogToken(ctx.status)\n } ${formatAccessLogToken(getContentLength(ctx))}`;\n}\n\n/**\n * Dev format (colored output for development).\n * :method :path :status :response-time ms - :res[content-length]\n */\nfunction formatDev(\n ctx: KoaContext,\n responseTime: number,\n): string {\n const contentLength = getContentLength(ctx) ?? \"-\";\n return `${ctx.method} ${ctx.path} ${ctx.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(\n ctx: KoaContext,\n responseTime: number,\n): string {\n const remoteAddr = getRemoteAddr(ctx) ?? \"-\";\n const contentLength = getContentLength(ctx) ?? \"-\";\n return `${remoteAddr} ${ctx.method} ${ctx.url} ${ctx.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(\n ctx: KoaContext,\n responseTime: number,\n): string {\n const contentLength = getContentLength(ctx) ?? \"-\";\n return `${ctx.method} ${ctx.path} ${ctx.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 \"structured-combined\": formatCombined,\n \"structured-common\": formatCommon,\n \"morgan-combined\": formatMorganCombined,\n \"morgan-common\": formatMorganCommon,\n dev: formatDev,\n short: formatShort,\n tiny: formatTiny,\n};\n\n/**\n * Normalize category to array format.\n */\nfunction normalizeCategory(\n category: string | readonly string[],\n): readonly string[] {\n return typeof category === \"string\" ? [category] : category;\n}\n\n/**\n * Creates Koa middleware for HTTP request logging using LogTape.\n *\n * This middleware provides Morgan-compatible request logging with LogTape\n * as the backend, supporting structured logging and customizable formats.\n * It serves as an alternative to koa-logger with structured logging support.\n *\n * @example Basic usage\n * ```typescript\n * import Koa from \"koa\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { koaLogger } from \"@logtape/koa\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"koa\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = new Koa();\n * app.use(koaLogger());\n *\n * app.use((ctx) => {\n * ctx.body = { hello: \"world\" };\n * });\n *\n * app.listen(3000);\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(koaLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (ctx) => ctx.path === \"/health\",\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(koaLogger({\n * format: (ctx, responseTime) => ({\n * method: ctx.method,\n * path: ctx.path,\n * status: ctx.status,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the middleware.\n * @returns Koa middleware function.\n * @since 1.3.0\n */\nexport function koaLogger(\n options: KoaLogTapeOptions = {},\n): KoaMiddleware {\n const category = normalizeCategory(options.category ?? [\"koa\"]);\n const logger = getLogger(category);\n const level = options.level ?? \"info\";\n const formatOption = options.format ?? \"structured-combined\";\n const skip = options.skip ?? (() => false);\n const logRequest = options.logRequest ?? false;\n const contextOptions = normalizeRequestContextOptions(options.context);\n\n // Resolve format function\n const formatFn: FormatFunction = typeof formatOption === \"string\"\n ? predefinedFormats[formatOption]\n : formatOption;\n\n const logMethod = logger[level].bind(logger);\n\n return async (ctx: KoaContext, next: () => Promise<void>): Promise<void> => {\n const startTime = Date.now();\n\n const handleRequest = async (\n requestContext: Record<string, unknown>,\n ): Promise<void> => {\n // For immediate logging, log when request arrives\n if (logRequest) {\n if (!skip(ctx)) {\n const result = withRequestLogContext(\n formatFn(ctx, 0),\n requestContext,\n );\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n await next();\n return;\n }\n\n // Log after response is sent\n await next();\n\n if (skip(ctx)) return;\n\n const responseTime = Date.now() - startTime;\n const result = withRequestLogContext(\n formatFn(ctx, 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 if (contextOptions == null) {\n await handleRequest({});\n return;\n }\n\n const requestContext = await buildRequestContext(ctx, contextOptions);\n await withContext(requestContext, () => handleRequest(requestContext));\n };\n}\n"],"mappings":";;;AA2QA,MAAM,yBAAyB;;;;AAK/B,SAAS,+BACPA,SACmC;AACnC,KAAI,YAAY,KAAM,QAAO,CAAE;AAC/B,KAAI,YAAY,SAAS,WAAW,KAAM;AAC1C,QAAO;AACR;;;;AAKD,SAAS,0BACPC,SAC8B;AAC9B,KAAI,YAAY,MAAO;AACvB,KAAI,YAAY,QAAQ,WAAW,KAAM,QAAO,CAAE;AAClD,QAAO;AACR;;;;AAKD,SAAS,oBAA4B;AACnC,YAAW,WAAW,QAAQ,eAAe,WAC3C,QAAO,WAAW,OAAO,YAAY;AAEvC,SAAQ,EAAE,KAAK,KAAK,CAAC,SAAS,GAAG,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,CAAC;AAC1E;;;;AAKD,SAAS,0BAA0BC,OAA8B;CAC/D,MAAM,UAAU,MAAM,MAAM;AAC5B,Q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AACD,UAAM,MAAM;AACZ;GACD;AAGD,SAAM,MAAM;AAEZ,OAAI,KAAK,IAAI,CAAE;GAEf,MAAM,eAAe,KAAK,KAAK,GAAG;GAClC,MAAM,SAAS,sBACb,SAAS,KAAK,aAAa,EAC3BC,iBACD;AAED,cAAW,WAAW,SACpB,WAAU,QAAQA,iBAAe;OAEjC,WAAU,+CAA+C,OAAO;EAEnE;AAED,MAAI,kBAAkB,MAAM;AAC1B,SAAM,cAAc,CAAE,EAAC;AACvB;EACD;EAED,MAAM,iBAAiB,MAAM,oBAAoB,KAAK,eAAe;AACrE,QAAM,YAAY,gBAAgB,MAAM,cAAc,eAAe,CAAC;CACvE;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logtape/koa",
3
- "version": "2.2.0-dev.761+b49eecfd",
3
+ "version": "2.2.0-dev.767+7533e10c",
4
4
  "description": "Koa adapter for LogTape logging library",
5
5
  "keywords": [
6
6
  "logging",
@@ -52,7 +52,7 @@
52
52
  ],
53
53
  "peerDependencies": {
54
54
  "koa": "^2.0.0 || ^3.0.0",
55
- "@logtape/logtape": "^2.2.0-dev.761+b49eecfd"
55
+ "@logtape/logtape": "^2.2.0-dev.767+7533e10c"
56
56
  },
57
57
  "devDependencies": {
58
58
  "@alinea/suite": "^0.6.3",