@tanngo11/log 0.4.2 → 0.4.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.3
4
+
5
+ Fixed:
6
+ - `patchConsole` drops console calls that carry an error already written on a summary line, so a
7
+ failed request is not logged twice.
8
+ - The Strapi transport honours the winston logger's runtime level. Strapi's data export and
9
+ import commands set it to `error` to keep their output quiet.
10
+
11
+ Added:
12
+ - `patchConsole(log, { skip })`.
13
+ - `nextConsoleSkip` (`/next`): drops Next's console copy of a render error, which
14
+ `onRequestError` logs with route and digest.
15
+
3
16
  ## 0.4.2
4
17
 
5
18
  Fixed:
package/README.md CHANGED
@@ -217,12 +217,14 @@ Server components and anything not wrapped:
217
217
  ```ts
218
218
  // instrumentation.ts
219
219
  import { patchConsole } from "@tanngo11/log";
220
- import { nextOnRequestError, registerNext } from "@tanngo11/log/next";
220
+ import { nextConsoleSkip, nextOnRequestError, registerNext } from "@tanngo11/log/next";
221
221
  import { log } from "@/lib/log";
222
222
 
223
223
  export function register() {
224
224
  registerNext(log); // app.started + crash logging (Next keeps serving, so no exit)
225
- patchConsole(log); // Next's own error output and leftover console.* become JSON
225
+ // Next prints render errors with console.error before onRequestError logs them:
226
+ // nextConsoleSkip drops that copy so each error is one line.
227
+ patchConsole(log, { skip: nextConsoleSkip });
226
228
  }
227
229
  export const onRequestError = nextOnRequestError(log);
228
230
  ```
@@ -301,7 +303,8 @@ return [
301
303
  It is recorded as `upstream_request_id`, which links both services' logs. Set
302
304
  `trustIncomingRequestId: true` to adopt it instead.
303
305
  - Winston levels are mapped: `http` and `verbose` become `debug`, `silly` becomes `trace`.
304
- `LOG_LEVEL` filters.
306
+ `LOG_LEVEL` filters. A level set on the winston logger at runtime is honoured too: Strapi's
307
+ data export/import commands set it to `error`.
305
308
 
306
309
  Tested against the versions Strapi 5.51 uses: Koa 2, `@koa/router` 12 and winston 3.10.
307
310
 
package/dist/index.cjs CHANGED
@@ -228,6 +228,9 @@ var logged = globalSingleton("logged", () => /* @__PURE__ */ new WeakSet());
228
228
  function markLogged(err) {
229
229
  if (typeof err === "object" && err !== null) logged.add(err);
230
230
  }
231
+ function isLogged(err) {
232
+ return typeof err === "object" && err !== null && logged.has(err);
233
+ }
231
234
 
232
235
  // src/normalize.ts
233
236
  var HOOK_EXEMPT = /* @__PURE__ */ new Set(["level", "message", "event"]);
@@ -575,7 +578,7 @@ function jobData(data) {
575
578
 
576
579
  // src/console.ts
577
580
  var METHODS = { log: "info", info: "info", warn: "warn", error: "error", debug: "debug", trace: "debug" };
578
- function patchConsole(log) {
581
+ function patchConsole(log, opts = {}) {
579
582
  const target = console;
580
583
  const saved = {};
581
584
  let inside = false;
@@ -587,6 +590,7 @@ function patchConsole(log) {
587
590
  if (inside) return previous.apply(console, args);
588
591
  inside = true;
589
592
  try {
593
+ if (args.some((arg) => isErrorLike(arg) && isLogged(arg)) || opts.skip?.(args)) return;
590
594
  let err;
591
595
  const parts = [];
592
596
  for (const arg of args) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/context.ts","../src/global.ts","../src/levels.ts","../src/redact.ts","../src/error.ts","../src/normalize.ts","../src/pretty.ts","../src/logger.ts","../src/request-id.ts","../src/http.ts","../src/fetch.ts","../src/job.ts","../src/console.ts","../src/process.ts"],"sourcesContent":["export { createLogger, type Logger, type LoggerOptions } from \"./logger\";\nexport { LEVELS, type Level } from \"./levels\";\nexport type { Fields, RedactHook } from \"./normalize\";\nexport { REDACT_PATTERNS, type KeyPattern } from \"./redact\";\nexport { serializeError } from \"./error\";\nexport { addContext, getContext, recordError, withContext } from \"./context\";\nexport {\n DEFAULT_SKIP_PATHS,\n logHttpRequest,\n parseTraceparent,\n propagationHeaders,\n requestContextFields,\n resolveRequestId,\n type HttpLogOptions,\n type HttpRequestInfo,\n} from \"./http\";\nexport { createFetch, type FetchLogOptions } from \"./fetch\";\nexport { jobData, runJob, type JobInfo } from \"./job\";\nexport { patchConsole } from \"./console\";\nexport { installProcessHandlers, logShutdown, logStartup, type ProcessHandlerOptions } from \"./process\";\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { globalSingleton } from \"./global\";\nimport type { Fields } from \"./normalize\";\n\nexport interface ContextStore {\n fields: Fields;\n error?: unknown;\n /** Route template captured while the router still knew it (Express error path). */\n route?: string;\n parent?: ContextStore;\n}\n\nconst als = globalSingleton(\"als\", () => new AsyncLocalStorage<ContextStore>());\n\nexport const STORE_KEY: symbol = Symbol.for(\"@tanngo11/log.store\");\n\nexport function runWithStore<T>(fields: Fields, fn: (store: ContextStore) => T): T {\n const parent = als.getStore();\n const store: ContextStore = { fields: { ...parent?.fields, ...fields }, parent };\n return als.run(store, () => fn(store));\n}\n\nexport function withContext<T>(fields: Fields, fn: () => T): T {\n return runWithStore(fields, () => fn());\n}\n\nexport function currentStore(): ContextStore | undefined {\n return als.getStore();\n}\n\nexport function getContext(): Fields {\n return als.getStore()?.fields ?? {};\n}\n\n// Applies to the current context and every enclosing one, so a field added inside a nested\n// withContext/runJob still reaches the request's http.request line.\nexport function addContext(fields: Fields): void {\n for (let s = als.getStore(); s; s = s.parent) Object.assign(s.fields, fields);\n}\n\n// Sets the error on the store and on enclosing stores that have none yet.\nexport function recordErrorIn(store: ContextStore, err: unknown): void {\n store.error = err;\n for (let s = store.parent; s; s = s.parent) if (s.error === undefined) s.error = err;\n}\n\n// Marks the error that the current request/job summary line should carry. Does not write a line.\nexport function recordError(err: unknown): void {\n const store = als.getStore();\n if (store) recordErrorIn(store, err);\n}\n\nexport function attachStore(target: object, store: ContextStore): void {\n (target as Record<symbol, ContextStore>)[STORE_KEY] = store;\n}\n\nexport function storeOf(target: unknown): ContextStore | undefined {\n if (typeof target !== \"object\" || target === null) return undefined;\n return (target as Record<symbol, ContextStore | undefined>)[STORE_KEY];\n}\n","// Singletons shared by every copy of this package loaded in the process (ESM and CJS builds,\n// or duplicated installs), so context and dedupe state never split.\nexport function globalSingleton<T>(name: string, make: () => T): T {\n const key = Symbol.for(`@tanngo11/log.${name}`);\n const g = globalThis as unknown as Record<symbol, T | undefined>;\n let value = g[key];\n if (value === undefined) {\n value = make();\n g[key] = value;\n }\n return value;\n}\n","export const LEVELS = [\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\"] as const;\nexport type Level = (typeof LEVELS)[number];\n\nexport const LEVEL_RANK: Record<Level, number> = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n};\n\nconst ALIASES: Record<string, Level> = { warning: \"warn\", err: \"error\", critical: \"fatal\", panic: \"fatal\" };\n\nexport function parseLevel(value: unknown, fallback: Level = \"info\"): Level {\n if (typeof value !== \"string\") return fallback;\n const v = value.trim().toLowerCase();\n if ((LEVELS as readonly string[]).includes(v)) return v as Level;\n return ALIASES[v] ?? fallback;\n}\n","// Redaction shared by the logger and the error serializer. The collector redacts again,\n// but it cannot see secrets inside JSON-encoded strings, so the app side must catch them.\n\nexport const DEFAULT_REDACT_KEYS = [\n \"password\", \"passwd\", \"pwd\", \"passphrase\", \"secret\", \"client_secret\",\n \"token\", \"access_token\", \"refresh_token\", \"id_token\", \"auth_token\",\n \"api_key\", \"apikey\", \"access_key\", \"secret_key\", \"private_key\",\n \"authorization\", \"cookie\", \"set_cookie\", \"session_id\", \"sessionid\",\n \"credential\", \"credentials\", \"dsn\", \"connection_string\", \"conn_string\", \"jwt\", \"bearer\",\n];\n\n/** Opt-in value patterns for `redactValues`. Not on by default: they can hit ordinary numbers. */\nexport const REDACT_PATTERNS = {\n /** Vietnamese mobile numbers: 0912345678, +84912345678, 84912345678. */\n phoneVN: /(?<![\\d+])(?:\\+?84|0)[35789]\\d{8}(?!\\d)/g,\n /** Visa, Mastercard, Amex, Discover-like card numbers, with optional spaces or dashes. */\n paymentCard: /(?<!\\d)(?:4\\d{3}|5[1-5]\\d{2}|2[2-7]\\d{2}|3[47]\\d{2}|6(?:011|5\\d{2}))(?:[ -]?\\d{4}){2}[ -]?\\d{1,4}(?!\\d)/g,\n /** IPv4 addresses. */\n ipv4: /(?<![\\d.])(?:\\d{1,3}\\.){3}\\d{1,3}(?![\\d.])/g,\n} as const;\n\n// Keys that only describe a secret (count, type, timestamps, flags) stay readable.\nconst SAFE_SUFFIXES = [\"_count\", \"_type\", \"_length\", \"_expires_at\", \"_expires_in\", \"_ttl\", \"_at\", \"_ms\", \"_enabled\"];\n\nexport const REDACTED = \"[REDACTED]\";\n\nexport function toSnakeCase(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .toLowerCase();\n}\n\nconst URL_CREDENTIALS_RE = /([a-z][a-z0-9+.-]*:\\/\\/)[^\\s/@:\"']+:[^\\s/@\"']+@/gi;\nconst BEARER_RE = /\\bBearer\\s+[A-Za-z0-9._~+/=-]+/gi;\nconst JWT_RE = /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+/g;\nconst EMAIL_RE = /[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,})/g;\n\nexport type KeyPattern = string | RegExp;\n\nexport interface RedactorOptions {\n /** Extra sensitive keys: names (matched like the defaults) or patterns tested on the snake_case key. */\n keys?: readonly KeyPattern[];\n /** Extra value patterns; every match inside any string becomes [REDACTED]. */\n values?: readonly RegExp[];\n}\n\nexport interface Redactor {\n isSensitive(key: string): boolean;\n /** Masks secrets and emails that appear inside free text. */\n scrub(s: string): string;\n /** JSON.stringify that redacts sensitive keys at any depth and never throws. */\n json(value: unknown): string;\n}\n\nfunction globalize(re: RegExp): RegExp {\n return re.flags.includes(\"g\") ? new RegExp(re.source, re.flags) : new RegExp(re.source, `${re.flags}g`);\n}\n\nexport function createRedactor(opts: RedactorOptions = {}): Redactor {\n const words = [...DEFAULT_REDACT_KEYS];\n const keyPatterns: RegExp[] = [];\n for (const k of opts.keys ?? []) {\n if (typeof k === \"string\") words.push(toSnakeCase(k));\n else keyPatterns.push(new RegExp(k.source, k.flags.replace(\"g\", \"\")));\n }\n const valuePatterns = (opts.values ?? []).map(globalize);\n\n const isSensitive = (key: string): boolean => {\n const k = toSnakeCase(key);\n if (keyPatterns.some((re) => re.test(k))) return true;\n if (!words.includes(k) && SAFE_SUFFIXES.some((s) => k.endsWith(s))) return false;\n return words.some((w) => k === w || k.startsWith(`${w}_`) || k.endsWith(`_${w}`) || k.includes(`_${w}_`));\n };\n\n const scrub = (s: string): string => {\n let out = s\n .replace(URL_CREDENTIALS_RE, `$1${REDACTED}@`)\n .replace(BEARER_RE, `Bearer ${REDACTED}`)\n .replace(JWT_RE, \"[REDACTED_JWT]\")\n .replace(EMAIL_RE, \"***@$1\");\n for (const re of valuePatterns) out = out.replace(re, REDACTED);\n return out;\n };\n\n const json = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n const text = JSON.stringify(value, (key, val: unknown) => {\n if (key && val !== null && val !== undefined && isSensitive(key)) return REDACTED;\n if (typeof val === \"bigint\") return val.toString();\n if (val instanceof Error) return { name: val.name, message: val.message };\n return val;\n });\n return text ?? String(value);\n } catch {\n return String(value);\n }\n };\n\n return { isSensitive, scrub, json };\n}\n\nexport const defaultRedactor: Redactor = createRedactor();\n","import { globalSingleton } from \"./global\";\nimport { defaultRedactor } from \"./redact\";\n\nexport interface ErrFields {\n err_type?: string;\n err_message?: string;\n err_code?: string;\n err_stack?: string;\n err_cause?: string;\n}\n\nconst MAX_CAUSE_DEPTH = 5;\n\nexport function isErrorLike(v: unknown): v is Error {\n if (v instanceof Error) return true;\n return (\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as { message?: unknown }).message === \"string\" &&\n (\"stack\" in v || \"name\" in v)\n );\n}\n\nfunction errorType(e: Error): string {\n if (e.name && e.name !== \"Error\") return e.name;\n const ctor = (e as { constructor?: { name?: string } }).constructor?.name;\n return ctor && ctor !== \"Object\" ? ctor : \"Error\";\n}\n\nexport function serializeError(err: unknown): ErrFields {\n if (!isErrorLike(err)) {\n if (typeof err === \"string\") return { err_type: \"string\", err_message: err };\n return { err_type: typeof err, err_message: defaultRedactor.json(err) };\n }\n const e = err as Error & { code?: unknown; cause?: unknown };\n const out: ErrFields = { err_type: errorType(e), err_message: String(e.message ?? \"\") };\n if (e.code !== undefined && e.code !== null) out.err_code = String(e.code);\n if (typeof e.stack === \"string\") out.err_stack = e.stack;\n\n const causes: string[] = [];\n let cause = e.cause;\n while (cause !== undefined && cause !== null && causes.length < MAX_CAUSE_DEPTH) {\n if (isErrorLike(cause)) {\n causes.push(`${errorType(cause)}: ${cause.message}`);\n cause = (cause as { cause?: unknown }).cause;\n } else {\n causes.push(defaultRedactor.json(cause));\n cause = undefined;\n }\n }\n if (causes.length > 0) out.err_cause = causes.join(\" <- \");\n return out;\n}\n\nconst logged = globalSingleton(\"logged\", () => new WeakSet<object>());\n\n// Marks an error as already written, so a later boundary (e.g. Next's onRequestError)\n// does not log it a second time.\nexport function markLogged(err: unknown): void {\n if (typeof err === \"object\" && err !== null) logged.add(err);\n}\n\nexport function isLogged(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && logged.has(err);\n}\n","import { isErrorLike, serializeError } from \"./error\";\nimport type { Level } from \"./levels\";\nimport { REDACTED, toSnakeCase, type Redactor } from \"./redact\";\n\nexport { DEFAULT_REDACT_KEYS, toSnakeCase } from \"./redact\";\n\n/** Final per-field hook: return a replacement, or undefined to drop the field. */\nexport type RedactHook = (key: string, value: Primitive) => unknown;\n\nexport type Fields = Record<string, unknown>;\nexport type Primitive = string | number | boolean | null;\nexport type LogRecord = Record<string, Primitive>;\n\nexport interface NormalizeOptions {\n snakeCase: boolean;\n redactor: Redactor;\n hook?: RedactHook;\n}\n\n// Fields the redact hook never sees, so every line keeps its level, message and event.\nconst HOOK_EXEMPT = new Set([\"level\", \"message\", \"event\"]);\n\n// Keys owned by Vector (overwritten or deleted on ingest) or by the logger itself.\nexport const RESERVED_KEYS = new Set([\n \"project\", \"service\", \"vps\", \"version\", \"container_name\", \"container_id\", \"image\", \"stream\",\n \"_timestamp\", \"label\", \"host\", \"source_type\", \"msg\", \"lvl\", \"severity\", \"level\", \"message\",\n]);\n\nexport const MAX_LINE_BYTES = 16000;\nconst MAX_MESSAGE = 500;\nconst MAX_STACK = 4000;\nconst MAX_STRING = 1000;\nconst MAX_DEPTH = 3;\nconst TRUNCATED = \"…[truncated]\";\n\n// Fields kept when a line is too large.\nconst KEEP_ON_SHRINK = new Set([\n \"level\", \"message\", \"event\", \"request_id\", \"trace_id\", \"span_id\", \"job_name\", \"job_id\", \"job_attempt\",\n \"user_id\", \"tenant_id\", \"err_type\", \"err_message\", \"err_code\",\n]);\n\nexport function stripUrl(url: string): string {\n const noQuery = url.split(/[?#]/, 1)[0] ?? \"\";\n return noQuery.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/@\\s]*@/i, \"$1\");\n}\n\nexport function truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max - TRUNCATED.length) + TRUNCATED : s;\n}\n\nfunction isPlainObject(v: unknown): v is Fields {\n if (typeof v !== \"object\" || v === null) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction isUrlKey(key: string): boolean {\n return key === \"http_path\" || key === \"http_url\" || key.endsWith(\"_url\");\n}\n\nfunction flattenInto(out: LogRecord, prefix: string, obj: Fields, depth: number, opts: NormalizeOptions): void {\n for (const [rawKey, value] of Object.entries(obj)) {\n const key = opts.snakeCase ? toSnakeCase(rawKey) : rawKey;\n const full = prefix ? `${prefix}_${key}` : key;\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") continue;\n if (value !== null && (opts.redactor.isSensitive(rawKey) || opts.redactor.isSensitive(full))) {\n out[full] = REDACTED;\n continue;\n }\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n out[full] = value;\n } else if (typeof value === \"number\") {\n out[full] = Number.isFinite(value) ? value : String(value);\n } else if (typeof value === \"bigint\") {\n out[full] = value.toString();\n } else if (value instanceof Date) {\n out[full] = Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n } else if (isErrorLike(value)) {\n out[full] = `${value.name}: ${value.message}`;\n } else if (isPlainObject(value) && depth < MAX_DEPTH - 1) {\n flattenInto(out, full, value, depth + 1, opts);\n } else {\n // Arrays, deep objects, class instances: stringified with sensitive keys redacted.\n out[full] = opts.redactor.json(value);\n }\n }\n}\n\nfunction finalize(key: string, value: Primitive, opts: NormalizeOptions): Primitive {\n if (typeof value !== \"string\") return value;\n const v = opts.redactor.scrub(isUrlKey(key) ? stripUrl(value) : value);\n return truncate(v, key === \"err_stack\" ? MAX_STACK : MAX_STRING);\n}\n\nexport function buildRecord(\n level: Level,\n message: unknown,\n sources: (Fields | undefined)[],\n opts: NormalizeOptions,\n): LogRecord {\n const merged: Fields = {};\n for (const source of sources) if (source) Object.assign(merged, source);\n\n let err: unknown;\n if (merged.err !== undefined && merged.err !== null) {\n err = merged.err;\n delete merged.err;\n } else if (isErrorLike(merged.error)) {\n err = merged.error;\n delete merged.error;\n }\n\n const flat: LogRecord = {};\n flattenInto(flat, \"\", merged, 0, opts);\n if (err !== undefined) Object.assign(flat, serializeError(err));\n\n const text = typeof message === \"string\" ? message : opts.redactor.json(message);\n const out: LogRecord = { level, message: truncate(opts.redactor.scrub(text), MAX_MESSAGE) };\n for (const [k, v] of Object.entries(flat)) {\n const key = RESERVED_KEYS.has(k) ? `app_${k}` : k;\n let value = finalize(key, v, opts);\n if (opts.hook && !HOOK_EXEMPT.has(key)) {\n const replaced = opts.hook(key, value);\n if (replaced === undefined) continue;\n value = typeof replaced === \"object\" && replaced !== null ? opts.redactor.json(replaced) : (replaced as Primitive);\n }\n out[key] = value;\n }\n return out;\n}\n\nfunction byteLength(s: string): number {\n // UTF-8 uses at most 3 bytes per UTF-16 code unit: skip encoding short lines.\n if (s.length * 3 <= MAX_LINE_BYTES) return s.length;\n return new TextEncoder().encode(s).length;\n}\n\nexport function serializeRecord(record: LogRecord): string {\n const line = JSON.stringify(record);\n if (byteLength(line) <= MAX_LINE_BYTES) return line;\n const small: LogRecord = {};\n for (const [k, v] of Object.entries(record)) {\n if (KEEP_ON_SHRINK.has(k) || k.startsWith(\"http_\")) small[k] = v;\n }\n small.log_truncated = true;\n return JSON.stringify(small);\n}\n","import type { LogRecord } from \"./normalize\";\n\n// Human-readable line for local development only (LOG_FORMAT=pretty).\nexport function formatPretty(record: LogRecord): string {\n const { level, message, err_stack, ...rest } = record;\n const time = new Date().toISOString().slice(11, 23);\n const extras = Object.entries(rest)\n .map(([k, v]) => `${k}=${typeof v === \"string\" && /\\s/.test(v) ? JSON.stringify(v) : String(v)}`)\n .join(\" \");\n let line = `${time} ${String(level).toUpperCase().padEnd(5)} ${String(message)}${extras ? ` ${extras}` : \"\"}`;\n if (typeof err_stack === \"string\") line += `\\n${err_stack}`;\n return line;\n}\n","import { getContext } from \"./context\";\nimport { LEVEL_RANK, parseLevel, type Level } from \"./levels\";\nimport {\n buildRecord,\n serializeRecord,\n type Fields,\n type NormalizeOptions,\n type RedactHook,\n} from \"./normalize\";\nimport { formatPretty } from \"./pretty\";\nimport { createRedactor, type KeyPattern } from \"./redact\";\n\ntype LogMethod = (message: string, fields?: Fields) => void;\n\nexport interface Logger {\n readonly level: Level;\n trace: LogMethod;\n debug: LogMethod;\n info: LogMethod;\n warn: LogMethod;\n error: LogMethod;\n fatal: LogMethod;\n child(fields: Fields): Logger;\n isLevelEnabled(level: Level): boolean;\n}\n\nexport interface LoggerOptions {\n level?: Level | string;\n format?: \"json\" | \"pretty\";\n base?: Fields;\n /** Extra sensitive keys: names (matched like the defaults) or RegExp tested on the snake_case key. */\n redactKeys?: KeyPattern[];\n /** Extra value patterns masked in every string, e.g. REDACT_PATTERNS.phoneVN. */\n redactValues?: RegExp[];\n /** Final per-field hook: return a replacement, or undefined to drop the field. */\n redact?: RedactHook;\n snakeCase?: boolean;\n write?: (line: string) => void;\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== \"undefined\" ? process.env?.[name] : undefined;\n}\n\n// Captured before patchConsole can replace it, so the fallback never loops into the logger.\nconst consoleLog = console.log.bind(console);\n\nfunction defaultWrite(line: string): void {\n if (typeof process !== \"undefined\" && typeof process.stdout?.write === \"function\") {\n process.stdout.write(`${line}\\n`);\n } else {\n consoleLog(line);\n }\n}\n\nexport function createLogger(options: LoggerOptions = {}): Logger {\n const level = parseLevel(options.level ?? env(\"LOG_LEVEL\"));\n const format = options.format ?? (env(\"LOG_FORMAT\") === \"pretty\" ? \"pretty\" : \"json\");\n const write = options.write ?? defaultWrite;\n const norm: NormalizeOptions = {\n snakeCase: options.snakeCase ?? true,\n redactor: createRedactor({ keys: options.redactKeys, values: options.redactValues }),\n hook: options.redact,\n };\n\n const make = (bound: Fields): Logger => {\n const emit = (lvl: Level, message: string, fields?: Fields) => {\n if (LEVEL_RANK[lvl] < LEVEL_RANK[level]) return;\n let line: string;\n try {\n const record = buildRecord(lvl, message, [options.base, getContext(), bound, fields], norm);\n line = format === \"pretty\" ? formatPretty(record) : serializeRecord(record);\n } catch (e) {\n line = JSON.stringify({\n level: \"error\",\n message: \"log serialize failed\",\n event: \"log.serialize_failed\",\n err_message: String((e as Error)?.message ?? e).slice(0, 1000),\n original_message: String(message).slice(0, 500),\n });\n }\n try {\n write(line);\n } catch {\n // Logging must never break the app.\n }\n };\n return {\n level,\n trace: (m, f) => emit(\"trace\", m, f),\n debug: (m, f) => emit(\"debug\", m, f),\n info: (m, f) => emit(\"info\", m, f),\n warn: (m, f) => emit(\"warn\", m, f),\n error: (m, f) => emit(\"error\", m, f),\n fatal: (m, f) => emit(\"fatal\", m, f),\n child: (fields) => make({ ...bound, ...fields }),\n isLevelEnabled: (l) => LEVEL_RANK[l] >= LEVEL_RANK[level],\n };\n };\n return make({});\n}\n","// No imports: this module is shared with the edge entry (next-edge).\nexport const REQUEST_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\nexport function newRequestId(): string {\n return globalThis.crypto.randomUUID();\n}\n\nfunction first(header?: string | string[] | null): string | undefined {\n return Array.isArray(header) ? header[0] : (header ?? undefined);\n}\n\nexport function resolveRequestId(header?: string | string[] | null): string {\n const value = first(header);\n return value && REQUEST_ID_RE.test(value) ? value : newRequestId();\n}\n\nexport function parseTraceparent(header?: string | string[] | null): { trace_id: string; span_id: string } | undefined {\n const value = first(header)?.trim().toLowerCase();\n const m = value ? TRACEPARENT_RE.exec(value) : null;\n if (!m) return undefined;\n const [, version, traceId, spanId] = m as unknown as [string, string, string, string];\n if (version === \"ff\" || /^0+$/.test(traceId) || /^0+$/.test(spanId)) return undefined;\n return { trace_id: traceId, span_id: spanId };\n}\n","import { getContext } from \"./context\";\nimport { markLogged, serializeError } from \"./error\";\nimport type { Logger } from \"./logger\";\nimport { stripUrl, type Fields } from \"./normalize\";\nimport { parseTraceparent, resolveRequestId } from \"./request-id\";\n\nexport { newRequestId, parseTraceparent, REQUEST_ID_RE, resolveRequestId } from \"./request-id\";\n\nexport type HeaderSource = Headers | Record<string, string | string[] | undefined>;\n\nfunction header(headers: HeaderSource, name: string): string | string[] | undefined {\n if (typeof (headers as Headers).get === \"function\") return (headers as Headers).get(name) ?? undefined;\n return (headers as Record<string, string | string[] | undefined>)[name];\n}\n\nexport function requestContextFields(headers: HeaderSource): { request_id: string; trace_id?: string; span_id?: string } {\n const out: { request_id: string; trace_id?: string; span_id?: string } = {\n request_id: resolveRequestId(header(headers, \"x-request-id\")),\n };\n const tp = parseTraceparent(header(headers, \"traceparent\"));\n if (tp) Object.assign(out, tp);\n return out;\n}\n\n// Headers to forward to services we own, so their logs share request_id / trace_id.\nexport function propagationHeaders(): Record<string, string> {\n const ctx = getContext();\n const out: Record<string, string> = {};\n if (typeof ctx.request_id === \"string\") out[\"x-request-id\"] = ctx.request_id;\n if (typeof ctx.trace_id === \"string\" && typeof ctx.span_id === \"string\") {\n out.traceparent = `00-${ctx.trace_id}-${ctx.span_id}-01`;\n }\n return out;\n}\n\nexport const DEFAULT_SKIP_PATHS: (string | RegExp)[] = [\n /^\\/(health|healthz|ready|readyz|livez)\\/?$/,\n \"/favicon.ico\",\n /^\\/_next\\/static\\//,\n];\n\nexport interface HttpLogOptions {\n skipPaths?: (string | RegExp)[];\n}\n\nexport interface HttpRequestInfo {\n method: string;\n route?: string;\n path: string;\n status: number;\n duration_ms?: number;\n err?: unknown;\n fields?: Fields;\n}\n\nexport function shouldSkip(method: string, path: string, skipPaths: (string | RegExp)[] = DEFAULT_SKIP_PATHS): boolean {\n if (method.toUpperCase() === \"OPTIONS\") return true;\n const p = stripUrl(path);\n return skipPaths.some((s) => (typeof s === \"string\" ? p === s : s.test(p)));\n}\n\n// Writes the one `http.request` summary line for an inbound request.\nexport function logHttpRequest(log: Logger, info: HttpRequestInfo, opts: HttpLogOptions = {}): void {\n if (shouldSkip(info.method, info.path, opts.skipPaths)) return;\n const level = info.status >= 500 ? \"error\" : info.status >= 400 ? \"warn\" : \"info\";\n const path = stripUrl(info.path);\n const errFields: Fields = {};\n if (info.err !== undefined && info.err !== null) {\n Object.assign(errFields, serializeError(info.err));\n if (info.status < 500) delete errFields.err_stack;\n markLogged(info.err);\n }\n // Route templates keep the message bounded; the raw path would make one message per URL.\n const message = info.route ? `${info.method} ${info.route} ${info.status}` : `${info.method} ${info.status}`;\n log[level](message, {\n ...info.fields,\n event: \"http.request\",\n http_method: info.method,\n http_route: info.route,\n http_path: path,\n http_status: info.status,\n duration_ms: info.duration_ms === undefined ? undefined : Math.round(info.duration_ms),\n ...errFields,\n });\n}\n","import { propagationHeaders } from \"./http\";\nimport type { Logger } from \"./logger\";\n\nexport interface FetchLogOptions {\n peer_service: string;\n /** Forward x-request-id / traceparent. Only for services we own. */\n internal?: boolean;\n slowMs?: number;\n fetch?: typeof fetch;\n}\n\nfunction describeRequest(input: RequestInfo | URL, init?: RequestInit): { method: string; url: string } {\n const method = (init?.method ?? (input instanceof Request ? input.method : \"GET\")).toUpperCase();\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n return { method, url };\n}\n\nexport function createFetch(log: Logger, opts: FetchLogOptions): typeof fetch {\n const slowMs = opts.slowMs ?? 1000;\n const wrapped = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const base = opts.fetch ?? globalThis.fetch;\n const { method, url } = describeRequest(input, init);\n let requestInit = init;\n if (opts.internal) {\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n for (const [k, v] of Object.entries(propagationHeaders())) if (!headers.has(k)) headers.set(k, v);\n requestInit = { ...init, headers };\n }\n const fields = { event: \"http.outbound\", peer_service: opts.peer_service, http_method: method, http_url: url };\n const start = performance.now();\n try {\n const res = await base(input, requestInit);\n const duration_ms = Math.round(performance.now() - start);\n if (res.status >= 500) {\n log.warn(\"outbound request failed\", { ...fields, http_status: res.status, duration_ms });\n } else if (duration_ms >= slowMs) {\n log.warn(\"outbound request slow\", { ...fields, http_status: res.status, duration_ms });\n }\n return res;\n } catch (err) {\n log.warn(\"outbound request failed\", { ...fields, duration_ms: Math.round(performance.now() - start), err });\n throw err;\n }\n };\n return wrapped as typeof fetch;\n}\n","import { getContext, withContext } from \"./context\";\nimport { markLogged } from \"./error\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\nexport interface JobInfo {\n job_name: string;\n job_id?: string | number;\n job_attempt?: number;\n /** No retries left after this attempt (or decided per error). Defaults to true when unknown. */\n final_attempt?: boolean | ((err: unknown) => boolean);\n request_id?: string;\n fields?: Fields;\n}\n\nexport async function runJob<T>(log: Logger, info: JobInfo, fn: () => T | Promise<T>): Promise<T> {\n const ctx: Fields = { ...info.fields, job_name: info.job_name };\n if (info.job_id !== undefined) ctx.job_id = String(info.job_id);\n if (info.job_attempt !== undefined) ctx.job_attempt = info.job_attempt;\n if (info.request_id !== undefined) ctx.request_id = info.request_id;\n\n return withContext(ctx, async () => {\n const start = performance.now();\n try {\n const result = await fn();\n log.info(\"job completed\", { event: \"job.completed\", duration_ms: Math.round(performance.now() - start) });\n return result;\n } catch (err) {\n const final = typeof info.final_attempt === \"function\" ? info.final_attempt(err) : (info.final_attempt ?? true);\n log[final ? \"error\" : \"warn\"](\"job failed\", {\n event: \"job.failed\",\n duration_ms: Math.round(performance.now() - start),\n err,\n });\n markLogged(err);\n throw err;\n }\n });\n}\n\n/** Adds the current request_id to a job payload, so the job's logs link back to the request. */\nexport function jobData<T extends Record<string, unknown>>(data: T): T & { request_id?: string } {\n const requestId = getContext().request_id;\n if (typeof requestId !== \"string\" || data.request_id !== undefined) return data;\n return { ...data, request_id: requestId };\n}\n","import { isErrorLike } from \"./error\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport { defaultRedactor } from \"./redact\";\n\nconst METHODS = { log: \"info\", info: \"info\", warn: \"warn\", error: \"error\", debug: \"debug\", trace: \"debug\" } as const;\ntype Method = keyof typeof METHODS;\ntype ConsoleFn = (...args: unknown[]) => void;\n\n/**\n * Routes console.log/info/warn/error/debug/trace through the logger, so legacy console calls\n * and framework output (e.g. Next.js errors) become JSON lines with request context.\n * Returns a function that restores the previous console methods.\n */\nexport function patchConsole(log: Logger): () => void {\n const target = console as unknown as Record<Method, ConsoleFn>;\n const saved = {} as Record<Method, ConsoleFn>;\n let inside = false;\n\n for (const method of Object.keys(METHODS) as Method[]) {\n const previous = target[method];\n saved[method] = previous;\n const level: Level = METHODS[method];\n target[method] = (...args: unknown[]) => {\n // A write path that itself uses console must not loop back into the logger.\n if (inside) return previous.apply(console, args);\n inside = true;\n try {\n let err: unknown;\n const parts: string[] = [];\n for (const arg of args) {\n if (isErrorLike(arg)) {\n err ??= arg;\n parts.push(arg.message);\n } else {\n parts.push(typeof arg === \"string\" ? arg : defaultRedactor.json(arg));\n }\n }\n log[level](parts.join(\" \"), { event: \"console\", console_method: method, err });\n } finally {\n inside = false;\n }\n };\n }\n\n return () => {\n for (const method of Object.keys(saved) as Method[]) target[method] = saved[method];\n };\n}\n","import { globalSingleton } from \"./global\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\nexport function logStartup(log: Logger, fields: Fields = {}): void {\n log.info(\"app started\", {\n event: \"app.started\",\n runtime_version: `node ${process.versions.node}`,\n log_level: log.level,\n ...fields,\n });\n}\n\n/** Call at the start of your own shutdown handler (e.g. on SIGTERM). The library never handles signals. */\nexport function logShutdown(log: Logger, fields: Fields = {}): void {\n log.info(\"app stopping\", { event: \"app.stopping\", ...fields });\n}\n\nexport interface ProcessHandlerOptions {\n /** Exit with code 1 after an uncaught error. Next.js keeps serving, so its adapter passes false. */\n exitOnCrash?: boolean;\n /** Time other crash handlers (Sentry, APM) get to flush before exit. Default 1000 ms. */\n exitDelayMs?: number;\n exit?: (code: number) => void;\n}\n\nexport function crashHandlers(log: Logger, opts: ProcessHandlerOptions = {}) {\n const exitOnCrash = opts.exitOnCrash ?? true;\n const exitDelayMs = opts.exitDelayMs ?? 1000;\n const exit = opts.exit ?? ((code: number) => process.exit(code));\n let exiting = false;\n const crash = (source: string, err: unknown) => {\n if (!exitOnCrash) {\n log.error(\"unhandled error\", { event: \"app.unhandled_error\", crash_source: source, err });\n return;\n }\n log.fatal(\"app crashed\", { event: \"app.crashed\", crash_source: source, err });\n if (exiting) return;\n exiting = true;\n if (typeof process !== \"undefined\") process.exitCode = 1;\n // Deferred so listeners registered after ours still run; unref so a process with nothing\n // left to do exits on its own (with exitCode 1) without waiting.\n const timer = setTimeout(() => exit(1), exitDelayMs);\n (timer as { unref?: () => void }).unref?.();\n };\n return {\n onUncaught: (err: unknown) => crash(\"uncaughtException\", err),\n onRejection: (reason: unknown) => crash(\"unhandledRejection\", reason),\n };\n}\n\nconst state = globalSingleton(\"process\", () => ({ installed: false }));\n\n/** Logs uncaught exceptions and unhandled rejections. Does not touch SIGTERM/SIGINT. */\nexport function installProcessHandlers(log: Logger, opts: ProcessHandlerOptions = {}): void {\n if (state.installed || typeof process === \"undefined\" || typeof process.on !== \"function\") return;\n state.installed = true;\n const h = crashHandlers(log, opts);\n process.on(\"uncaughtException\", h.onUncaught);\n process.on(\"unhandledRejection\", h.onRejection);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,8BAAkC;;;ACE3B,SAAS,gBAAmB,MAAc,MAAkB;AACjE,QAAM,MAAM,uBAAO,IAAI,iBAAiB,IAAI,EAAE;AAC9C,QAAM,IAAI;AACV,MAAI,QAAQ,EAAE,GAAG;AACjB,MAAI,UAAU,QAAW;AACvB,YAAQ,KAAK;AACb,MAAE,GAAG,IAAI;AAAA,EACX;AACA,SAAO;AACT;;;ADCA,IAAM,MAAM,gBAAgB,OAAO,MAAM,IAAI,0CAAgC,CAAC;AAIvE,SAAS,aAAgB,QAAgB,IAAmC;AACjF,QAAM,SAAS,IAAI,SAAS;AAC5B,QAAM,QAAsB,EAAE,QAAQ,EAAE,GAAG,QAAQ,QAAQ,GAAG,OAAO,GAAG,OAAO;AAC/E,SAAO,IAAI,IAAI,OAAO,MAAM,GAAG,KAAK,CAAC;AACvC;AAEO,SAAS,YAAe,QAAgB,IAAgB;AAC7D,SAAO,aAAa,QAAQ,MAAM,GAAG,CAAC;AACxC;AAMO,SAAS,aAAqB;AACnC,SAAO,IAAI,SAAS,GAAG,UAAU,CAAC;AACpC;AAIO,SAAS,WAAW,QAAsB;AAC/C,WAAS,IAAI,IAAI,SAAS,GAAG,GAAG,IAAI,EAAE,OAAQ,QAAO,OAAO,EAAE,QAAQ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AQ,IAAI,CAAC;AACxF;AAAA,IACF;AACA,QAAI,MAAM,eAAe,EAAE,OAAO,eAAe,cAAc,QAAQ,IAAI,CAAC;AAC5E,QAAI,QAAS;AACb,cAAU;AACV,QAAI,OAAO,YAAY,YAAa,SAAQ,WAAW;AAGvD,UAAM,QAAQ,WAAW,MAAM,KAAK,CAAC,GAAG,WAAW;AACnD,IAAC,MAAiC,QAAQ;AAAA,EAC5C;AACA,SAAO;AAAA,IACL,YAAY,CAAC,QAAiB,MAAM,qBAAqB,GAAG;AAAA,IAC5D,aAAa,CAAC,WAAoB,MAAM,sBAAsB,MAAM;AAAA,EACtE;AACF;AAEA,IAAM,QAAQ,gBAAgB,WAAW,OAAO,EAAE,WAAW,MAAM,EAAE;AAG9D,SAAS,uBAAuB,KAAa,OAA8B,CAAC,GAAS;AAC1F,MAAI,MAAM,aAAa,OAAO,YAAY,eAAe,OAAO,QAAQ,OAAO,WAAY;AAC3F,QAAM,YAAY;AAClB,QAAM,IAAI,cAAc,KAAK,IAAI;AACjC,UAAQ,GAAG,qBAAqB,EAAE,UAAU;AAC5C,UAAQ,GAAG,sBAAsB,EAAE,WAAW;AAChD;","names":["header"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/context.ts","../src/global.ts","../src/levels.ts","../src/redact.ts","../src/error.ts","../src/normalize.ts","../src/pretty.ts","../src/logger.ts","../src/request-id.ts","../src/http.ts","../src/fetch.ts","../src/job.ts","../src/console.ts","../src/process.ts"],"sourcesContent":["export { createLogger, type Logger, type LoggerOptions } from \"./logger\";\nexport { LEVELS, type Level } from \"./levels\";\nexport type { Fields, RedactHook } from \"./normalize\";\nexport { REDACT_PATTERNS, type KeyPattern } from \"./redact\";\nexport { serializeError } from \"./error\";\nexport { addContext, getContext, recordError, withContext } from \"./context\";\nexport {\n DEFAULT_SKIP_PATHS,\n logHttpRequest,\n parseTraceparent,\n propagationHeaders,\n requestContextFields,\n resolveRequestId,\n type HttpLogOptions,\n type HttpRequestInfo,\n} from \"./http\";\nexport { createFetch, type FetchLogOptions } from \"./fetch\";\nexport { jobData, runJob, type JobInfo } from \"./job\";\nexport { patchConsole, type PatchConsoleOptions } from \"./console\";\nexport { installProcessHandlers, logShutdown, logStartup, type ProcessHandlerOptions } from \"./process\";\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { globalSingleton } from \"./global\";\nimport type { Fields } from \"./normalize\";\n\nexport interface ContextStore {\n fields: Fields;\n error?: unknown;\n /** Route template captured while the router still knew it (Express error path). */\n route?: string;\n parent?: ContextStore;\n}\n\nconst als = globalSingleton(\"als\", () => new AsyncLocalStorage<ContextStore>());\n\nexport const STORE_KEY: symbol = Symbol.for(\"@tanngo11/log.store\");\n\nexport function runWithStore<T>(fields: Fields, fn: (store: ContextStore) => T): T {\n const parent = als.getStore();\n const store: ContextStore = { fields: { ...parent?.fields, ...fields }, parent };\n return als.run(store, () => fn(store));\n}\n\nexport function withContext<T>(fields: Fields, fn: () => T): T {\n return runWithStore(fields, () => fn());\n}\n\nexport function currentStore(): ContextStore | undefined {\n return als.getStore();\n}\n\nexport function getContext(): Fields {\n return als.getStore()?.fields ?? {};\n}\n\n// Applies to the current context and every enclosing one, so a field added inside a nested\n// withContext/runJob still reaches the request's http.request line.\nexport function addContext(fields: Fields): void {\n for (let s = als.getStore(); s; s = s.parent) Object.assign(s.fields, fields);\n}\n\n// Sets the error on the store and on enclosing stores that have none yet.\nexport function recordErrorIn(store: ContextStore, err: unknown): void {\n store.error = err;\n for (let s = store.parent; s; s = s.parent) if (s.error === undefined) s.error = err;\n}\n\n// Marks the error that the current request/job summary line should carry. Does not write a line.\nexport function recordError(err: unknown): void {\n const store = als.getStore();\n if (store) recordErrorIn(store, err);\n}\n\nexport function attachStore(target: object, store: ContextStore): void {\n (target as Record<symbol, ContextStore>)[STORE_KEY] = store;\n}\n\nexport function storeOf(target: unknown): ContextStore | undefined {\n if (typeof target !== \"object\" || target === null) return undefined;\n return (target as Record<symbol, ContextStore | undefined>)[STORE_KEY];\n}\n","// Singletons shared by every copy of this package loaded in the process (ESM and CJS builds,\n// or duplicated installs), so context and dedupe state never split.\nexport function globalSingleton<T>(name: string, make: () => T): T {\n const key = Symbol.for(`@tanngo11/log.${name}`);\n const g = globalThis as unknown as Record<symbol, T | undefined>;\n let value = g[key];\n if (value === undefined) {\n value = make();\n g[key] = value;\n }\n return value;\n}\n","export const LEVELS = [\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\"] as const;\nexport type Level = (typeof LEVELS)[number];\n\nexport const LEVEL_RANK: Record<Level, number> = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n};\n\nconst ALIASES: Record<string, Level> = { warning: \"warn\", err: \"error\", critical: \"fatal\", panic: \"fatal\" };\n\nexport function parseLevel(value: unknown, fallback: Level = \"info\"): Level {\n if (typeof value !== \"string\") return fallback;\n const v = value.trim().toLowerCase();\n if ((LEVELS as readonly string[]).includes(v)) return v as Level;\n return ALIASES[v] ?? fallback;\n}\n","// Redaction shared by the logger and the error serializer. The collector redacts again,\n// but it cannot see secrets inside JSON-encoded strings, so the app side must catch them.\n\nexport const DEFAULT_REDACT_KEYS = [\n \"password\", \"passwd\", \"pwd\", \"passphrase\", \"secret\", \"client_secret\",\n \"token\", \"access_token\", \"refresh_token\", \"id_token\", \"auth_token\",\n \"api_key\", \"apikey\", \"access_key\", \"secret_key\", \"private_key\",\n \"authorization\", \"cookie\", \"set_cookie\", \"session_id\", \"sessionid\",\n \"credential\", \"credentials\", \"dsn\", \"connection_string\", \"conn_string\", \"jwt\", \"bearer\",\n];\n\n/** Opt-in value patterns for `redactValues`. Not on by default: they can hit ordinary numbers. */\nexport const REDACT_PATTERNS = {\n /** Vietnamese mobile numbers: 0912345678, +84912345678, 84912345678. */\n phoneVN: /(?<![\\d+])(?:\\+?84|0)[35789]\\d{8}(?!\\d)/g,\n /** Visa, Mastercard, Amex, Discover-like card numbers, with optional spaces or dashes. */\n paymentCard: /(?<!\\d)(?:4\\d{3}|5[1-5]\\d{2}|2[2-7]\\d{2}|3[47]\\d{2}|6(?:011|5\\d{2}))(?:[ -]?\\d{4}){2}[ -]?\\d{1,4}(?!\\d)/g,\n /** IPv4 addresses. */\n ipv4: /(?<![\\d.])(?:\\d{1,3}\\.){3}\\d{1,3}(?![\\d.])/g,\n} as const;\n\n// Keys that only describe a secret (count, type, timestamps, flags) stay readable.\nconst SAFE_SUFFIXES = [\"_count\", \"_type\", \"_length\", \"_expires_at\", \"_expires_in\", \"_ttl\", \"_at\", \"_ms\", \"_enabled\"];\n\nexport const REDACTED = \"[REDACTED]\";\n\nexport function toSnakeCase(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .toLowerCase();\n}\n\nconst URL_CREDENTIALS_RE = /([a-z][a-z0-9+.-]*:\\/\\/)[^\\s/@:\"']+:[^\\s/@\"']+@/gi;\nconst BEARER_RE = /\\bBearer\\s+[A-Za-z0-9._~+/=-]+/gi;\nconst JWT_RE = /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+/g;\nconst EMAIL_RE = /[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,})/g;\n\nexport type KeyPattern = string | RegExp;\n\nexport interface RedactorOptions {\n /** Extra sensitive keys: names (matched like the defaults) or patterns tested on the snake_case key. */\n keys?: readonly KeyPattern[];\n /** Extra value patterns; every match inside any string becomes [REDACTED]. */\n values?: readonly RegExp[];\n}\n\nexport interface Redactor {\n isSensitive(key: string): boolean;\n /** Masks secrets and emails that appear inside free text. */\n scrub(s: string): string;\n /** JSON.stringify that redacts sensitive keys at any depth and never throws. */\n json(value: unknown): string;\n}\n\nfunction globalize(re: RegExp): RegExp {\n return re.flags.includes(\"g\") ? new RegExp(re.source, re.flags) : new RegExp(re.source, `${re.flags}g`);\n}\n\nexport function createRedactor(opts: RedactorOptions = {}): Redactor {\n const words = [...DEFAULT_REDACT_KEYS];\n const keyPatterns: RegExp[] = [];\n for (const k of opts.keys ?? []) {\n if (typeof k === \"string\") words.push(toSnakeCase(k));\n else keyPatterns.push(new RegExp(k.source, k.flags.replace(\"g\", \"\")));\n }\n const valuePatterns = (opts.values ?? []).map(globalize);\n\n const isSensitive = (key: string): boolean => {\n const k = toSnakeCase(key);\n if (keyPatterns.some((re) => re.test(k))) return true;\n if (!words.includes(k) && SAFE_SUFFIXES.some((s) => k.endsWith(s))) return false;\n return words.some((w) => k === w || k.startsWith(`${w}_`) || k.endsWith(`_${w}`) || k.includes(`_${w}_`));\n };\n\n const scrub = (s: string): string => {\n let out = s\n .replace(URL_CREDENTIALS_RE, `$1${REDACTED}@`)\n .replace(BEARER_RE, `Bearer ${REDACTED}`)\n .replace(JWT_RE, \"[REDACTED_JWT]\")\n .replace(EMAIL_RE, \"***@$1\");\n for (const re of valuePatterns) out = out.replace(re, REDACTED);\n return out;\n };\n\n const json = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n const text = JSON.stringify(value, (key, val: unknown) => {\n if (key && val !== null && val !== undefined && isSensitive(key)) return REDACTED;\n if (typeof val === \"bigint\") return val.toString();\n if (val instanceof Error) return { name: val.name, message: val.message };\n return val;\n });\n return text ?? String(value);\n } catch {\n return String(value);\n }\n };\n\n return { isSensitive, scrub, json };\n}\n\nexport const defaultRedactor: Redactor = createRedactor();\n","import { globalSingleton } from \"./global\";\nimport { defaultRedactor } from \"./redact\";\n\nexport interface ErrFields {\n err_type?: string;\n err_message?: string;\n err_code?: string;\n err_stack?: string;\n err_cause?: string;\n}\n\nconst MAX_CAUSE_DEPTH = 5;\n\nexport function isErrorLike(v: unknown): v is Error {\n if (v instanceof Error) return true;\n return (\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as { message?: unknown }).message === \"string\" &&\n (\"stack\" in v || \"name\" in v)\n );\n}\n\nfunction errorType(e: Error): string {\n if (e.name && e.name !== \"Error\") return e.name;\n const ctor = (e as { constructor?: { name?: string } }).constructor?.name;\n return ctor && ctor !== \"Object\" ? ctor : \"Error\";\n}\n\nexport function serializeError(err: unknown): ErrFields {\n if (!isErrorLike(err)) {\n if (typeof err === \"string\") return { err_type: \"string\", err_message: err };\n return { err_type: typeof err, err_message: defaultRedactor.json(err) };\n }\n const e = err as Error & { code?: unknown; cause?: unknown };\n const out: ErrFields = { err_type: errorType(e), err_message: String(e.message ?? \"\") };\n if (e.code !== undefined && e.code !== null) out.err_code = String(e.code);\n if (typeof e.stack === \"string\") out.err_stack = e.stack;\n\n const causes: string[] = [];\n let cause = e.cause;\n while (cause !== undefined && cause !== null && causes.length < MAX_CAUSE_DEPTH) {\n if (isErrorLike(cause)) {\n causes.push(`${errorType(cause)}: ${cause.message}`);\n cause = (cause as { cause?: unknown }).cause;\n } else {\n causes.push(defaultRedactor.json(cause));\n cause = undefined;\n }\n }\n if (causes.length > 0) out.err_cause = causes.join(\" <- \");\n return out;\n}\n\nconst logged = globalSingleton(\"logged\", () => new WeakSet<object>());\n\n// Marks an error as already written, so a later boundary (e.g. Next's onRequestError)\n// does not log it a second time.\nexport function markLogged(err: unknown): void {\n if (typeof err === \"object\" && err !== null) logged.add(err);\n}\n\nexport function isLogged(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && logged.has(err);\n}\n","import { isErrorLike, serializeError } from \"./error\";\nimport type { Level } from \"./levels\";\nimport { REDACTED, toSnakeCase, type Redactor } from \"./redact\";\n\nexport { DEFAULT_REDACT_KEYS, toSnakeCase } from \"./redact\";\n\n/** Final per-field hook: return a replacement, or undefined to drop the field. */\nexport type RedactHook = (key: string, value: Primitive) => unknown;\n\nexport type Fields = Record<string, unknown>;\nexport type Primitive = string | number | boolean | null;\nexport type LogRecord = Record<string, Primitive>;\n\nexport interface NormalizeOptions {\n snakeCase: boolean;\n redactor: Redactor;\n hook?: RedactHook;\n}\n\n// Fields the redact hook never sees, so every line keeps its level, message and event.\nconst HOOK_EXEMPT = new Set([\"level\", \"message\", \"event\"]);\n\n// Keys owned by Vector (overwritten or deleted on ingest) or by the logger itself.\nexport const RESERVED_KEYS = new Set([\n \"project\", \"service\", \"vps\", \"version\", \"container_name\", \"container_id\", \"image\", \"stream\",\n \"_timestamp\", \"label\", \"host\", \"source_type\", \"msg\", \"lvl\", \"severity\", \"level\", \"message\",\n]);\n\nexport const MAX_LINE_BYTES = 16000;\nconst MAX_MESSAGE = 500;\nconst MAX_STACK = 4000;\nconst MAX_STRING = 1000;\nconst MAX_DEPTH = 3;\nconst TRUNCATED = \"…[truncated]\";\n\n// Fields kept when a line is too large.\nconst KEEP_ON_SHRINK = new Set([\n \"level\", \"message\", \"event\", \"request_id\", \"trace_id\", \"span_id\", \"job_name\", \"job_id\", \"job_attempt\",\n \"user_id\", \"tenant_id\", \"err_type\", \"err_message\", \"err_code\",\n]);\n\nexport function stripUrl(url: string): string {\n const noQuery = url.split(/[?#]/, 1)[0] ?? \"\";\n return noQuery.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/@\\s]*@/i, \"$1\");\n}\n\nexport function truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max - TRUNCATED.length) + TRUNCATED : s;\n}\n\nfunction isPlainObject(v: unknown): v is Fields {\n if (typeof v !== \"object\" || v === null) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction isUrlKey(key: string): boolean {\n return key === \"http_path\" || key === \"http_url\" || key.endsWith(\"_url\");\n}\n\nfunction flattenInto(out: LogRecord, prefix: string, obj: Fields, depth: number, opts: NormalizeOptions): void {\n for (const [rawKey, value] of Object.entries(obj)) {\n const key = opts.snakeCase ? toSnakeCase(rawKey) : rawKey;\n const full = prefix ? `${prefix}_${key}` : key;\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") continue;\n if (value !== null && (opts.redactor.isSensitive(rawKey) || opts.redactor.isSensitive(full))) {\n out[full] = REDACTED;\n continue;\n }\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n out[full] = value;\n } else if (typeof value === \"number\") {\n out[full] = Number.isFinite(value) ? value : String(value);\n } else if (typeof value === \"bigint\") {\n out[full] = value.toString();\n } else if (value instanceof Date) {\n out[full] = Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n } else if (isErrorLike(value)) {\n out[full] = `${value.name}: ${value.message}`;\n } else if (isPlainObject(value) && depth < MAX_DEPTH - 1) {\n flattenInto(out, full, value, depth + 1, opts);\n } else {\n // Arrays, deep objects, class instances: stringified with sensitive keys redacted.\n out[full] = opts.redactor.json(value);\n }\n }\n}\n\nfunction finalize(key: string, value: Primitive, opts: NormalizeOptions): Primitive {\n if (typeof value !== \"string\") return value;\n const v = opts.redactor.scrub(isUrlKey(key) ? stripUrl(value) : value);\n return truncate(v, key === \"err_stack\" ? MAX_STACK : MAX_STRING);\n}\n\nexport function buildRecord(\n level: Level,\n message: unknown,\n sources: (Fields | undefined)[],\n opts: NormalizeOptions,\n): LogRecord {\n const merged: Fields = {};\n for (const source of sources) if (source) Object.assign(merged, source);\n\n let err: unknown;\n if (merged.err !== undefined && merged.err !== null) {\n err = merged.err;\n delete merged.err;\n } else if (isErrorLike(merged.error)) {\n err = merged.error;\n delete merged.error;\n }\n\n const flat: LogRecord = {};\n flattenInto(flat, \"\", merged, 0, opts);\n if (err !== undefined) Object.assign(flat, serializeError(err));\n\n const text = typeof message === \"string\" ? message : opts.redactor.json(message);\n const out: LogRecord = { level, message: truncate(opts.redactor.scrub(text), MAX_MESSAGE) };\n for (const [k, v] of Object.entries(flat)) {\n const key = RESERVED_KEYS.has(k) ? `app_${k}` : k;\n let value = finalize(key, v, opts);\n if (opts.hook && !HOOK_EXEMPT.has(key)) {\n const replaced = opts.hook(key, value);\n if (replaced === undefined) continue;\n value = typeof replaced === \"object\" && replaced !== null ? opts.redactor.json(replaced) : (replaced as Primitive);\n }\n out[key] = value;\n }\n return out;\n}\n\nfunction byteLength(s: string): number {\n // UTF-8 uses at most 3 bytes per UTF-16 code unit: skip encoding short lines.\n if (s.length * 3 <= MAX_LINE_BYTES) return s.length;\n return new TextEncoder().encode(s).length;\n}\n\nexport function serializeRecord(record: LogRecord): string {\n const line = JSON.stringify(record);\n if (byteLength(line) <= MAX_LINE_BYTES) return line;\n const small: LogRecord = {};\n for (const [k, v] of Object.entries(record)) {\n if (KEEP_ON_SHRINK.has(k) || k.startsWith(\"http_\")) small[k] = v;\n }\n small.log_truncated = true;\n return JSON.stringify(small);\n}\n","import type { LogRecord } from \"./normalize\";\n\n// Human-readable line for local development only (LOG_FORMAT=pretty).\nexport function formatPretty(record: LogRecord): string {\n const { level, message, err_stack, ...rest } = record;\n const time = new Date().toISOString().slice(11, 23);\n const extras = Object.entries(rest)\n .map(([k, v]) => `${k}=${typeof v === \"string\" && /\\s/.test(v) ? JSON.stringify(v) : String(v)}`)\n .join(\" \");\n let line = `${time} ${String(level).toUpperCase().padEnd(5)} ${String(message)}${extras ? ` ${extras}` : \"\"}`;\n if (typeof err_stack === \"string\") line += `\\n${err_stack}`;\n return line;\n}\n","import { getContext } from \"./context\";\nimport { LEVEL_RANK, parseLevel, type Level } from \"./levels\";\nimport {\n buildRecord,\n serializeRecord,\n type Fields,\n type NormalizeOptions,\n type RedactHook,\n} from \"./normalize\";\nimport { formatPretty } from \"./pretty\";\nimport { createRedactor, type KeyPattern } from \"./redact\";\n\ntype LogMethod = (message: string, fields?: Fields) => void;\n\nexport interface Logger {\n readonly level: Level;\n trace: LogMethod;\n debug: LogMethod;\n info: LogMethod;\n warn: LogMethod;\n error: LogMethod;\n fatal: LogMethod;\n child(fields: Fields): Logger;\n isLevelEnabled(level: Level): boolean;\n}\n\nexport interface LoggerOptions {\n level?: Level | string;\n format?: \"json\" | \"pretty\";\n base?: Fields;\n /** Extra sensitive keys: names (matched like the defaults) or RegExp tested on the snake_case key. */\n redactKeys?: KeyPattern[];\n /** Extra value patterns masked in every string, e.g. REDACT_PATTERNS.phoneVN. */\n redactValues?: RegExp[];\n /** Final per-field hook: return a replacement, or undefined to drop the field. */\n redact?: RedactHook;\n snakeCase?: boolean;\n write?: (line: string) => void;\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== \"undefined\" ? process.env?.[name] : undefined;\n}\n\n// Captured before patchConsole can replace it, so the fallback never loops into the logger.\nconst consoleLog = console.log.bind(console);\n\nfunction defaultWrite(line: string): void {\n if (typeof process !== \"undefined\" && typeof process.stdout?.write === \"function\") {\n process.stdout.write(`${line}\\n`);\n } else {\n consoleLog(line);\n }\n}\n\nexport function createLogger(options: LoggerOptions = {}): Logger {\n const level = parseLevel(options.level ?? env(\"LOG_LEVEL\"));\n const format = options.format ?? (env(\"LOG_FORMAT\") === \"pretty\" ? \"pretty\" : \"json\");\n const write = options.write ?? defaultWrite;\n const norm: NormalizeOptions = {\n snakeCase: options.snakeCase ?? true,\n redactor: createRedactor({ keys: options.redactKeys, values: options.redactValues }),\n hook: options.redact,\n };\n\n const make = (bound: Fields): Logger => {\n const emit = (lvl: Level, message: string, fields?: Fields) => {\n if (LEVEL_RANK[lvl] < LEVEL_RANK[level]) return;\n let line: string;\n try {\n const record = buildRecord(lvl, message, [options.base, getContext(), bound, fields], norm);\n line = format === \"pretty\" ? formatPretty(record) : serializeRecord(record);\n } catch (e) {\n line = JSON.stringify({\n level: \"error\",\n message: \"log serialize failed\",\n event: \"log.serialize_failed\",\n err_message: String((e as Error)?.message ?? e).slice(0, 1000),\n original_message: String(message).slice(0, 500),\n });\n }\n try {\n write(line);\n } catch {\n // Logging must never break the app.\n }\n };\n return {\n level,\n trace: (m, f) => emit(\"trace\", m, f),\n debug: (m, f) => emit(\"debug\", m, f),\n info: (m, f) => emit(\"info\", m, f),\n warn: (m, f) => emit(\"warn\", m, f),\n error: (m, f) => emit(\"error\", m, f),\n fatal: (m, f) => emit(\"fatal\", m, f),\n child: (fields) => make({ ...bound, ...fields }),\n isLevelEnabled: (l) => LEVEL_RANK[l] >= LEVEL_RANK[level],\n };\n };\n return make({});\n}\n","// No imports: this module is shared with the edge entry (next-edge).\nexport const REQUEST_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\nexport function newRequestId(): string {\n return globalThis.crypto.randomUUID();\n}\n\nfunction first(header?: string | string[] | null): string | undefined {\n return Array.isArray(header) ? header[0] : (header ?? undefined);\n}\n\nexport function resolveRequestId(header?: string | string[] | null): string {\n const value = first(header);\n return value && REQUEST_ID_RE.test(value) ? value : newRequestId();\n}\n\nexport function parseTraceparent(header?: string | string[] | null): { trace_id: string; span_id: string } | undefined {\n const value = first(header)?.trim().toLowerCase();\n const m = value ? TRACEPARENT_RE.exec(value) : null;\n if (!m) return undefined;\n const [, version, traceId, spanId] = m as unknown as [string, string, string, string];\n if (version === \"ff\" || /^0+$/.test(traceId) || /^0+$/.test(spanId)) return undefined;\n return { trace_id: traceId, span_id: spanId };\n}\n","import { getContext } from \"./context\";\nimport { markLogged, serializeError } from \"./error\";\nimport type { Logger } from \"./logger\";\nimport { stripUrl, type Fields } from \"./normalize\";\nimport { parseTraceparent, resolveRequestId } from \"./request-id\";\n\nexport { newRequestId, parseTraceparent, REQUEST_ID_RE, resolveRequestId } from \"./request-id\";\n\nexport type HeaderSource = Headers | Record<string, string | string[] | undefined>;\n\nfunction header(headers: HeaderSource, name: string): string | string[] | undefined {\n if (typeof (headers as Headers).get === \"function\") return (headers as Headers).get(name) ?? undefined;\n return (headers as Record<string, string | string[] | undefined>)[name];\n}\n\nexport function requestContextFields(headers: HeaderSource): { request_id: string; trace_id?: string; span_id?: string } {\n const out: { request_id: string; trace_id?: string; span_id?: string } = {\n request_id: resolveRequestId(header(headers, \"x-request-id\")),\n };\n const tp = parseTraceparent(header(headers, \"traceparent\"));\n if (tp) Object.assign(out, tp);\n return out;\n}\n\n// Headers to forward to services we own, so their logs share request_id / trace_id.\nexport function propagationHeaders(): Record<string, string> {\n const ctx = getContext();\n const out: Record<string, string> = {};\n if (typeof ctx.request_id === \"string\") out[\"x-request-id\"] = ctx.request_id;\n if (typeof ctx.trace_id === \"string\" && typeof ctx.span_id === \"string\") {\n out.traceparent = `00-${ctx.trace_id}-${ctx.span_id}-01`;\n }\n return out;\n}\n\nexport const DEFAULT_SKIP_PATHS: (string | RegExp)[] = [\n /^\\/(health|healthz|ready|readyz|livez)\\/?$/,\n \"/favicon.ico\",\n /^\\/_next\\/static\\//,\n];\n\nexport interface HttpLogOptions {\n skipPaths?: (string | RegExp)[];\n}\n\nexport interface HttpRequestInfo {\n method: string;\n route?: string;\n path: string;\n status: number;\n duration_ms?: number;\n err?: unknown;\n fields?: Fields;\n}\n\nexport function shouldSkip(method: string, path: string, skipPaths: (string | RegExp)[] = DEFAULT_SKIP_PATHS): boolean {\n if (method.toUpperCase() === \"OPTIONS\") return true;\n const p = stripUrl(path);\n return skipPaths.some((s) => (typeof s === \"string\" ? p === s : s.test(p)));\n}\n\n// Writes the one `http.request` summary line for an inbound request.\nexport function logHttpRequest(log: Logger, info: HttpRequestInfo, opts: HttpLogOptions = {}): void {\n if (shouldSkip(info.method, info.path, opts.skipPaths)) return;\n const level = info.status >= 500 ? \"error\" : info.status >= 400 ? \"warn\" : \"info\";\n const path = stripUrl(info.path);\n const errFields: Fields = {};\n if (info.err !== undefined && info.err !== null) {\n Object.assign(errFields, serializeError(info.err));\n if (info.status < 500) delete errFields.err_stack;\n markLogged(info.err);\n }\n // Route templates keep the message bounded; the raw path would make one message per URL.\n const message = info.route ? `${info.method} ${info.route} ${info.status}` : `${info.method} ${info.status}`;\n log[level](message, {\n ...info.fields,\n event: \"http.request\",\n http_method: info.method,\n http_route: info.route,\n http_path: path,\n http_status: info.status,\n duration_ms: info.duration_ms === undefined ? undefined : Math.round(info.duration_ms),\n ...errFields,\n });\n}\n","import { propagationHeaders } from \"./http\";\nimport type { Logger } from \"./logger\";\n\nexport interface FetchLogOptions {\n peer_service: string;\n /** Forward x-request-id / traceparent. Only for services we own. */\n internal?: boolean;\n slowMs?: number;\n fetch?: typeof fetch;\n}\n\nfunction describeRequest(input: RequestInfo | URL, init?: RequestInit): { method: string; url: string } {\n const method = (init?.method ?? (input instanceof Request ? input.method : \"GET\")).toUpperCase();\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n return { method, url };\n}\n\nexport function createFetch(log: Logger, opts: FetchLogOptions): typeof fetch {\n const slowMs = opts.slowMs ?? 1000;\n const wrapped = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const base = opts.fetch ?? globalThis.fetch;\n const { method, url } = describeRequest(input, init);\n let requestInit = init;\n if (opts.internal) {\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n for (const [k, v] of Object.entries(propagationHeaders())) if (!headers.has(k)) headers.set(k, v);\n requestInit = { ...init, headers };\n }\n const fields = { event: \"http.outbound\", peer_service: opts.peer_service, http_method: method, http_url: url };\n const start = performance.now();\n try {\n const res = await base(input, requestInit);\n const duration_ms = Math.round(performance.now() - start);\n if (res.status >= 500) {\n log.warn(\"outbound request failed\", { ...fields, http_status: res.status, duration_ms });\n } else if (duration_ms >= slowMs) {\n log.warn(\"outbound request slow\", { ...fields, http_status: res.status, duration_ms });\n }\n return res;\n } catch (err) {\n log.warn(\"outbound request failed\", { ...fields, duration_ms: Math.round(performance.now() - start), err });\n throw err;\n }\n };\n return wrapped as typeof fetch;\n}\n","import { getContext, withContext } from \"./context\";\nimport { markLogged } from \"./error\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\nexport interface JobInfo {\n job_name: string;\n job_id?: string | number;\n job_attempt?: number;\n /** No retries left after this attempt (or decided per error). Defaults to true when unknown. */\n final_attempt?: boolean | ((err: unknown) => boolean);\n request_id?: string;\n fields?: Fields;\n}\n\nexport async function runJob<T>(log: Logger, info: JobInfo, fn: () => T | Promise<T>): Promise<T> {\n const ctx: Fields = { ...info.fields, job_name: info.job_name };\n if (info.job_id !== undefined) ctx.job_id = String(info.job_id);\n if (info.job_attempt !== undefined) ctx.job_attempt = info.job_attempt;\n if (info.request_id !== undefined) ctx.request_id = info.request_id;\n\n return withContext(ctx, async () => {\n const start = performance.now();\n try {\n const result = await fn();\n log.info(\"job completed\", { event: \"job.completed\", duration_ms: Math.round(performance.now() - start) });\n return result;\n } catch (err) {\n const final = typeof info.final_attempt === \"function\" ? info.final_attempt(err) : (info.final_attempt ?? true);\n log[final ? \"error\" : \"warn\"](\"job failed\", {\n event: \"job.failed\",\n duration_ms: Math.round(performance.now() - start),\n err,\n });\n markLogged(err);\n throw err;\n }\n });\n}\n\n/** Adds the current request_id to a job payload, so the job's logs link back to the request. */\nexport function jobData<T extends Record<string, unknown>>(data: T): T & { request_id?: string } {\n const requestId = getContext().request_id;\n if (typeof requestId !== \"string\" || data.request_id !== undefined) return data;\n return { ...data, request_id: requestId };\n}\n","import { isErrorLike, isLogged } from \"./error\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport { defaultRedactor } from \"./redact\";\n\nconst METHODS = { log: \"info\", info: \"info\", warn: \"warn\", error: \"error\", debug: \"debug\", trace: \"debug\" } as const;\ntype Method = keyof typeof METHODS;\ntype ConsoleFn = (...args: unknown[]) => void;\n\nexport interface PatchConsoleOptions {\n /** Return true to drop a console call, e.g. errors a framework hook will log anyway. */\n skip?: (args: unknown[]) => boolean;\n}\n\n/**\n * Routes console.log/info/warn/error/debug/trace through the logger, so legacy console calls\n * and framework output (e.g. Next.js errors) become JSON lines with request context.\n * Calls carrying an error that is already on a summary line are dropped.\n * Returns a function that restores the previous console methods.\n */\nexport function patchConsole(log: Logger, opts: PatchConsoleOptions = {}): () => void {\n const target = console as unknown as Record<Method, ConsoleFn>;\n const saved = {} as Record<Method, ConsoleFn>;\n let inside = false;\n\n for (const method of Object.keys(METHODS) as Method[]) {\n const previous = target[method];\n saved[method] = previous;\n const level: Level = METHODS[method];\n target[method] = (...args: unknown[]) => {\n // A write path that itself uses console must not loop back into the logger.\n if (inside) return previous.apply(console, args);\n inside = true;\n try {\n if (args.some((arg) => isErrorLike(arg) && isLogged(arg)) || opts.skip?.(args)) return;\n let err: unknown;\n const parts: string[] = [];\n for (const arg of args) {\n if (isErrorLike(arg)) {\n err ??= arg;\n parts.push(arg.message);\n } else {\n parts.push(typeof arg === \"string\" ? arg : defaultRedactor.json(arg));\n }\n }\n log[level](parts.join(\" \"), { event: \"console\", console_method: method, err });\n } finally {\n inside = false;\n }\n };\n }\n\n return () => {\n for (const method of Object.keys(saved) as Method[]) target[method] = saved[method];\n };\n}\n","import { globalSingleton } from \"./global\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\nexport function logStartup(log: Logger, fields: Fields = {}): void {\n log.info(\"app started\", {\n event: \"app.started\",\n runtime_version: `node ${process.versions.node}`,\n log_level: log.level,\n ...fields,\n });\n}\n\n/** Call at the start of your own shutdown handler (e.g. on SIGTERM). The library never handles signals. */\nexport function logShutdown(log: Logger, fields: Fields = {}): void {\n log.info(\"app stopping\", { event: \"app.stopping\", ...fields });\n}\n\nexport interface ProcessHandlerOptions {\n /** Exit with code 1 after an uncaught error. Next.js keeps serving, so its adapter passes false. */\n exitOnCrash?: boolean;\n /** Time other crash handlers (Sentry, APM) get to flush before exit. Default 1000 ms. */\n exitDelayMs?: number;\n exit?: (code: number) => void;\n}\n\nexport function crashHandlers(log: Logger, opts: ProcessHandlerOptions = {}) {\n const exitOnCrash = opts.exitOnCrash ?? true;\n const exitDelayMs = opts.exitDelayMs ?? 1000;\n const exit = opts.exit ?? ((code: number) => process.exit(code));\n let exiting = false;\n const crash = (source: string, err: unknown) => {\n if (!exitOnCrash) {\n log.error(\"unhandled error\", { event: \"app.unhandled_error\", crash_source: source, err });\n return;\n }\n log.fatal(\"app crashed\", { event: \"app.crashed\", crash_source: source, err });\n if (exiting) return;\n exiting = true;\n if (typeof process !== \"undefined\") process.exitCode = 1;\n // Deferred so listeners registered after ours still run; unref so a process with nothing\n // left to do exits on its own (with exitCode 1) without waiting.\n const timer = setTimeout(() => exit(1), exitDelayMs);\n (timer as { unref?: () => void }).unref?.();\n };\n return {\n onUncaught: (err: unknown) => crash(\"uncaughtException\", err),\n onRejection: (reason: unknown) => crash(\"unhandledRejection\", reason),\n };\n}\n\nconst state = globalSingleton(\"process\", () => ({ installed: false }));\n\n/** Logs uncaught exceptions and unhandled rejections. Does not touch SIGTERM/SIGINT. */\nexport function installProcessHandlers(log: Logger, opts: ProcessHandlerOptions = {}): void {\n if (state.installed || typeof process === \"undefined\" || typeof process.on !== \"function\") return;\n state.installed = true;\n const h = crashHandlers(log, opts);\n process.on(\"uncaughtException\", h.onUncaught);\n process.on(\"unhandledRejection\", h.onRejection);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,8BAAkC;;;ACE3B,SAAS,gBAAmB,MAAc,MAAkB;AACjE,QAAM,MAAM,uBAAO,IAAI,iBAAiB,IAAI,EAAE;AAC9C,QAAM,IAAI;AACV,MAAI,QAAQ,EAAE,GAAG;AACjB,MAAI,UAAU,QAAW;AACvB,YAAQ,KAAK;AACb,MAAE,GAAG,IAAI;AAAA,EACX;AACA,SAAO;AACT;;;ADCA,IAAM,MAAM,gBAAgB,OAAO,MAAM,IAAI,0CAAgC,CAAC;AAIvE,SAAS,aAAgB,QAAgB,IAAmC;AACjF,QAAM,SAAS,IAAI,SAAS;AAC5B,QAAM,QAAsB,EAAE,QAAQ,EAAE,GAAG,QAAQ,QAAQ,GAAG,OAAO,GAAG,OAAO;AAC/E,SAAO,IAAI,IAAI,OAAO,MAAM,GAAG,KAAK,CAAC;AACvC;AAEO,SAAS,YAAe,QAA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jobData<T extends Record<string, unknown>>(data: T): T & {
46
46
  request_id?: string;
47
47
  };
48
48
 
49
+ interface PatchConsoleOptions {
50
+ /** Return true to drop a console call, e.g. errors a framework hook will log anyway. */
51
+ skip?: (args: unknown[]) => boolean;
52
+ }
49
53
  /**
50
54
  * Routes console.log/info/warn/error/debug/trace through the logger, so legacy console calls
51
55
  * and framework output (e.g. Next.js errors) become JSON lines with request context.
56
+ * Calls carrying an error that is already on a summary line are dropped.
52
57
  * Returns a function that restores the previous console methods.
53
58
  */
54
- declare function patchConsole(log: Logger): () => void;
59
+ declare function patchConsole(log: Logger, opts?: PatchConsoleOptions): () => void;
55
60
 
56
61
  declare function logStartup(log: Logger, fields?: Fields): void;
57
62
  /** Call at the start of your own shutdown handler (e.g. on SIGTERM). The library never handles signals. */
@@ -66,4 +71,4 @@ interface ProcessHandlerOptions {
66
71
  /** Logs uncaught exceptions and unhandled rejections. Does not touch SIGTERM/SIGINT. */
67
72
  declare function installProcessHandlers(log: Logger, opts?: ProcessHandlerOptions): void;
68
73
 
69
- export { type FetchLogOptions, Fields, type JobInfo, Logger, type ProcessHandlerOptions, addContext, createFetch, getContext, installProcessHandlers, jobData, logShutdown, logStartup, parseTraceparent, patchConsole, recordError, resolveRequestId, runJob, serializeError, withContext };
74
+ export { type FetchLogOptions, Fields, type JobInfo, Logger, type PatchConsoleOptions, type ProcessHandlerOptions, addContext, createFetch, getContext, installProcessHandlers, jobData, logShutdown, logStartup, parseTraceparent, patchConsole, recordError, resolveRequestId, runJob, serializeError, withContext };
package/dist/index.d.ts CHANGED
@@ -46,12 +46,17 @@ declare function jobData<T extends Record<string, unknown>>(data: T): T & {
46
46
  request_id?: string;
47
47
  };
48
48
 
49
+ interface PatchConsoleOptions {
50
+ /** Return true to drop a console call, e.g. errors a framework hook will log anyway. */
51
+ skip?: (args: unknown[]) => boolean;
52
+ }
49
53
  /**
50
54
  * Routes console.log/info/warn/error/debug/trace through the logger, so legacy console calls
51
55
  * and framework output (e.g. Next.js errors) become JSON lines with request context.
56
+ * Calls carrying an error that is already on a summary line are dropped.
52
57
  * Returns a function that restores the previous console methods.
53
58
  */
54
- declare function patchConsole(log: Logger): () => void;
59
+ declare function patchConsole(log: Logger, opts?: PatchConsoleOptions): () => void;
55
60
 
56
61
  declare function logStartup(log: Logger, fields?: Fields): void;
57
62
  /** Call at the start of your own shutdown handler (e.g. on SIGTERM). The library never handles signals. */
@@ -66,4 +71,4 @@ interface ProcessHandlerOptions {
66
71
  /** Logs uncaught exceptions and unhandled rejections. Does not touch SIGTERM/SIGINT. */
67
72
  declare function installProcessHandlers(log: Logger, opts?: ProcessHandlerOptions): void;
68
73
 
69
- export { type FetchLogOptions, Fields, type JobInfo, Logger, type ProcessHandlerOptions, addContext, createFetch, getContext, installProcessHandlers, jobData, logShutdown, logStartup, parseTraceparent, patchConsole, recordError, resolveRequestId, runJob, serializeError, withContext };
74
+ export { type FetchLogOptions, Fields, type JobInfo, Logger, type PatchConsoleOptions, type ProcessHandlerOptions, addContext, createFetch, getContext, installProcessHandlers, jobData, logShutdown, logStartup, parseTraceparent, patchConsole, recordError, resolveRequestId, runJob, serializeError, withContext };
package/dist/index.js CHANGED
@@ -26,6 +26,7 @@ import {
26
26
  defaultRedactor,
27
27
  getContext,
28
28
  isErrorLike,
29
+ isLogged,
29
30
  recordError,
30
31
  serializeError,
31
32
  withContext
@@ -156,7 +157,7 @@ function createFetch(log, opts) {
156
157
 
157
158
  // src/console.ts
158
159
  var METHODS = { log: "info", info: "info", warn: "warn", error: "error", debug: "debug", trace: "debug" };
159
- function patchConsole(log) {
160
+ function patchConsole(log, opts = {}) {
160
161
  const target = console;
161
162
  const saved = {};
162
163
  let inside = false;
@@ -168,6 +169,7 @@ function patchConsole(log) {
168
169
  if (inside) return previous.apply(console, args);
169
170
  inside = true;
170
171
  try {
172
+ if (args.some((arg) => isErrorLike(arg) && isLogged(arg)) || opts.skip?.(args)) return;
171
173
  let err;
172
174
  const parts = [];
173
175
  for (const arg of args) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/levels.ts","../src/pretty.ts","../src/logger.ts","../src/fetch.ts","../src/console.ts"],"sourcesContent":["export const LEVELS = [\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\"] as const;\nexport type Level = (typeof LEVELS)[number];\n\nexport const LEVEL_RANK: Record<Level, number> = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n};\n\nconst ALIASES: Record<string, Level> = { warning: \"warn\", err: \"error\", critical: \"fatal\", panic: \"fatal\" };\n\nexport function parseLevel(value: unknown, fallback: Level = \"info\"): Level {\n if (typeof value !== \"string\") return fallback;\n const v = value.trim().toLowerCase();\n if ((LEVELS as readonly string[]).includes(v)) return v as Level;\n return ALIASES[v] ?? fallback;\n}\n","import type { LogRecord } from \"./normalize\";\n\n// Human-readable line for local development only (LOG_FORMAT=pretty).\nexport function formatPretty(record: LogRecord): string {\n const { level, message, err_stack, ...rest } = record;\n const time = new Date().toISOString().slice(11, 23);\n const extras = Object.entries(rest)\n .map(([k, v]) => `${k}=${typeof v === \"string\" && /\\s/.test(v) ? JSON.stringify(v) : String(v)}`)\n .join(\" \");\n let line = `${time} ${String(level).toUpperCase().padEnd(5)} ${String(message)}${extras ? ` ${extras}` : \"\"}`;\n if (typeof err_stack === \"string\") line += `\\n${err_stack}`;\n return line;\n}\n","import { getContext } from \"./context\";\nimport { LEVEL_RANK, parseLevel, type Level } from \"./levels\";\nimport {\n buildRecord,\n serializeRecord,\n type Fields,\n type NormalizeOptions,\n type RedactHook,\n} from \"./normalize\";\nimport { formatPretty } from \"./pretty\";\nimport { createRedactor, type KeyPattern } from \"./redact\";\n\ntype LogMethod = (message: string, fields?: Fields) => void;\n\nexport interface Logger {\n readonly level: Level;\n trace: LogMethod;\n debug: LogMethod;\n info: LogMethod;\n warn: LogMethod;\n error: LogMethod;\n fatal: LogMethod;\n child(fields: Fields): Logger;\n isLevelEnabled(level: Level): boolean;\n}\n\nexport interface LoggerOptions {\n level?: Level | string;\n format?: \"json\" | \"pretty\";\n base?: Fields;\n /** Extra sensitive keys: names (matched like the defaults) or RegExp tested on the snake_case key. */\n redactKeys?: KeyPattern[];\n /** Extra value patterns masked in every string, e.g. REDACT_PATTERNS.phoneVN. */\n redactValues?: RegExp[];\n /** Final per-field hook: return a replacement, or undefined to drop the field. */\n redact?: RedactHook;\n snakeCase?: boolean;\n write?: (line: string) => void;\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== \"undefined\" ? process.env?.[name] : undefined;\n}\n\n// Captured before patchConsole can replace it, so the fallback never loops into the logger.\nconst consoleLog = console.log.bind(console);\n\nfunction defaultWrite(line: string): void {\n if (typeof process !== \"undefined\" && typeof process.stdout?.write === \"function\") {\n process.stdout.write(`${line}\\n`);\n } else {\n consoleLog(line);\n }\n}\n\nexport function createLogger(options: LoggerOptions = {}): Logger {\n const level = parseLevel(options.level ?? env(\"LOG_LEVEL\"));\n const format = options.format ?? (env(\"LOG_FORMAT\") === \"pretty\" ? \"pretty\" : \"json\");\n const write = options.write ?? defaultWrite;\n const norm: NormalizeOptions = {\n snakeCase: options.snakeCase ?? true,\n redactor: createRedactor({ keys: options.redactKeys, values: options.redactValues }),\n hook: options.redact,\n };\n\n const make = (bound: Fields): Logger => {\n const emit = (lvl: Level, message: string, fields?: Fields) => {\n if (LEVEL_RANK[lvl] < LEVEL_RANK[level]) return;\n let line: string;\n try {\n const record = buildRecord(lvl, message, [options.base, getContext(), bound, fields], norm);\n line = format === \"pretty\" ? formatPretty(record) : serializeRecord(record);\n } catch (e) {\n line = JSON.stringify({\n level: \"error\",\n message: \"log serialize failed\",\n event: \"log.serialize_failed\",\n err_message: String((e as Error)?.message ?? e).slice(0, 1000),\n original_message: String(message).slice(0, 500),\n });\n }\n try {\n write(line);\n } catch {\n // Logging must never break the app.\n }\n };\n return {\n level,\n trace: (m, f) => emit(\"trace\", m, f),\n debug: (m, f) => emit(\"debug\", m, f),\n info: (m, f) => emit(\"info\", m, f),\n warn: (m, f) => emit(\"warn\", m, f),\n error: (m, f) => emit(\"error\", m, f),\n fatal: (m, f) => emit(\"fatal\", m, f),\n child: (fields) => make({ ...bound, ...fields }),\n isLevelEnabled: (l) => LEVEL_RANK[l] >= LEVEL_RANK[level],\n };\n };\n return make({});\n}\n","import { propagationHeaders } from \"./http\";\nimport type { Logger } from \"./logger\";\n\nexport interface FetchLogOptions {\n peer_service: string;\n /** Forward x-request-id / traceparent. Only for services we own. */\n internal?: boolean;\n slowMs?: number;\n fetch?: typeof fetch;\n}\n\nfunction describeRequest(input: RequestInfo | URL, init?: RequestInit): { method: string; url: string } {\n const method = (init?.method ?? (input instanceof Request ? input.method : \"GET\")).toUpperCase();\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n return { method, url };\n}\n\nexport function createFetch(log: Logger, opts: FetchLogOptions): typeof fetch {\n const slowMs = opts.slowMs ?? 1000;\n const wrapped = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const base = opts.fetch ?? globalThis.fetch;\n const { method, url } = describeRequest(input, init);\n let requestInit = init;\n if (opts.internal) {\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n for (const [k, v] of Object.entries(propagationHeaders())) if (!headers.has(k)) headers.set(k, v);\n requestInit = { ...init, headers };\n }\n const fields = { event: \"http.outbound\", peer_service: opts.peer_service, http_method: method, http_url: url };\n const start = performance.now();\n try {\n const res = await base(input, requestInit);\n const duration_ms = Math.round(performance.now() - start);\n if (res.status >= 500) {\n log.warn(\"outbound request failed\", { ...fields, http_status: res.status, duration_ms });\n } else if (duration_ms >= slowMs) {\n log.warn(\"outbound request slow\", { ...fields, http_status: res.status, duration_ms });\n }\n return res;\n } catch (err) {\n log.warn(\"outbound request failed\", { ...fields, duration_ms: Math.round(performance.now() - start), err });\n throw err;\n }\n };\n return wrapped as typeof fetch;\n}\n","import { isErrorLike } from \"./error\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport { defaultRedactor } from \"./redact\";\n\nconst METHODS = { log: \"info\", info: \"info\", warn: \"warn\", error: \"error\", debug: \"debug\", trace: \"debug\" } as const;\ntype Method = keyof typeof METHODS;\ntype ConsoleFn = (...args: unknown[]) => void;\n\n/**\n * Routes console.log/info/warn/error/debug/trace through the logger, so legacy console calls\n * and framework output (e.g. Next.js errors) become JSON lines with request context.\n * Returns a function that restores the previous console methods.\n */\nexport function patchConsole(log: Logger): () => void {\n const target = console as unknown as Record<Method, ConsoleFn>;\n const saved = {} as Record<Method, ConsoleFn>;\n let inside = false;\n\n for (const method of Object.keys(METHODS) as Method[]) {\n const previous = target[method];\n saved[method] = previous;\n const level: Level = METHODS[method];\n target[method] = (...args: unknown[]) => {\n // A write path that itself uses console must not loop back into the logger.\n if (inside) return previous.apply(console, args);\n inside = true;\n try {\n let err: unknown;\n const parts: string[] = [];\n for (const arg of args) {\n if (isErrorLike(arg)) {\n err ??= arg;\n parts.push(arg.message);\n } else {\n parts.push(typeof arg === \"string\" ? arg : defaultRedactor.json(arg));\n }\n }\n log[level](parts.join(\" \"), { event: \"console\", console_method: method, err });\n } finally {\n inside = false;\n }\n };\n }\n\n return () => {\n for (const method of Object.keys(saved) as Method[]) target[method] = saved[method];\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAO,IAAM,SAAS,CAAC,SAAS,SAAS,QAAQ,QAAQ,SAAS,OAAO;AAGlE,IAAM,aAAoC;AAAA,EAC/C,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AACT;AAEA,IAAM,UAAiC,EAAE,SAAS,QAAQ,KAAK,SAAS,UAAU,SAAS,OAAO,QAAQ;AAEnG,SAAS,WAAW,OAAgB,WAAkB,QAAe;AAC1E,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,IAAI,MAAM,KAAK,EAAE,YAAY;A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,MACvF;AACA,aAAO;AAAA,IACT,SAAS,KAAK;AACZ,UAAI,KAAK,2BAA2B,EAAE,GAAG,QAAQ,aAAa,KAAK,MAAM,YAAY,IAAI,IAAI,KAAK,GAAG,IAAI,CAAC;AAC1G,YAAM;AAAA,IACR;AAAA,EACF;AACA,SAAO;AACT;;;ACxCA,IAAM,UAAU,EAAE,KAAK,QAAQ,MAAM,QAAQ,MAAM,QAAQ,OAAO,SAAS,OAAO,SAAS,OAAO,QAAQ;AASnG,SAAS,aAAa,KAAyB;AACpD,QAAM,SAAS;AACf,QAAM,QAAQ,CAAC;AACf,MAAI,SAAS;AAEb,aAAW,UAAU,OAAO,KAAK,OAAO,GAAe;AACrD,UAAM,WAAW,OAAO,MAAM;AAC9B,UAAM,MAAM,IAAI;AAChB,UAAM,QAAe,QAAQ,MAAM;AACnC,WAAO,MAAM,IAAI,IAAI,SAAoB;AAEvC,UAAI,OAAQ,QAAO,SAAS,MAAM,SAAS,IAAI;AAC/C,eAAS;AACT,UAAI;AACF,YAAI;AACJ,cAAM,QAAkB,CAAC;AACzB,mBAAW,OAAO,MAAM;AACtB,cAAI,YAAY,GAAG,GAAG;AACpB,oBAAQ;AACR,kBAAM,KAAK,IAAI,OAAO;AAAA,UACxB,OAAO;AACL,kBAAM,KAAK,OAAO,QAAQ,WAAW,MAAM,gBAAgB,KAAK,GAAG,CAAC;AAAA,UACtE;AAAA,QACF;AACA,YAAI,KAAK,EAAE,MAAM,KAAK,GAAG,GAAG,EAAE,OAAO,WAAW,gBAAgB,QAAQ,IAAI,CAAC;AAAA,MAC/E,UAAE;AACA,iBAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF;AAEA,SAAO,MAAM;AACX,eAAW,UAAU,OAAO,KAAK,KAAK,EAAe,QAAO,MAAM,IAAI,MAAM,MAAM;AAAA,EACpF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/levels.ts","../src/pretty.ts","../src/logger.ts","../src/fetch.ts","../src/console.ts"],"sourcesContent":["export const LEVELS = [\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\"] as const;\nexport type Level = (typeof LEVELS)[number];\n\nexport const LEVEL_RANK: Record<Level, number> = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n};\n\nconst ALIASES: Record<string, Level> = { warning: \"warn\", err: \"error\", critical: \"fatal\", panic: \"fatal\" };\n\nexport function parseLevel(value: unknown, fallback: Level = \"info\"): Level {\n if (typeof value !== \"string\") return fallback;\n const v = value.trim().toLowerCase();\n if ((LEVELS as readonly string[]).includes(v)) return v as Level;\n return ALIASES[v] ?? fallback;\n}\n","import type { LogRecord } from \"./normalize\";\n\n// Human-readable line for local development only (LOG_FORMAT=pretty).\nexport function formatPretty(record: LogRecord): string {\n const { level, message, err_stack, ...rest } = record;\n const time = new Date().toISOString().slice(11, 23);\n const extras = Object.entries(rest)\n .map(([k, v]) => `${k}=${typeof v === \"string\" && /\\s/.test(v) ? JSON.stringify(v) : String(v)}`)\n .join(\" \");\n let line = `${time} ${String(level).toUpperCase().padEnd(5)} ${String(message)}${extras ? ` ${extras}` : \"\"}`;\n if (typeof err_stack === \"string\") line += `\\n${err_stack}`;\n return line;\n}\n","import { getContext } from \"./context\";\nimport { LEVEL_RANK, parseLevel, type Level } from \"./levels\";\nimport {\n buildRecord,\n serializeRecord,\n type Fields,\n type NormalizeOptions,\n type RedactHook,\n} from \"./normalize\";\nimport { formatPretty } from \"./pretty\";\nimport { createRedactor, type KeyPattern } from \"./redact\";\n\ntype LogMethod = (message: string, fields?: Fields) => void;\n\nexport interface Logger {\n readonly level: Level;\n trace: LogMethod;\n debug: LogMethod;\n info: LogMethod;\n warn: LogMethod;\n error: LogMethod;\n fatal: LogMethod;\n child(fields: Fields): Logger;\n isLevelEnabled(level: Level): boolean;\n}\n\nexport interface LoggerOptions {\n level?: Level | string;\n format?: \"json\" | \"pretty\";\n base?: Fields;\n /** Extra sensitive keys: names (matched like the defaults) or RegExp tested on the snake_case key. */\n redactKeys?: KeyPattern[];\n /** Extra value patterns masked in every string, e.g. REDACT_PATTERNS.phoneVN. */\n redactValues?: RegExp[];\n /** Final per-field hook: return a replacement, or undefined to drop the field. */\n redact?: RedactHook;\n snakeCase?: boolean;\n write?: (line: string) => void;\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== \"undefined\" ? process.env?.[name] : undefined;\n}\n\n// Captured before patchConsole can replace it, so the fallback never loops into the logger.\nconst consoleLog = console.log.bind(console);\n\nfunction defaultWrite(line: string): void {\n if (typeof process !== \"undefined\" && typeof process.stdout?.write === \"function\") {\n process.stdout.write(`${line}\\n`);\n } else {\n consoleLog(line);\n }\n}\n\nexport function createLogger(options: LoggerOptions = {}): Logger {\n const level = parseLevel(options.level ?? env(\"LOG_LEVEL\"));\n const format = options.format ?? (env(\"LOG_FORMAT\") === \"pretty\" ? \"pretty\" : \"json\");\n const write = options.write ?? defaultWrite;\n const norm: NormalizeOptions = {\n snakeCase: options.snakeCase ?? true,\n redactor: createRedactor({ keys: options.redactKeys, values: options.redactValues }),\n hook: options.redact,\n };\n\n const make = (bound: Fields): Logger => {\n const emit = (lvl: Level, message: string, fields?: Fields) => {\n if (LEVEL_RANK[lvl] < LEVEL_RANK[level]) return;\n let line: string;\n try {\n const record = buildRecord(lvl, message, [options.base, getContext(), bound, fields], norm);\n line = format === \"pretty\" ? formatPretty(record) : serializeRecord(record);\n } catch (e) {\n line = JSON.stringify({\n level: \"error\",\n message: \"log serialize failed\",\n event: \"log.serialize_failed\",\n err_message: String((e as Error)?.message ?? e).slice(0, 1000),\n original_message: String(message).slice(0, 500),\n });\n }\n try {\n write(line);\n } catch {\n // Logging must never break the app.\n }\n };\n return {\n level,\n trace: (m, f) => emit(\"trace\", m, f),\n debug: (m, f) => emit(\"debug\", m, f),\n info: (m, f) => emit(\"info\", m, f),\n warn: (m, f) => emit(\"warn\", m, f),\n error: (m, f) => emit(\"error\", m, f),\n fatal: (m, f) => emit(\"fatal\", m, f),\n child: (fields) => make({ ...bound, ...fields }),\n isLevelEnabled: (l) => LEVEL_RANK[l] >= LEVEL_RANK[level],\n };\n };\n return make({});\n}\n","import { propagationHeaders } from \"./http\";\nimport type { Logger } from \"./logger\";\n\nexport interface FetchLogOptions {\n peer_service: string;\n /** Forward x-request-id / traceparent. Only for services we own. */\n internal?: boolean;\n slowMs?: number;\n fetch?: typeof fetch;\n}\n\nfunction describeRequest(input: RequestInfo | URL, init?: RequestInit): { method: string; url: string } {\n const method = (init?.method ?? (input instanceof Request ? input.method : \"GET\")).toUpperCase();\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n return { method, url };\n}\n\nexport function createFetch(log: Logger, opts: FetchLogOptions): typeof fetch {\n const slowMs = opts.slowMs ?? 1000;\n const wrapped = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const base = opts.fetch ?? globalThis.fetch;\n const { method, url } = describeRequest(input, init);\n let requestInit = init;\n if (opts.internal) {\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n for (const [k, v] of Object.entries(propagationHeaders())) if (!headers.has(k)) headers.set(k, v);\n requestInit = { ...init, headers };\n }\n const fields = { event: \"http.outbound\", peer_service: opts.peer_service, http_method: method, http_url: url };\n const start = performance.now();\n try {\n const res = await base(input, requestInit);\n const duration_ms = Math.round(performance.now() - start);\n if (res.status >= 500) {\n log.warn(\"outbound request failed\", { ...fields, http_status: res.status, duration_ms });\n } else if (duration_ms >= slowMs) {\n log.warn(\"outbound request slow\", { ...fields, http_status: res.status, duration_ms });\n }\n return res;\n } catch (err) {\n log.warn(\"outbound request failed\", { ...fields, duration_ms: Math.round(performance.now() - start), err });\n throw err;\n }\n };\n return wrapped as typeof fetch;\n}\n","import { isErrorLike, isLogged } from \"./error\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport { defaultRedactor } from \"./redact\";\n\nconst METHODS = { log: \"info\", info: \"info\", warn: \"warn\", error: \"error\", debug: \"debug\", trace: \"debug\" } as const;\ntype Method = keyof typeof METHODS;\ntype ConsoleFn = (...args: unknown[]) => void;\n\nexport interface PatchConsoleOptions {\n /** Return true to drop a console call, e.g. errors a framework hook will log anyway. */\n skip?: (args: unknown[]) => boolean;\n}\n\n/**\n * Routes console.log/info/warn/error/debug/trace through the logger, so legacy console calls\n * and framework output (e.g. Next.js errors) become JSON lines with request context.\n * Calls carrying an error that is already on a summary line are dropped.\n * Returns a function that restores the previous console methods.\n */\nexport function patchConsole(log: Logger, opts: PatchConsoleOptions = {}): () => void {\n const target = console as unknown as Record<Method, ConsoleFn>;\n const saved = {} as Record<Method, ConsoleFn>;\n let inside = false;\n\n for (const method of Object.keys(METHODS) as Method[]) {\n const previous = target[method];\n saved[method] = previous;\n const level: Level = METHODS[method];\n target[method] = (...args: unknown[]) => {\n // A write path that itself uses console must not loop back into the logger.\n if (inside) return previous.apply(console, args);\n inside = true;\n try {\n if (args.some((arg) => isErrorLike(arg) && isLogged(arg)) || opts.skip?.(args)) return;\n let err: unknown;\n const parts: string[] = [];\n for (const arg of args) {\n if (isErrorLike(arg)) {\n err ??= arg;\n parts.push(arg.message);\n } else {\n parts.push(typeof arg === \"string\" ? arg : defaultRedactor.json(arg));\n }\n }\n log[level](parts.join(\" \"), { event: \"console\", console_method: method, err });\n } finally {\n inside = false;\n }\n };\n }\n\n return () => {\n for (const method of Object.keys(saved) as Method[]) target[method] = saved[method];\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAO,IAAM,SAAS,CAAC,SAAS,SAAS,QAAQ,QAAQ,SAAS,OAAO;AAGlE,IAAM,aAAoC;AAAA,EAC/C,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AACT;AAEA,IAAM,UAAiC,EAAE,SAAS,QAAQ,KAAK,SAAS,UAAU,SAAS,OAAO,QAAQ;AAEnG,SAAS,WAAW,OAAgB,WAAkB,QAAe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;AAEA,SAAO,MAAM;AACX,eAAW,UAAU,OAAO,KAAK,KAAK,EAAe,QAAO,MAAM,IAAI,MAAM,MAAM;AAAA,EACpF;AACF;","names":[]}
package/dist/next.cjs CHANGED
@@ -30,6 +30,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/next.ts
31
31
  var next_exports = {};
32
32
  __export(next_exports, {
33
+ nextConsoleSkip: () => nextConsoleSkip,
33
34
  nextControlStatus: () => nextControlStatus,
34
35
  nextOnRequestError: () => nextOnRequestError,
35
36
  registerNext: () => registerNext,
@@ -354,6 +355,9 @@ function withLogging(log, handler, opts = {}) {
354
355
  });
355
356
  };
356
357
  }
358
+ function nextConsoleSkip(args) {
359
+ return args.some((arg) => isErrorLike(arg) && typeof arg.digest === "string");
360
+ }
357
361
  function nextOnRequestError(log, opts = {}) {
358
362
  return async (err, request, context) => {
359
363
  if (isLogged(err) || nextControlStatus(err) !== void 0) return;
@@ -416,6 +420,7 @@ function withAction(log, name, action, opts = {}) {
416
420
  }
417
421
  // Annotate the CommonJS export names for ESM import in node:
418
422
  0 && (module.exports = {
423
+ nextConsoleSkip,
419
424
  nextControlStatus,
420
425
  nextOnRequestError,
421
426
  registerNext,
package/dist/next.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/next.ts","../src/context.ts","../src/global.ts","../src/redact.ts","../src/error.ts","../src/normalize.ts","../src/request-id.ts","../src/http.ts","../src/process.ts"],"sourcesContent":["import { runWithStore } from \"./context\";\nimport { isLogged, markLogged } from \"./error\";\nimport { logHttpRequest, requestContextFields, type HeaderSource, type HttpLogOptions } from \"./http\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\nimport { installProcessHandlers, logStartup } from \"./process\";\n\nexport interface WithLoggingOptions extends HttpLogOptions {\n /** Route template, e.g. \"/api/orders/[id]\". Left empty when not given. */\n route?: string;\n}\n\n/** Status for Next's control-flow errors (redirect(), notFound(), forbidden()...), else undefined. */\nexport function nextControlStatus(err: unknown): number | undefined {\n const digest = (err as { digest?: unknown } | null)?.digest;\n if (typeof digest !== \"string\") return undefined;\n if (digest.startsWith(\"NEXT_REDIRECT\")) {\n const status = Number(digest.split(\";\")[3]);\n return Number.isInteger(status) && status >= 300 ? status : 307;\n }\n if (digest === \"NEXT_NOT_FOUND\") return 404;\n if (digest.startsWith(\"NEXT_HTTP_ERROR_FALLBACK;\")) return Number(digest.split(\";\")[1]) || 404;\n return undefined;\n}\n\nfunction asError(value: unknown): unknown {\n if (typeof value === \"object\" && value !== null) return value;\n return Object.assign(new Error(String(value)), { name: \"NonErrorThrown\", thrown: value });\n}\n\nfunction trySetHeader(res: Response, name: string, value: string): void {\n try {\n res.headers.set(name, value);\n } catch {\n // Some responses (Response.redirect, proxied fetch responses) have immutable headers.\n }\n}\n\n/** Any App Router route handler: `()`, `(request)` or `(request, { params })`. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type RouteHandler = (...args: any[]) => Response | Promise<Response>;\n\n/**\n * Wraps an App Router route handler: request context + one http.request line. The returned\n * function has exactly the handler's parameters, so Next's route type checks still pass.\n */\nexport function withLogging<H extends RouteHandler>(\n log: Logger,\n handler: H,\n opts: WithLoggingOptions = {},\n): (...args: Parameters<H>) => Promise<Awaited<ReturnType<H>>> {\n return async (...args): Promise<Awaited<ReturnType<H>>> => {\n const request: unknown = args[0];\n // Next always passes the request; direct calls in unit tests may not.\n if (!(request instanceof Request)) return (await handler(...args)) as Awaited<ReturnType<H>>;\n const ctx = requestContextFields(request.headers);\n const path = new URL(request.url).pathname;\n const start = performance.now();\n return await runWithStore(ctx, async (store): Promise<Awaited<ReturnType<H>>> => {\n const summary = (status: number, err: unknown) =>\n logHttpRequest(\n log,\n {\n method: request.method,\n route: opts.route,\n path,\n status,\n duration_ms: performance.now() - start,\n err,\n fields: store.fields,\n },\n opts,\n );\n try {\n const res = (await handler(...args)) as Awaited<ReturnType<H>>;\n summary((res as Response).status, store.error);\n trySetHeader(res as Response, \"x-request-id\", ctx.request_id);\n return res;\n } catch (caught) {\n const control = nextControlStatus(caught);\n // Non-objects cannot be marked as logged, so onRequestError would log them again.\n const err = control === undefined ? asError(caught) : caught;\n summary(control ?? 500, control === undefined ? err : store.error);\n throw err;\n }\n });\n };\n}\n\nexport interface NextRequestInfo {\n path?: string;\n method?: string;\n headers?: Record<string, string | string[] | undefined>;\n}\n\nexport interface NextErrorContext {\n routerKind?: string;\n routePath?: string;\n routeType?: string;\n}\n\n/** `export const onRequestError = nextOnRequestError(log)` in instrumentation.ts. */\nexport function nextOnRequestError(log: Logger, opts: HttpLogOptions = {}) {\n return async (err: unknown, request: NextRequestInfo, context: NextErrorContext): Promise<void> => {\n if (isLogged(err) || nextControlStatus(err) !== undefined) return;\n const digest = (err as { digest?: unknown } | null)?.digest;\n logHttpRequest(\n log,\n {\n method: request?.method ?? \"GET\",\n route: context?.routePath,\n path: request?.path ?? \"\",\n status: 500,\n err,\n fields: {\n ...requestContextFields(request?.headers ?? {}),\n next_route_type: context?.routeType,\n next_router_kind: context?.routerKind,\n next_digest: typeof digest === \"string\" ? digest : undefined,\n },\n },\n opts,\n );\n };\n}\n\n/** Call from `register()` in instrumentation.ts. Does nothing on the edge runtime. */\nexport function registerNext(log: Logger, fields?: Fields): void {\n if (process.env.NEXT_RUNTIME && process.env.NEXT_RUNTIME !== \"nodejs\") return;\n // Next keeps serving after an unhandled rejection, so do not exit.\n installProcessHandlers(log, { exitOnCrash: false });\n logStartup(log, { port: process.env.PORT ? Number(process.env.PORT) : undefined, ...fields });\n}\n\nexport interface WithActionOptions {\n /** Request headers source. Defaults to `headers()` from next/headers. */\n headers?: () => HeaderSource | Promise<HeaderSource>;\n}\n\nasync function nextHeaders(): Promise<HeaderSource> {\n try {\n const mod = (await import(\"next/headers\")) as { headers: () => HeaderSource | Promise<HeaderSource> };\n return await mod.headers();\n } catch {\n // Called outside a request (tests, scripts) or Next is not installed.\n return {};\n }\n}\n\n/**\n * Wraps a server action: request context (request_id from x-request-id) plus one\n * `action.completed` / `action.failed` line. redirect()/notFound() count as completed.\n */\nexport function withAction<A extends unknown[], R>(\n log: Logger,\n name: string,\n action: (...args: A) => Promise<R>,\n opts: WithActionOptions = {},\n): (...args: A) => Promise<R> {\n return async (...args) => {\n const headers = await (opts.headers ?? nextHeaders)();\n const start = performance.now();\n return runWithStore({ ...requestContextFields(headers), action_name: name }, async (store) => {\n const fields = () => ({ ...store.fields, duration_ms: Math.round(performance.now() - start) });\n try {\n const result = await action(...args);\n log.info(\"server action completed\", { ...fields(), event: \"action.completed\", err: store.error });\n return result;\n } catch (caught) {\n const control = nextControlStatus(caught);\n if (control !== undefined) {\n log.info(\"server action completed\", { ...fields(), event: \"action.completed\", next_control_status: control });\n throw caught;\n }\n const err = asError(caught);\n log.error(\"server action failed\", { ...fields(), event: \"action.failed\", err });\n markLogged(err);\n throw err;\n }\n });\n };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { globalSingleton } from \"./global\";\nimport type { Fields } from \"./normalize\";\n\nexport interface ContextStore {\n fields: Fields;\n error?: unknown;\n /** Route template captured while the router still knew it (Express error path). */\n route?: string;\n parent?: ContextStore;\n}\n\nconst als = globalSingleton(\"als\", () => new AsyncLocalStorage<ContextStore>());\n\nexport const STORE_KEY: symbol = Symbol.for(\"@tanngo11/log.store\");\n\nexport function runWithStore<T>(fields: Fields, fn: (store: ContextStore) => T): T {\n const parent = als.getStore();\n const store: ContextStore = { fields: { ...parent?.fields, ...fields }, parent };\n return als.run(store, () => fn(store));\n}\n\nexport function withContext<T>(fields: Fields, fn: () => T): T {\n return runWithStore(fields, () => fn());\n}\n\nexport function currentStore(): ContextStore | undefined {\n return als.getStore();\n}\n\nexport function getContext(): Fields {\n return als.getStore()?.fields ?? {};\n}\n\n// Applies to the current context and every enclosing one, so a field added inside a nested\n// withContext/runJob still reaches the request's http.request line.\nexport function addContext(fields: Fields): void {\n for (let s = als.getStore(); s; s = s.parent) Object.assign(s.fields, fields);\n}\n\n// Sets the error on the store and on enclosing stores that have none yet.\nexport function recordErrorIn(store: ContextStore, err: unknown): void {\n store.error = err;\n for (let s = store.parent; s; s = s.parent) if (s.error === undefined) s.error = err;\n}\n\n// Marks the error that the current request/job summary line should carry. Does not write a line.\nexport function recordError(err: unknown): void {\n const store = als.getStore();\n if (store) recordErrorIn(store, err);\n}\n\nexport function attachStore(target: object, store: ContextStore): void {\n (target as Record<symbol, ContextStore>)[STORE_KEY] = store;\n}\n\nexport function storeOf(target: unknown): ContextStore | undefined {\n if (typeof target !== \"object\" || target === null) return undefined;\n return (target as Record<symbol, ContextStore | undefined>)[STORE_KEY];\n}\n","// Singletons shared by every copy of this package loaded in the process (ESM and CJS builds,\n// or duplicated installs), so context and dedupe state never split.\nexport function globalSingleton<T>(name: string, make: () => T): T {\n const key = Symbol.for(`@tanngo11/log.${name}`);\n const g = globalThis as unknown as Record<symbol, T | undefined>;\n let value = g[key];\n if (value === undefined) {\n value = make();\n g[key] = value;\n }\n return value;\n}\n","// Redaction shared by the logger and the error serializer. The collector redacts again,\n// but it cannot see secrets inside JSON-encoded strings, so the app side must catch them.\n\nexport const DEFAULT_REDACT_KEYS = [\n \"password\", \"passwd\", \"pwd\", \"passphrase\", \"secret\", \"client_secret\",\n \"token\", \"access_token\", \"refresh_token\", \"id_token\", \"auth_token\",\n \"api_key\", \"apikey\", \"access_key\", \"secret_key\", \"private_key\",\n \"authorization\", \"cookie\", \"set_cookie\", \"session_id\", \"sessionid\",\n \"credential\", \"credentials\", \"dsn\", \"connection_string\", \"conn_string\", \"jwt\", \"bearer\",\n];\n\n/** Opt-in value patterns for `redactValues`. Not on by default: they can hit ordinary numbers. */\nexport const REDACT_PATTERNS = {\n /** Vietnamese mobile numbers: 0912345678, +84912345678, 84912345678. */\n phoneVN: /(?<![\\d+])(?:\\+?84|0)[35789]\\d{8}(?!\\d)/g,\n /** Visa, Mastercard, Amex, Discover-like card numbers, with optional spaces or dashes. */\n paymentCard: /(?<!\\d)(?:4\\d{3}|5[1-5]\\d{2}|2[2-7]\\d{2}|3[47]\\d{2}|6(?:011|5\\d{2}))(?:[ -]?\\d{4}){2}[ -]?\\d{1,4}(?!\\d)/g,\n /** IPv4 addresses. */\n ipv4: /(?<![\\d.])(?:\\d{1,3}\\.){3}\\d{1,3}(?![\\d.])/g,\n} as const;\n\n// Keys that only describe a secret (count, type, timestamps, flags) stay readable.\nconst SAFE_SUFFIXES = [\"_count\", \"_type\", \"_length\", \"_expires_at\", \"_expires_in\", \"_ttl\", \"_at\", \"_ms\", \"_enabled\"];\n\nexport const REDACTED = \"[REDACTED]\";\n\nexport function toSnakeCase(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .toLowerCase();\n}\n\nconst URL_CREDENTIALS_RE = /([a-z][a-z0-9+.-]*:\\/\\/)[^\\s/@:\"']+:[^\\s/@\"']+@/gi;\nconst BEARER_RE = /\\bBearer\\s+[A-Za-z0-9._~+/=-]+/gi;\nconst JWT_RE = /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+/g;\nconst EMAIL_RE = /[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,})/g;\n\nexport type KeyPattern = string | RegExp;\n\nexport interface RedactorOptions {\n /** Extra sensitive keys: names (matched like the defaults) or patterns tested on the snake_case key. */\n keys?: readonly KeyPattern[];\n /** Extra value patterns; every match inside any string becomes [REDACTED]. */\n values?: readonly RegExp[];\n}\n\nexport interface Redactor {\n isSensitive(key: string): boolean;\n /** Masks secrets and emails that appear inside free text. */\n scrub(s: string): string;\n /** JSON.stringify that redacts sensitive keys at any depth and never throws. */\n json(value: unknown): string;\n}\n\nfunction globalize(re: RegExp): RegExp {\n return re.flags.includes(\"g\") ? new RegExp(re.source, re.flags) : new RegExp(re.source, `${re.flags}g`);\n}\n\nexport function createRedactor(opts: RedactorOptions = {}): Redactor {\n const words = [...DEFAULT_REDACT_KEYS];\n const keyPatterns: RegExp[] = [];\n for (const k of opts.keys ?? []) {\n if (typeof k === \"string\") words.push(toSnakeCase(k));\n else keyPatterns.push(new RegExp(k.source, k.flags.replace(\"g\", \"\")));\n }\n const valuePatterns = (opts.values ?? []).map(globalize);\n\n const isSensitive = (key: string): boolean => {\n const k = toSnakeCase(key);\n if (keyPatterns.some((re) => re.test(k))) return true;\n if (!words.includes(k) && SAFE_SUFFIXES.some((s) => k.endsWith(s))) return false;\n return words.some((w) => k === w || k.startsWith(`${w}_`) || k.endsWith(`_${w}`) || k.includes(`_${w}_`));\n };\n\n const scrub = (s: string): string => {\n let out = s\n .replace(URL_CREDENTIALS_RE, `$1${REDACTED}@`)\n .replace(BEARER_RE, `Bearer ${REDACTED}`)\n .replace(JWT_RE, \"[REDACTED_JWT]\")\n .replace(EMAIL_RE, \"***@$1\");\n for (const re of valuePatterns) out = out.replace(re, REDACTED);\n return out;\n };\n\n const json = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n const text = JSON.stringify(value, (key, val: unknown) => {\n if (key && val !== null && val !== undefined && isSensitive(key)) return REDACTED;\n if (typeof val === \"bigint\") return val.toString();\n if (val instanceof Error) return { name: val.name, message: val.message };\n return val;\n });\n return text ?? String(value);\n } catch {\n return String(value);\n }\n };\n\n return { isSensitive, scrub, json };\n}\n\nexport const defaultRedactor: Redactor = createRedactor();\n","import { globalSingleton } from \"./global\";\nimport { defaultRedactor } from \"./redact\";\n\nexport interface ErrFields {\n err_type?: string;\n err_message?: string;\n err_code?: string;\n err_stack?: string;\n err_cause?: string;\n}\n\nconst MAX_CAUSE_DEPTH = 5;\n\nexport function isErrorLike(v: unknown): v is Error {\n if (v instanceof Error) return true;\n return (\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as { message?: unknown }).message === \"string\" &&\n (\"stack\" in v || \"name\" in v)\n );\n}\n\nfunction errorType(e: Error): string {\n if (e.name && e.name !== \"Error\") return e.name;\n const ctor = (e as { constructor?: { name?: string } }).constructor?.name;\n return ctor && ctor !== \"Object\" ? ctor : \"Error\";\n}\n\nexport function serializeError(err: unknown): ErrFields {\n if (!isErrorLike(err)) {\n if (typeof err === \"string\") return { err_type: \"string\", err_message: err };\n return { err_type: typeof err, err_message: defaultRedactor.json(err) };\n }\n const e = err as Error & { code?: unknown; cause?: unknown };\n const out: ErrFields = { err_type: errorType(e), err_message: String(e.message ?? \"\") };\n if (e.code !== undefined && e.code !== null) out.err_code = String(e.code);\n if (typeof e.stack === \"string\") out.err_stack = e.stack;\n\n const causes: string[] = [];\n let cause = e.cause;\n while (cause !== undefined && cause !== null && causes.length < MAX_CAUSE_DEPTH) {\n if (isErrorLike(cause)) {\n causes.push(`${errorType(cause)}: ${cause.message}`);\n cause = (cause as { cause?: unknown }).cause;\n } else {\n causes.push(defaultRedactor.json(cause));\n cause = undefined;\n }\n }\n if (causes.length > 0) out.err_cause = causes.join(\" <- \");\n return out;\n}\n\nconst logged = globalSingleton(\"logged\", () => new WeakSet<object>());\n\n// Marks an error as already written, so a later boundary (e.g. Next's onRequestError)\n// does not log it a second time.\nexport function markLogged(err: unknown): void {\n if (typeof err === \"object\" && err !== null) logged.add(err);\n}\n\nexport function isLogged(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && logged.has(err);\n}\n","import { isErrorLike, serializeError } from \"./error\";\nimport type { Level } from \"./levels\";\nimport { REDACTED, toSnakeCase, type Redactor } from \"./redact\";\n\nexport { DEFAULT_REDACT_KEYS, toSnakeCase } from \"./redact\";\n\n/** Final per-field hook: return a replacement, or undefined to drop the field. */\nexport type RedactHook = (key: string, value: Primitive) => unknown;\n\nexport type Fields = Record<string, unknown>;\nexport type Primitive = string | number | boolean | null;\nexport type LogRecord = Record<string, Primitive>;\n\nexport interface NormalizeOptions {\n snakeCase: boolean;\n redactor: Redactor;\n hook?: RedactHook;\n}\n\n// Fields the redact hook never sees, so every line keeps its level, message and event.\nconst HOOK_EXEMPT = new Set([\"level\", \"message\", \"event\"]);\n\n// Keys owned by Vector (overwritten or deleted on ingest) or by the logger itself.\nexport const RESERVED_KEYS = new Set([\n \"project\", \"service\", \"vps\", \"version\", \"container_name\", \"container_id\", \"image\", \"stream\",\n \"_timestamp\", \"label\", \"host\", \"source_type\", \"msg\", \"lvl\", \"severity\", \"level\", \"message\",\n]);\n\nexport const MAX_LINE_BYTES = 16000;\nconst MAX_MESSAGE = 500;\nconst MAX_STACK = 4000;\nconst MAX_STRING = 1000;\nconst MAX_DEPTH = 3;\nconst TRUNCATED = \"…[truncated]\";\n\n// Fields kept when a line is too large.\nconst KEEP_ON_SHRINK = new Set([\n \"level\", \"message\", \"event\", \"request_id\", \"trace_id\", \"span_id\", \"job_name\", \"job_id\", \"job_attempt\",\n \"user_id\", \"tenant_id\", \"err_type\", \"err_message\", \"err_code\",\n]);\n\nexport function stripUrl(url: string): string {\n const noQuery = url.split(/[?#]/, 1)[0] ?? \"\";\n return noQuery.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/@\\s]*@/i, \"$1\");\n}\n\nexport function truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max - TRUNCATED.length) + TRUNCATED : s;\n}\n\nfunction isPlainObject(v: unknown): v is Fields {\n if (typeof v !== \"object\" || v === null) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction isUrlKey(key: string): boolean {\n return key === \"http_path\" || key === \"http_url\" || key.endsWith(\"_url\");\n}\n\nfunction flattenInto(out: LogRecord, prefix: string, obj: Fields, depth: number, opts: NormalizeOptions): void {\n for (const [rawKey, value] of Object.entries(obj)) {\n const key = opts.snakeCase ? toSnakeCase(rawKey) : rawKey;\n const full = prefix ? `${prefix}_${key}` : key;\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") continue;\n if (value !== null && (opts.redactor.isSensitive(rawKey) || opts.redactor.isSensitive(full))) {\n out[full] = REDACTED;\n continue;\n }\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n out[full] = value;\n } else if (typeof value === \"number\") {\n out[full] = Number.isFinite(value) ? value : String(value);\n } else if (typeof value === \"bigint\") {\n out[full] = value.toString();\n } else if (value instanceof Date) {\n out[full] = Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n } else if (isErrorLike(value)) {\n out[full] = `${value.name}: ${value.message}`;\n } else if (isPlainObject(value) && depth < MAX_DEPTH - 1) {\n flattenInto(out, full, value, depth + 1, opts);\n } else {\n // Arrays, deep objects, class instances: stringified with sensitive keys redacted.\n out[full] = opts.redactor.json(value);\n }\n }\n}\n\nfunction finalize(key: string, value: Primitive, opts: NormalizeOptions): Primitive {\n if (typeof value !== \"string\") return value;\n const v = opts.redactor.scrub(isUrlKey(key) ? stripUrl(value) : value);\n return truncate(v, key === \"err_stack\" ? MAX_STACK : MAX_STRING);\n}\n\nexport function buildRecord(\n level: Level,\n message: unknown,\n sources: (Fields | undefined)[],\n opts: NormalizeOptions,\n): LogRecord {\n const merged: Fields = {};\n for (const source of sources) if (source) Object.assign(merged, source);\n\n let err: unknown;\n if (merged.err !== undefined && merged.err !== null) {\n err = merged.err;\n delete merged.err;\n } else if (isErrorLike(merged.error)) {\n err = merged.error;\n delete merged.error;\n }\n\n const flat: LogRecord = {};\n flattenInto(flat, \"\", merged, 0, opts);\n if (err !== undefined) Object.assign(flat, serializeError(err));\n\n const text = typeof message === \"string\" ? message : opts.redactor.json(message);\n const out: LogRecord = { level, message: truncate(opts.redactor.scrub(text), MAX_MESSAGE) };\n for (const [k, v] of Object.entries(flat)) {\n const key = RESERVED_KEYS.has(k) ? `app_${k}` : k;\n let value = finalize(key, v, opts);\n if (opts.hook && !HOOK_EXEMPT.has(key)) {\n const replaced = opts.hook(key, value);\n if (replaced === undefined) continue;\n value = typeof replaced === \"object\" && replaced !== null ? opts.redactor.json(replaced) : (replaced as Primitive);\n }\n out[key] = value;\n }\n return out;\n}\n\nfunction byteLength(s: string): number {\n // UTF-8 uses at most 3 bytes per UTF-16 code unit: skip encoding short lines.\n if (s.length * 3 <= MAX_LINE_BYTES) return s.length;\n return new TextEncoder().encode(s).length;\n}\n\nexport function serializeRecord(record: LogRecord): string {\n const line = JSON.stringify(record);\n if (byteLength(line) <= MAX_LINE_BYTES) return line;\n const small: LogRecord = {};\n for (const [k, v] of Object.entries(record)) {\n if (KEEP_ON_SHRINK.has(k) || k.startsWith(\"http_\")) small[k] = v;\n }\n small.log_truncated = true;\n return JSON.stringify(small);\n}\n","// No imports: this module is shared with the edge entry (next-edge).\nexport const REQUEST_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\nexport function newRequestId(): string {\n return globalThis.crypto.randomUUID();\n}\n\nfunction first(header?: string | string[] | null): string | undefined {\n return Array.isArray(header) ? header[0] : (header ?? undefined);\n}\n\nexport function resolveRequestId(header?: string | string[] | null): string {\n const value = first(header);\n return value && REQUEST_ID_RE.test(value) ? value : newRequestId();\n}\n\nexport function parseTraceparent(header?: string | string[] | null): { trace_id: string; span_id: string } | undefined {\n const value = first(header)?.trim().toLowerCase();\n const m = value ? TRACEPARENT_RE.exec(value) : null;\n if (!m) return undefined;\n const [, version, traceId, spanId] = m as unknown as [string, string, string, string];\n if (version === \"ff\" || /^0+$/.test(traceId) || /^0+$/.test(spanId)) return undefined;\n return { trace_id: traceId, span_id: spanId };\n}\n","import { getContext } from \"./context\";\nimport { markLogged, serializeError } from \"./error\";\nimport type { Logger } from \"./logger\";\nimport { stripUrl, type Fields } from \"./normalize\";\nimport { parseTraceparent, resolveRequestId } from \"./request-id\";\n\nexport { newRequestId, parseTraceparent, REQUEST_ID_RE, resolveRequestId } from \"./request-id\";\n\nexport type HeaderSource = Headers | Record<string, string | string[] | undefined>;\n\nfunction header(headers: HeaderSource, name: string): string | string[] | undefined {\n if (typeof (headers as Headers).get === \"function\") return (headers as Headers).get(name) ?? undefined;\n return (headers as Record<string, string | string[] | undefined>)[name];\n}\n\nexport function requestContextFields(headers: HeaderSource): { request_id: string; trace_id?: string; span_id?: string } {\n const out: { request_id: string; trace_id?: string; span_id?: string } = {\n request_id: resolveRequestId(header(headers, \"x-request-id\")),\n };\n const tp = parseTraceparent(header(headers, \"traceparent\"));\n if (tp) Object.assign(out, tp);\n return out;\n}\n\n// Headers to forward to services we own, so their logs share request_id / trace_id.\nexport function propagationHeaders(): Record<string, string> {\n const ctx = getContext();\n const out: Record<string, string> = {};\n if (typeof ctx.request_id === \"string\") out[\"x-request-id\"] = ctx.request_id;\n if (typeof ctx.trace_id === \"string\" && typeof ctx.span_id === \"string\") {\n out.traceparent = `00-${ctx.trace_id}-${ctx.span_id}-01`;\n }\n return out;\n}\n\nexport const DEFAULT_SKIP_PATHS: (string | RegExp)[] = [\n /^\\/(health|healthz|ready|readyz|livez)\\/?$/,\n \"/favicon.ico\",\n /^\\/_next\\/static\\//,\n];\n\nexport interface HttpLogOptions {\n skipPaths?: (string | RegExp)[];\n}\n\nexport interface HttpRequestInfo {\n method: string;\n route?: string;\n path: string;\n status: number;\n duration_ms?: number;\n err?: unknown;\n fields?: Fields;\n}\n\nexport function shouldSkip(method: string, path: string, skipPaths: (string | RegExp)[] = DEFAULT_SKIP_PATHS): boolean {\n if (method.toUpperCase() === \"OPTIONS\") return true;\n const p = stripUrl(path);\n return skipPaths.some((s) => (typeof s === \"string\" ? p === s : s.test(p)));\n}\n\n// Writes the one `http.request` summary line for an inbound request.\nexport function logHttpRequest(log: Logger, info: HttpRequestInfo, opts: HttpLogOptions = {}): void {\n if (shouldSkip(info.method, info.path, opts.skipPaths)) return;\n const level = info.status >= 500 ? \"error\" : info.status >= 400 ? \"warn\" : \"info\";\n const path = stripUrl(info.path);\n const errFields: Fields = {};\n if (info.err !== undefined && info.err !== null) {\n Object.assign(errFields, serializeError(info.err));\n if (info.status < 500) delete errFields.err_stack;\n markLogged(info.err);\n }\n // Route templates keep the message bounded; the raw path would make one message per URL.\n const message = info.route ? `${info.method} ${info.route} ${info.status}` : `${info.method} ${info.status}`;\n log[level](message, {\n ...info.fields,\n event: \"http.request\",\n http_method: info.method,\n http_route: info.route,\n http_path: path,\n http_status: info.status,\n duration_ms: info.duration_ms === undefined ? undefined : Math.round(info.duration_ms),\n ...errFields,\n });\n}\n","import { globalSingleton } from \"./global\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\nexport function logStartup(log: Logger, fields: Fields = {}): void {\n log.info(\"app started\", {\n event: \"app.started\",\n runtime_version: `node ${process.versions.node}`,\n log_level: log.level,\n ...fields,\n });\n}\n\n/** Call at the start of your own shutdown handler (e.g. on SIGTERM). The library never handles signals. */\nexport function logShutdown(log: Logger, fields: Fields = {}): void {\n log.info(\"app stopping\", { event: \"app.stopping\", ...fields });\n}\n\nexport interface ProcessHandlerOptions {\n /** Exit with code 1 after an uncaught error. Next.js keeps serving, so its adapter passes false. */\n exitOnCrash?: boolean;\n /** Time other crash handlers (Sentry, APM) get to flush before exit. Default 1000 ms. */\n exitDelayMs?: number;\n exit?: (code: number) => void;\n}\n\nexport function crashHandlers(log: Logger, opts: ProcessHandlerOptions = {}) {\n const exitOnCrash = opts.exitOnCrash ?? true;\n const exitDelayMs = opts.exitDelayMs ?? 1000;\n const exit = opts.exit ?? ((code: number) => process.exit(code));\n let exiting = false;\n const crash = (source: string, err: unknown) => {\n if (!exitOnCrash) {\n log.error(\"unhandled error\", { event: \"app.unhandled_error\", crash_source: source, err });\n return;\n }\n log.fatal(\"app crashed\", { event: \"app.crashed\", crash_source: source, err });\n if (exiting) return;\n exiting = true;\n if (typeof process !== \"undefined\") process.exitCode = 1;\n // Deferred so listeners registered after ours still run; unref so a process with nothing\n // left to do exits on its own (with exitCode 1) without waiting.\n const timer = setTimeout(() => exit(1), exitDelayMs);\n (timer as { unref?: () => void }).unref?.();\n };\n return {\n onUncaught: (err: unknown) => crash(\"uncaughtException\", err),\n onRejection: (reason: unknown) => crash(\"unhandledRejection\", reason),\n };\n}\n\nconst state = globalSingleton(\"process\", () => ({ installed: false }));\n\n/** Logs uncaught exceptions and unhandled rejections. Does not touch SIGTERM/SIGINT. */\nexport function installProcessHandlers(log: Logger, opts: ProcessHandlerOptions = {}): void {\n if (state.installed || typeof process === \"undefined\" || typeof process.on !== \"function\") return;\n state.installed = true;\n const h = crashHandlers(log, opts);\n process.on(\"uncaughtException\", h.onUncaught);\n process.on(\"unhandledRejection\", h.onRejection);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,8BAAkC;;;ACE3B,SAAS,gBAAmB,MAAc,MAAkB;AACjE,QAAM,MAAM,uBAAO,IAAI,iBAAiB,IAAI,EAAE;AAC9C,QAAM,IAAI;AACV,MAAI,QAAQ,EAAE,GAAG;AACjB,MAAI,UAAU,QAAW;AACvB,YAAQ,KAAK;AACb,MAAE,GAAG,IAAI;AAAA,EACX;AACA,SAAO;AACT;;;ADCA,IAAM,MAAM,gBAAgB,OAAO,MAAM,IAAI,0CAAgC,CAAC;AAIvE,SAAS,aAAgB,QAAgB,IAAmC;AACjF,QAAM,SAAS,IAAI,SAAS;AAC5B,QAAM,QAAsB,EAAE,QAAQ,EAAE,GAAG,QAAQ,QAAQ,GAAG,OAAO,GAAG,OAAO;AAC/E,SAAO,IAAI,IAAI,OAAO,MAAM,GAAG,KAAK,CAAC;AACvC;;;AEjBO,IAAM,sBAAsB;AAAA,EACjC;AAAA,EAAY;AAAA,EAAU;AAAA,EAAO;AAAA,EAAc;AAAA,EAAU;AAAA,EACrD;AAAA,EAAS;AAAA,EAAgB;AAAA,EAAiB;AAAA,EAAY;AAAA,EACtD;AAAA,EAAW;AAAA,EAAU;AAAA,EAAc;AAAA,EAAc;AAAA,EACjD;AAAA,EAAiB;AAA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qB,OAAO,GAAG,aAAa,KAAK,GAAG,OAAO,UAAU;AAC5F,YAAM,SAAS,OAAO,EAAE,GAAG,MAAM,QAAQ,aAAa,KAAK,MAAM,YAAY,IAAI,IAAI,KAAK,EAAE;AAC5F,UAAI;AACF,cAAM,SAAS,MAAM,OAAO,GAAG,IAAI;AACnC,YAAI,KAAK,2BAA2B,EAAE,GAAG,OAAO,GAAG,OAAO,oBAAoB,KAAK,MAAM,MAAM,CAAC;AAChG,eAAO;AAAA,MACT,SAAS,QAAQ;AACf,cAAM,UAAU,kBAAkB,MAAM;AACxC,YAAI,YAAY,QAAW;AACzB,cAAI,KAAK,2BAA2B,EAAE,GAAG,OAAO,GAAG,OAAO,oBAAoB,qBAAqB,QAAQ,CAAC;AAC5G,gBAAM;AAAA,QACR;AACA,cAAM,MAAM,QAAQ,MAAM;AAC1B,YAAI,MAAM,wBAAwB,EAAE,GAAG,OAAO,GAAG,OAAO,iBAAiB,IAAI,CAAC;AAC9E,mBAAW,GAAG;AACd,cAAM;AAAA,MACR;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":["header"]}
1
+ {"version":3,"sources":["../src/next.ts","../src/context.ts","../src/global.ts","../src/redact.ts","../src/error.ts","../src/normalize.ts","../src/request-id.ts","../src/http.ts","../src/process.ts"],"sourcesContent":["import { runWithStore } from \"./context\";\nimport { isErrorLike, isLogged, markLogged } from \"./error\";\nimport { logHttpRequest, requestContextFields, type HeaderSource, type HttpLogOptions } from \"./http\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\nimport { installProcessHandlers, logStartup } from \"./process\";\n\nexport interface WithLoggingOptions extends HttpLogOptions {\n /** Route template, e.g. \"/api/orders/[id]\". Left empty when not given. */\n route?: string;\n}\n\n/** Status for Next's control-flow errors (redirect(), notFound(), forbidden()...), else undefined. */\nexport function nextControlStatus(err: unknown): number | undefined {\n const digest = (err as { digest?: unknown } | null)?.digest;\n if (typeof digest !== \"string\") return undefined;\n if (digest.startsWith(\"NEXT_REDIRECT\")) {\n const status = Number(digest.split(\";\")[3]);\n return Number.isInteger(status) && status >= 300 ? status : 307;\n }\n if (digest === \"NEXT_NOT_FOUND\") return 404;\n if (digest.startsWith(\"NEXT_HTTP_ERROR_FALLBACK;\")) return Number(digest.split(\";\")[1]) || 404;\n return undefined;\n}\n\nfunction asError(value: unknown): unknown {\n if (typeof value === \"object\" && value !== null) return value;\n return Object.assign(new Error(String(value)), { name: \"NonErrorThrown\", thrown: value });\n}\n\nfunction trySetHeader(res: Response, name: string, value: string): void {\n try {\n res.headers.set(name, value);\n } catch {\n // Some responses (Response.redirect, proxied fetch responses) have immutable headers.\n }\n}\n\n/** Any App Router route handler: `()`, `(request)` or `(request, { params })`. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type RouteHandler = (...args: any[]) => Response | Promise<Response>;\n\n/**\n * Wraps an App Router route handler: request context + one http.request line. The returned\n * function has exactly the handler's parameters, so Next's route type checks still pass.\n */\nexport function withLogging<H extends RouteHandler>(\n log: Logger,\n handler: H,\n opts: WithLoggingOptions = {},\n): (...args: Parameters<H>) => Promise<Awaited<ReturnType<H>>> {\n return async (...args): Promise<Awaited<ReturnType<H>>> => {\n const request: unknown = args[0];\n // Next always passes the request; direct calls in unit tests may not.\n if (!(request instanceof Request)) return (await handler(...args)) as Awaited<ReturnType<H>>;\n const ctx = requestContextFields(request.headers);\n const path = new URL(request.url).pathname;\n const start = performance.now();\n return await runWithStore(ctx, async (store): Promise<Awaited<ReturnType<H>>> => {\n const summary = (status: number, err: unknown) =>\n logHttpRequest(\n log,\n {\n method: request.method,\n route: opts.route,\n path,\n status,\n duration_ms: performance.now() - start,\n err,\n fields: store.fields,\n },\n opts,\n );\n try {\n const res = (await handler(...args)) as Awaited<ReturnType<H>>;\n summary((res as Response).status, store.error);\n trySetHeader(res as Response, \"x-request-id\", ctx.request_id);\n return res;\n } catch (caught) {\n const control = nextControlStatus(caught);\n // Non-objects cannot be marked as logged, so onRequestError would log them again.\n const err = control === undefined ? asError(caught) : caught;\n summary(control ?? 500, control === undefined ? err : store.error);\n throw err;\n }\n });\n };\n}\n\n/**\n * patchConsole skip predicate for Next.js: Next prints a render error with console.error right\n * before calling onRequestError, by then the error carries a digest. Dropping that console\n * call leaves the single, richer onRequestError line.\n */\nexport function nextConsoleSkip(args: unknown[]): boolean {\n return args.some((arg) => isErrorLike(arg) && typeof (arg as { digest?: unknown }).digest === \"string\");\n}\n\nexport interface NextRequestInfo {\n path?: string;\n method?: string;\n headers?: Record<string, string | string[] | undefined>;\n}\n\nexport interface NextErrorContext {\n routerKind?: string;\n routePath?: string;\n routeType?: string;\n}\n\n/** `export const onRequestError = nextOnRequestError(log)` in instrumentation.ts. */\nexport function nextOnRequestError(log: Logger, opts: HttpLogOptions = {}) {\n return async (err: unknown, request: NextRequestInfo, context: NextErrorContext): Promise<void> => {\n if (isLogged(err) || nextControlStatus(err) !== undefined) return;\n const digest = (err as { digest?: unknown } | null)?.digest;\n logHttpRequest(\n log,\n {\n method: request?.method ?? \"GET\",\n route: context?.routePath,\n path: request?.path ?? \"\",\n status: 500,\n err,\n fields: {\n ...requestContextFields(request?.headers ?? {}),\n next_route_type: context?.routeType,\n next_router_kind: context?.routerKind,\n next_digest: typeof digest === \"string\" ? digest : undefined,\n },\n },\n opts,\n );\n };\n}\n\n/** Call from `register()` in instrumentation.ts. Does nothing on the edge runtime. */\nexport function registerNext(log: Logger, fields?: Fields): void {\n if (process.env.NEXT_RUNTIME && process.env.NEXT_RUNTIME !== \"nodejs\") return;\n // Next keeps serving after an unhandled rejection, so do not exit.\n installProcessHandlers(log, { exitOnCrash: false });\n logStartup(log, { port: process.env.PORT ? Number(process.env.PORT) : undefined, ...fields });\n}\n\nexport interface WithActionOptions {\n /** Request headers source. Defaults to `headers()` from next/headers. */\n headers?: () => HeaderSource | Promise<HeaderSource>;\n}\n\nasync function nextHeaders(): Promise<HeaderSource> {\n try {\n const mod = (await import(\"next/headers\")) as { headers: () => HeaderSource | Promise<HeaderSource> };\n return await mod.headers();\n } catch {\n // Called outside a request (tests, scripts) or Next is not installed.\n return {};\n }\n}\n\n/**\n * Wraps a server action: request context (request_id from x-request-id) plus one\n * `action.completed` / `action.failed` line. redirect()/notFound() count as completed.\n */\nexport function withAction<A extends unknown[], R>(\n log: Logger,\n name: string,\n action: (...args: A) => Promise<R>,\n opts: WithActionOptions = {},\n): (...args: A) => Promise<R> {\n return async (...args) => {\n const headers = await (opts.headers ?? nextHeaders)();\n const start = performance.now();\n return runWithStore({ ...requestContextFields(headers), action_name: name }, async (store) => {\n const fields = () => ({ ...store.fields, duration_ms: Math.round(performance.now() - start) });\n try {\n const result = await action(...args);\n log.info(\"server action completed\", { ...fields(), event: \"action.completed\", err: store.error });\n return result;\n } catch (caught) {\n const control = nextControlStatus(caught);\n if (control !== undefined) {\n log.info(\"server action completed\", { ...fields(), event: \"action.completed\", next_control_status: control });\n throw caught;\n }\n const err = asError(caught);\n log.error(\"server action failed\", { ...fields(), event: \"action.failed\", err });\n markLogged(err);\n throw err;\n }\n });\n };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { globalSingleton } from \"./global\";\nimport type { Fields } from \"./normalize\";\n\nexport interface ContextStore {\n fields: Fields;\n error?: unknown;\n /** Route template captured while the router still knew it (Express error path). */\n route?: string;\n parent?: ContextStore;\n}\n\nconst als = globalSingleton(\"als\", () => new AsyncLocalStorage<ContextStore>());\n\nexport const STORE_KEY: symbol = Symbol.for(\"@tanngo11/log.store\");\n\nexport function runWithStore<T>(fields: Fields, fn: (store: ContextStore) => T): T {\n const parent = als.getStore();\n const store: ContextStore = { fields: { ...parent?.fields, ...fields }, parent };\n return als.run(store, () => fn(store));\n}\n\nexport function withContext<T>(fields: Fields, fn: () => T): T {\n return runWithStore(fields, () => fn());\n}\n\nexport function currentStore(): ContextStore | undefined {\n return als.getStore();\n}\n\nexport function getContext(): Fields {\n return als.getStore()?.fields ?? {};\n}\n\n// Applies to the current context and every enclosing one, so a field added inside a nested\n// withContext/runJob still reaches the request's http.request line.\nexport function addContext(fields: Fields): void {\n for (let s = als.getStore(); s; s = s.parent) Object.assign(s.fields, fields);\n}\n\n// Sets the error on the store and on enclosing stores that have none yet.\nexport function recordErrorIn(store: ContextStore, err: unknown): void {\n store.error = err;\n for (let s = store.parent; s; s = s.parent) if (s.error === undefined) s.error = err;\n}\n\n// Marks the error that the current request/job summary line should carry. Does not write a line.\nexport function recordError(err: unknown): void {\n const store = als.getStore();\n if (store) recordErrorIn(store, err);\n}\n\nexport function attachStore(target: object, store: ContextStore): void {\n (target as Record<symbol, ContextStore>)[STORE_KEY] = store;\n}\n\nexport function storeOf(target: unknown): ContextStore | undefined {\n if (typeof target !== \"object\" || target === null) return undefined;\n return (target as Record<symbol, ContextStore | undefined>)[STORE_KEY];\n}\n","// Singletons shared by every copy of this package loaded in the process (ESM and CJS builds,\n// or duplicated installs), so context and dedupe state never split.\nexport function globalSingleton<T>(name: string, make: () => T): T {\n const key = Symbol.for(`@tanngo11/log.${name}`);\n const g = globalThis as unknown as Record<symbol, T | undefined>;\n let value = g[key];\n if (value === undefined) {\n value = make();\n g[key] = value;\n }\n return value;\n}\n","// Redaction shared by the logger and the error serializer. The collector redacts again,\n// but it cannot see secrets inside JSON-encoded strings, so the app side must catch them.\n\nexport const DEFAULT_REDACT_KEYS = [\n \"password\", \"passwd\", \"pwd\", \"passphrase\", \"secret\", \"client_secret\",\n \"token\", \"access_token\", \"refresh_token\", \"id_token\", \"auth_token\",\n \"api_key\", \"apikey\", \"access_key\", \"secret_key\", \"private_key\",\n \"authorization\", \"cookie\", \"set_cookie\", \"session_id\", \"sessionid\",\n \"credential\", \"credentials\", \"dsn\", \"connection_string\", \"conn_string\", \"jwt\", \"bearer\",\n];\n\n/** Opt-in value patterns for `redactValues`. Not on by default: they can hit ordinary numbers. */\nexport const REDACT_PATTERNS = {\n /** Vietnamese mobile numbers: 0912345678, +84912345678, 84912345678. */\n phoneVN: /(?<![\\d+])(?:\\+?84|0)[35789]\\d{8}(?!\\d)/g,\n /** Visa, Mastercard, Amex, Discover-like card numbers, with optional spaces or dashes. */\n paymentCard: /(?<!\\d)(?:4\\d{3}|5[1-5]\\d{2}|2[2-7]\\d{2}|3[47]\\d{2}|6(?:011|5\\d{2}))(?:[ -]?\\d{4}){2}[ -]?\\d{1,4}(?!\\d)/g,\n /** IPv4 addresses. */\n ipv4: /(?<![\\d.])(?:\\d{1,3}\\.){3}\\d{1,3}(?![\\d.])/g,\n} as const;\n\n// Keys that only describe a secret (count, type, timestamps, flags) stay readable.\nconst SAFE_SUFFIXES = [\"_count\", \"_type\", \"_length\", \"_expires_at\", \"_expires_in\", \"_ttl\", \"_at\", \"_ms\", \"_enabled\"];\n\nexport const REDACTED = \"[REDACTED]\";\n\nexport function toSnakeCase(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .toLowerCase();\n}\n\nconst URL_CREDENTIALS_RE = /([a-z][a-z0-9+.-]*:\\/\\/)[^\\s/@:\"']+:[^\\s/@\"']+@/gi;\nconst BEARER_RE = /\\bBearer\\s+[A-Za-z0-9._~+/=-]+/gi;\nconst JWT_RE = /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+/g;\nconst EMAIL_RE = /[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,})/g;\n\nexport type KeyPattern = string | RegExp;\n\nexport interface RedactorOptions {\n /** Extra sensitive keys: names (matched like the defaults) or patterns tested on the snake_case key. */\n keys?: readonly KeyPattern[];\n /** Extra value patterns; every match inside any string becomes [REDACTED]. */\n values?: readonly RegExp[];\n}\n\nexport interface Redactor {\n isSensitive(key: string): boolean;\n /** Masks secrets and emails that appear inside free text. */\n scrub(s: string): string;\n /** JSON.stringify that redacts sensitive keys at any depth and never throws. */\n json(value: unknown): string;\n}\n\nfunction globalize(re: RegExp): RegExp {\n return re.flags.includes(\"g\") ? new RegExp(re.source, re.flags) : new RegExp(re.source, `${re.flags}g`);\n}\n\nexport function createRedactor(opts: RedactorOptions = {}): Redactor {\n const words = [...DEFAULT_REDACT_KEYS];\n const keyPatterns: RegExp[] = [];\n for (const k of opts.keys ?? []) {\n if (typeof k === \"string\") words.push(toSnakeCase(k));\n else keyPatterns.push(new RegExp(k.source, k.flags.replace(\"g\", \"\")));\n }\n const valuePatterns = (opts.values ?? []).map(globalize);\n\n const isSensitive = (key: string): boolean => {\n const k = toSnakeCase(key);\n if (keyPatterns.some((re) => re.test(k))) return true;\n if (!words.includes(k) && SAFE_SUFFIXES.some((s) => k.endsWith(s))) return false;\n return words.some((w) => k === w || k.startsWith(`${w}_`) || k.endsWith(`_${w}`) || k.includes(`_${w}_`));\n };\n\n const scrub = (s: string): string => {\n let out = s\n .replace(URL_CREDENTIALS_RE, `$1${REDACTED}@`)\n .replace(BEARER_RE, `Bearer ${REDACTED}`)\n .replace(JWT_RE, \"[REDACTED_JWT]\")\n .replace(EMAIL_RE, \"***@$1\");\n for (const re of valuePatterns) out = out.replace(re, REDACTED);\n return out;\n };\n\n const json = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n const text = JSON.stringify(value, (key, val: unknown) => {\n if (key && val !== null && val !== undefined && isSensitive(key)) return REDACTED;\n if (typeof val === \"bigint\") return val.toString();\n if (val instanceof Error) return { name: val.name, message: val.message };\n return val;\n });\n return text ?? String(value);\n } catch {\n return String(value);\n }\n };\n\n return { isSensitive, scrub, json };\n}\n\nexport const defaultRedactor: Redactor = createRedactor();\n","import { globalSingleton } from \"./global\";\nimport { defaultRedactor } from \"./redact\";\n\nexport interface ErrFields {\n err_type?: string;\n err_message?: string;\n err_code?: string;\n err_stack?: string;\n err_cause?: string;\n}\n\nconst MAX_CAUSE_DEPTH = 5;\n\nexport function isErrorLike(v: unknown): v is Error {\n if (v instanceof Error) return true;\n return (\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as { message?: unknown }).message === \"string\" &&\n (\"stack\" in v || \"name\" in v)\n );\n}\n\nfunction errorType(e: Error): string {\n if (e.name && e.name !== \"Error\") return e.name;\n const ctor = (e as { constructor?: { name?: string } }).constructor?.name;\n return ctor && ctor !== \"Object\" ? ctor : \"Error\";\n}\n\nexport function serializeError(err: unknown): ErrFields {\n if (!isErrorLike(err)) {\n if (typeof err === \"string\") return { err_type: \"string\", err_message: err };\n return { err_type: typeof err, err_message: defaultRedactor.json(err) };\n }\n const e = err as Error & { code?: unknown; cause?: unknown };\n const out: ErrFields = { err_type: errorType(e), err_message: String(e.message ?? \"\") };\n if (e.code !== undefined && e.code !== null) out.err_code = String(e.code);\n if (typeof e.stack === \"string\") out.err_stack = e.stack;\n\n const causes: string[] = [];\n let cause = e.cause;\n while (cause !== undefined && cause !== null && causes.length < MAX_CAUSE_DEPTH) {\n if (isErrorLike(cause)) {\n causes.push(`${errorType(cause)}: ${cause.message}`);\n cause = (cause as { cause?: unknown }).cause;\n } else {\n causes.push(defaultRedactor.json(cause));\n cause = undefined;\n }\n }\n if (causes.length > 0) out.err_cause = causes.join(\" <- \");\n return out;\n}\n\nconst logged = globalSingleton(\"logged\", () => new WeakSet<object>());\n\n// Marks an error as already written, so a later boundary (e.g. Next's onRequestError)\n// does not log it a second time.\nexport function markLogged(err: unknown): void {\n if (typeof err === \"object\" && err !== null) logged.add(err);\n}\n\nexport function isLogged(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && logged.has(err);\n}\n","import { isErrorLike, serializeError } from \"./error\";\nimport type { Level } from \"./levels\";\nimport { REDACTED, toSnakeCase, type Redactor } from \"./redact\";\n\nexport { DEFAULT_REDACT_KEYS, toSnakeCase } from \"./redact\";\n\n/** Final per-field hook: return a replacement, or undefined to drop the field. */\nexport type RedactHook = (key: string, value: Primitive) => unknown;\n\nexport type Fields = Record<string, unknown>;\nexport type Primitive = string | number | boolean | null;\nexport type LogRecord = Record<string, Primitive>;\n\nexport interface NormalizeOptions {\n snakeCase: boolean;\n redactor: Redactor;\n hook?: RedactHook;\n}\n\n// Fields the redact hook never sees, so every line keeps its level, message and event.\nconst HOOK_EXEMPT = new Set([\"level\", \"message\", \"event\"]);\n\n// Keys owned by Vector (overwritten or deleted on ingest) or by the logger itself.\nexport const RESERVED_KEYS = new Set([\n \"project\", \"service\", \"vps\", \"version\", \"container_name\", \"container_id\", \"image\", \"stream\",\n \"_timestamp\", \"label\", \"host\", \"source_type\", \"msg\", \"lvl\", \"severity\", \"level\", \"message\",\n]);\n\nexport const MAX_LINE_BYTES = 16000;\nconst MAX_MESSAGE = 500;\nconst MAX_STACK = 4000;\nconst MAX_STRING = 1000;\nconst MAX_DEPTH = 3;\nconst TRUNCATED = \"…[truncated]\";\n\n// Fields kept when a line is too large.\nconst KEEP_ON_SHRINK = new Set([\n \"level\", \"message\", \"event\", \"request_id\", \"trace_id\", \"span_id\", \"job_name\", \"job_id\", \"job_attempt\",\n \"user_id\", \"tenant_id\", \"err_type\", \"err_message\", \"err_code\",\n]);\n\nexport function stripUrl(url: string): string {\n const noQuery = url.split(/[?#]/, 1)[0] ?? \"\";\n return noQuery.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/@\\s]*@/i, \"$1\");\n}\n\nexport function truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max - TRUNCATED.length) + TRUNCATED : s;\n}\n\nfunction isPlainObject(v: unknown): v is Fields {\n if (typeof v !== \"object\" || v === null) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction isUrlKey(key: string): boolean {\n return key === \"http_path\" || key === \"http_url\" || key.endsWith(\"_url\");\n}\n\nfunction flattenInto(out: LogRecord, prefix: string, obj: Fields, depth: number, opts: NormalizeOptions): void {\n for (const [rawKey, value] of Object.entries(obj)) {\n const key = opts.snakeCase ? toSnakeCase(rawKey) : rawKey;\n const full = prefix ? `${prefix}_${key}` : key;\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") continue;\n if (value !== null && (opts.redactor.isSensitive(rawKey) || opts.redactor.isSensitive(full))) {\n out[full] = REDACTED;\n continue;\n }\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n out[full] = value;\n } else if (typeof value === \"number\") {\n out[full] = Number.isFinite(value) ? value : String(value);\n } else if (typeof value === \"bigint\") {\n out[full] = value.toString();\n } else if (value instanceof Date) {\n out[full] = Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n } else if (isErrorLike(value)) {\n out[full] = `${value.name}: ${value.message}`;\n } else if (isPlainObject(value) && depth < MAX_DEPTH - 1) {\n flattenInto(out, full, value, depth + 1, opts);\n } else {\n // Arrays, deep objects, class instances: stringified with sensitive keys redacted.\n out[full] = opts.redactor.json(value);\n }\n }\n}\n\nfunction finalize(key: string, value: Primitive, opts: NormalizeOptions): Primitive {\n if (typeof value !== \"string\") return value;\n const v = opts.redactor.scrub(isUrlKey(key) ? stripUrl(value) : value);\n return truncate(v, key === \"err_stack\" ? MAX_STACK : MAX_STRING);\n}\n\nexport function buildRecord(\n level: Level,\n message: unknown,\n sources: (Fields | undefined)[],\n opts: NormalizeOptions,\n): LogRecord {\n const merged: Fields = {};\n for (const source of sources) if (source) Object.assign(merged, source);\n\n let err: unknown;\n if (merged.err !== undefined && merged.err !== null) {\n err = merged.err;\n delete merged.err;\n } else if (isErrorLike(merged.error)) {\n err = merged.error;\n delete merged.error;\n }\n\n const flat: LogRecord = {};\n flattenInto(flat, \"\", merged, 0, opts);\n if (err !== undefined) Object.assign(flat, serializeError(err));\n\n const text = typeof message === \"string\" ? message : opts.redactor.json(message);\n const out: LogRecord = { level, message: truncate(opts.redactor.scrub(text), MAX_MESSAGE) };\n for (const [k, v] of Object.entries(flat)) {\n const key = RESERVED_KEYS.has(k) ? `app_${k}` : k;\n let value = finalize(key, v, opts);\n if (opts.hook && !HOOK_EXEMPT.has(key)) {\n const replaced = opts.hook(key, value);\n if (replaced === undefined) continue;\n value = typeof replaced === \"object\" && replaced !== null ? opts.redactor.json(replaced) : (replaced as Primitive);\n }\n out[key] = value;\n }\n return out;\n}\n\nfunction byteLength(s: string): number {\n // UTF-8 uses at most 3 bytes per UTF-16 code unit: skip encoding short lines.\n if (s.length * 3 <= MAX_LINE_BYTES) return s.length;\n return new TextEncoder().encode(s).length;\n}\n\nexport function serializeRecord(record: LogRecord): string {\n const line = JSON.stringify(record);\n if (byteLength(line) <= MAX_LINE_BYTES) return line;\n const small: LogRecord = {};\n for (const [k, v] of Object.entries(record)) {\n if (KEEP_ON_SHRINK.has(k) || k.startsWith(\"http_\")) small[k] = v;\n }\n small.log_truncated = true;\n return JSON.stringify(small);\n}\n","// No imports: this module is shared with the edge entry (next-edge).\nexport const REQUEST_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\nexport function newRequestId(): string {\n return globalThis.crypto.randomUUID();\n}\n\nfunction first(header?: string | string[] | null): string | undefined {\n return Array.isArray(header) ? header[0] : (header ?? undefined);\n}\n\nexport function resolveRequestId(header?: string | string[] | null): string {\n const value = first(header);\n return value && REQUEST_ID_RE.test(value) ? value : newRequestId();\n}\n\nexport function parseTraceparent(header?: string | string[] | null): { trace_id: string; span_id: string } | undefined {\n const value = first(header)?.trim().toLowerCase();\n const m = value ? TRACEPARENT_RE.exec(value) : null;\n if (!m) return undefined;\n const [, version, traceId, spanId] = m as unknown as [string, string, string, string];\n if (version === \"ff\" || /^0+$/.test(traceId) || /^0+$/.test(spanId)) return undefined;\n return { trace_id: traceId, span_id: spanId };\n}\n","import { getContext } from \"./context\";\nimport { markLogged, serializeError } from \"./error\";\nimport type { Logger } from \"./logger\";\nimport { stripUrl, type Fields } from \"./normalize\";\nimport { parseTraceparent, resolveRequestId } from \"./request-id\";\n\nexport { newRequestId, parseTraceparent, REQUEST_ID_RE, resolveRequestId } from \"./request-id\";\n\nexport type HeaderSource = Headers | Record<string, string | string[] | undefined>;\n\nfunction header(headers: HeaderSource, name: string): string | string[] | undefined {\n if (typeof (headers as Headers).get === \"function\") return (headers as Headers).get(name) ?? undefined;\n return (headers as Record<string, string | string[] | undefined>)[name];\n}\n\nexport function requestContextFields(headers: HeaderSource): { request_id: string; trace_id?: string; span_id?: string } {\n const out: { request_id: string; trace_id?: string; span_id?: string } = {\n request_id: resolveRequestId(header(headers, \"x-request-id\")),\n };\n const tp = parseTraceparent(header(headers, \"traceparent\"));\n if (tp) Object.assign(out, tp);\n return out;\n}\n\n// Headers to forward to services we own, so their logs share request_id / trace_id.\nexport function propagationHeaders(): Record<string, string> {\n const ctx = getContext();\n const out: Record<string, string> = {};\n if (typeof ctx.request_id === \"string\") out[\"x-request-id\"] = ctx.request_id;\n if (typeof ctx.trace_id === \"string\" && typeof ctx.span_id === \"string\") {\n out.traceparent = `00-${ctx.trace_id}-${ctx.span_id}-01`;\n }\n return out;\n}\n\nexport const DEFAULT_SKIP_PATHS: (string | RegExp)[] = [\n /^\\/(health|healthz|ready|readyz|livez)\\/?$/,\n \"/favicon.ico\",\n /^\\/_next\\/static\\//,\n];\n\nexport interface HttpLogOptions {\n skipPaths?: (string | RegExp)[];\n}\n\nexport interface HttpRequestInfo {\n method: string;\n route?: string;\n path: string;\n status: number;\n duration_ms?: number;\n err?: unknown;\n fields?: Fields;\n}\n\nexport function shouldSkip(method: string, path: string, skipPaths: (string | RegExp)[] = DEFAULT_SKIP_PATHS): boolean {\n if (method.toUpperCase() === \"OPTIONS\") return true;\n const p = stripUrl(path);\n return skipPaths.some((s) => (typeof s === \"string\" ? p === s : s.test(p)));\n}\n\n// Writes the one `http.request` summary line for an inbound request.\nexport function logHttpRequest(log: Logger, info: HttpRequestInfo, opts: HttpLogOptions = {}): void {\n if (shouldSkip(info.method, info.path, opts.skipPaths)) return;\n const level = info.status >= 500 ? \"error\" : info.status >= 400 ? \"warn\" : \"info\";\n const path = stripUrl(info.path);\n const errFields: Fields = {};\n if (info.err !== undefined && info.err !== null) {\n Object.assign(errFields, serializeError(info.err));\n if (info.status < 500) delete errFields.err_stack;\n markLogged(info.err);\n }\n // Route templates keep the message bounded; the raw path would make one message per URL.\n const message = info.route ? `${info.method} ${info.route} ${info.status}` : `${info.method} ${info.status}`;\n log[level](message, {\n ...info.fields,\n event: \"http.request\",\n http_method: info.method,\n http_route: info.route,\n http_path: path,\n http_status: info.status,\n duration_ms: info.duration_ms === undefined ? undefined : Math.round(info.duration_ms),\n ...errFields,\n });\n}\n","import { globalSingleton } from \"./global\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\nexport function logStartup(log: Logger, fields: Fields = {}): void {\n log.info(\"app started\", {\n event: \"app.started\",\n runtime_version: `node ${process.versions.node}`,\n log_level: log.level,\n ...fields,\n });\n}\n\n/** Call at the start of your own shutdown handler (e.g. on SIGTERM). The library never handles signals. */\nexport function logShutdown(log: Logger, fields: Fields = {}): void {\n log.info(\"app stopping\", { event: \"app.stopping\", ...fields });\n}\n\nexport interface ProcessHandlerOptions {\n /** Exit with code 1 after an uncaught error. Next.js keeps serving, so its adapter passes false. */\n exitOnCrash?: boolean;\n /** Time other crash handlers (Sentry, APM) get to flush before exit. Default 1000 ms. */\n exitDelayMs?: number;\n exit?: (code: number) => void;\n}\n\nexport function crashHandlers(log: Logger, opts: ProcessHandlerOptions = {}) {\n const exitOnCrash = opts.exitOnCrash ?? true;\n const exitDelayMs = opts.exitDelayMs ?? 1000;\n const exit = opts.exit ?? ((code: number) => process.exit(code));\n let exiting = false;\n const crash = (source: string, err: unknown) => {\n if (!exitOnCrash) {\n log.error(\"unhandled error\", { event: \"app.unhandled_error\", crash_source: source, err });\n return;\n }\n log.fatal(\"app crashed\", { event: \"app.crashed\", crash_source: source, err });\n if (exiting) return;\n exiting = true;\n if (typeof process !== \"undefined\") process.exitCode = 1;\n // Deferred so listeners registered after ours still run; unref so a process with nothing\n // left to do exits on its own (with exitCode 1) without waiting.\n const timer = setTimeout(() => exit(1), exitDelayMs);\n (timer as { unref?: () => void }).unref?.();\n };\n return {\n onUncaught: (err: unknown) => crash(\"uncaughtException\", err),\n onRejection: (reason: unknown) => crash(\"unhandledRejection\", reason),\n };\n}\n\nconst state = globalSingleton(\"process\", () => ({ installed: false }));\n\n/** Logs uncaught exceptions and unhandled rejections. Does not touch SIGTERM/SIGINT. */\nexport function installProcessHandlers(log: Logger, opts: ProcessHandlerOptions = {}): void {\n if (state.installed || typeof process === \"undefined\" || typeof process.on !== \"function\") return;\n state.installed = true;\n const h = crashHandlers(log, opts);\n process.on(\"uncaughtException\", h.onUncaught);\n process.on(\"unhandledRejection\", h.onRejection);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,8BAAkC;;;ACE3B,SAAS,gBAAmB,MAAc,MAAkB;AACjE,QAAM,MAAM,uBAAO,IAAI,iBAAiB,IAAI,EAAE;AAC9C,QAAM,IAAI;AACV,MAAI,QAAQ,EAAE,GAAG;AACjB,MAAI,UAAU,QAAW;AACvB,YAAQ,KAAK;AACb,MAAE,GAAG,IAAI;AAAA,EACX;AACA,SAAO;AACT;;;ADCA,IAAM,MAAM,gBAAgB,OAAO,MAAM,IAAI,0CAAgC,CAAC;AAIvE,SAAS,aAAgB,QAAgB,IAAmC;AACjF,QAAM,SAAS,IAAI,SAAS;AAC5B,QAAM,QAAsB,EAAE,QAAQ,EAAE,GAAG,QAAQ,QAAQ,GAAG,OAAO,GAAG,OAAO;AAC/E,SAAO,IAAI,IAAI,OAAO,MAAM,GAAG,KAAK,CAAC;AACvC;;;AEjBO,IAAM,sBAAsB;AAAA,EACjC;AAAA,EAAY;AAAA,EAAU;AAAA,EAAO;AAAA,EAAc;AAAA,EAAU;AAAA,EACrD;AAAA,EAAS;AAAA,EAAgB;AAAA,EAAiB;AAAA,E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AAO,CAAC;AAAA,EACV;AACF;AAMO,SAAS,WACd,KACA,MACA,QACA,OAA0B,CAAC,GACC;AAC5B,SAAO,UAAU,SAAS;AACxB,UAAM,UAAU,OAAO,KAAK,WAAW,aAAa;AACpD,UAAM,QAAQ,YAAY,IAAI;AAC9B,WAAO,aAAa,EAAE,GAAG,qBAAqB,OAAO,GAAG,aAAa,KAAK,GAAG,OAAO,UAAU;AAC5F,YAAM,SAAS,OAAO,EAAE,GAAG,MAAM,QAAQ,aAAa,KAAK,MAAM,YAAY,IAAI,IAAI,KAAK,EAAE;AAC5F,UAAI;AACF,cAAM,SAAS,MAAM,OAAO,GAAG,IAAI;AACnC,YAAI,KAAK,2BAA2B,EAAE,GAAG,OAAO,GAAG,OAAO,oBAAoB,KAAK,MAAM,MAAM,CAAC;AAChG,eAAO;AAAA,MACT,SAAS,QAAQ;AACf,cAAM,UAAU,kBAAkB,MAAM;AACxC,YAAI,YAAY,QAAW;AACzB,cAAI,KAAK,2BAA2B,EAAE,GAAG,OAAO,GAAG,OAAO,oBAAoB,qBAAqB,QAAQ,CAAC;AAC5G,gBAAM;AAAA,QACR;AACA,cAAM,MAAM,QAAQ,MAAM;AAC1B,YAAI,MAAM,wBAAwB,EAAE,GAAG,OAAO,GAAG,OAAO,iBAAiB,IAAI,CAAC;AAC9E,mBAAW,GAAG;AACd,cAAM;AAAA,MACR;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":["header"]}
package/dist/next.d.cts CHANGED
@@ -14,6 +14,12 @@ type RouteHandler = (...args: any[]) => Response | Promise<Response>;
14
14
  * function has exactly the handler's parameters, so Next's route type checks still pass.
15
15
  */
16
16
  declare function withLogging<H extends RouteHandler>(log: Logger, handler: H, opts?: WithLoggingOptions): (...args: Parameters<H>) => Promise<Awaited<ReturnType<H>>>;
17
+ /**
18
+ * patchConsole skip predicate for Next.js: Next prints a render error with console.error right
19
+ * before calling onRequestError, by then the error carries a digest. Dropping that console
20
+ * call leaves the single, richer onRequestError line.
21
+ */
22
+ declare function nextConsoleSkip(args: unknown[]): boolean;
17
23
  interface NextRequestInfo {
18
24
  path?: string;
19
25
  method?: string;
@@ -38,4 +44,4 @@ interface WithActionOptions {
38
44
  */
39
45
  declare function withAction<A extends unknown[], R>(log: Logger, name: string, action: (...args: A) => Promise<R>, opts?: WithActionOptions): (...args: A) => Promise<R>;
40
46
 
41
- export { type NextErrorContext, type NextRequestInfo, type RouteHandler, type WithActionOptions, type WithLoggingOptions, nextControlStatus, nextOnRequestError, registerNext, withAction, withLogging };
47
+ export { type NextErrorContext, type NextRequestInfo, type RouteHandler, type WithActionOptions, type WithLoggingOptions, nextConsoleSkip, nextControlStatus, nextOnRequestError, registerNext, withAction, withLogging };
package/dist/next.d.ts CHANGED
@@ -14,6 +14,12 @@ type RouteHandler = (...args: any[]) => Response | Promise<Response>;
14
14
  * function has exactly the handler's parameters, so Next's route type checks still pass.
15
15
  */
16
16
  declare function withLogging<H extends RouteHandler>(log: Logger, handler: H, opts?: WithLoggingOptions): (...args: Parameters<H>) => Promise<Awaited<ReturnType<H>>>;
17
+ /**
18
+ * patchConsole skip predicate for Next.js: Next prints a render error with console.error right
19
+ * before calling onRequestError, by then the error carries a digest. Dropping that console
20
+ * call leaves the single, richer onRequestError line.
21
+ */
22
+ declare function nextConsoleSkip(args: unknown[]): boolean;
17
23
  interface NextRequestInfo {
18
24
  path?: string;
19
25
  method?: string;
@@ -38,4 +44,4 @@ interface WithActionOptions {
38
44
  */
39
45
  declare function withAction<A extends unknown[], R>(log: Logger, name: string, action: (...args: A) => Promise<R>, opts?: WithActionOptions): (...args: A) => Promise<R>;
40
46
 
41
- export { type NextErrorContext, type NextRequestInfo, type RouteHandler, type WithActionOptions, type WithLoggingOptions, nextControlStatus, nextOnRequestError, registerNext, withAction, withLogging };
47
+ export { type NextErrorContext, type NextRequestInfo, type RouteHandler, type WithActionOptions, type WithLoggingOptions, nextConsoleSkip, nextControlStatus, nextOnRequestError, registerNext, withAction, withLogging };
package/dist/next.js CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  } from "./chunk-KD5H5G6Y.js";
9
9
  import "./chunk-KLBL7QEN.js";
10
10
  import {
11
+ isErrorLike,
11
12
  isLogged,
12
13
  markLogged,
13
14
  runWithStore
@@ -70,6 +71,9 @@ function withLogging(log, handler, opts = {}) {
70
71
  });
71
72
  };
72
73
  }
74
+ function nextConsoleSkip(args) {
75
+ return args.some((arg) => isErrorLike(arg) && typeof arg.digest === "string");
76
+ }
73
77
  function nextOnRequestError(log, opts = {}) {
74
78
  return async (err, request, context) => {
75
79
  if (isLogged(err) || nextControlStatus(err) !== void 0) return;
@@ -131,6 +135,7 @@ function withAction(log, name, action, opts = {}) {
131
135
  };
132
136
  }
133
137
  export {
138
+ nextConsoleSkip,
134
139
  nextControlStatus,
135
140
  nextOnRequestError,
136
141
  registerNext,
package/dist/next.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/next.ts"],"sourcesContent":["import { runWithStore } from \"./context\";\nimport { isLogged, markLogged } from \"./error\";\nimport { logHttpRequest, requestContextFields, type HeaderSource, type HttpLogOptions } from \"./http\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\nimport { installProcessHandlers, logStartup } from \"./process\";\n\nexport interface WithLoggingOptions extends HttpLogOptions {\n /** Route template, e.g. \"/api/orders/[id]\". Left empty when not given. */\n route?: string;\n}\n\n/** Status for Next's control-flow errors (redirect(), notFound(), forbidden()...), else undefined. */\nexport function nextControlStatus(err: unknown): number | undefined {\n const digest = (err as { digest?: unknown } | null)?.digest;\n if (typeof digest !== \"string\") return undefined;\n if (digest.startsWith(\"NEXT_REDIRECT\")) {\n const status = Number(digest.split(\";\")[3]);\n return Number.isInteger(status) && status >= 300 ? status : 307;\n }\n if (digest === \"NEXT_NOT_FOUND\") return 404;\n if (digest.startsWith(\"NEXT_HTTP_ERROR_FALLBACK;\")) return Number(digest.split(\";\")[1]) || 404;\n return undefined;\n}\n\nfunction asError(value: unknown): unknown {\n if (typeof value === \"object\" && value !== null) return value;\n return Object.assign(new Error(String(value)), { name: \"NonErrorThrown\", thrown: value });\n}\n\nfunction trySetHeader(res: Response, name: string, value: string): void {\n try {\n res.headers.set(name, value);\n } catch {\n // Some responses (Response.redirect, proxied fetch responses) have immutable headers.\n }\n}\n\n/** Any App Router route handler: `()`, `(request)` or `(request, { params })`. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type RouteHandler = (...args: any[]) => Response | Promise<Response>;\n\n/**\n * Wraps an App Router route handler: request context + one http.request line. The returned\n * function has exactly the handler's parameters, so Next's route type checks still pass.\n */\nexport function withLogging<H extends RouteHandler>(\n log: Logger,\n handler: H,\n opts: WithLoggingOptions = {},\n): (...args: Parameters<H>) => Promise<Awaited<ReturnType<H>>> {\n return async (...args): Promise<Awaited<ReturnType<H>>> => {\n const request: unknown = args[0];\n // Next always passes the request; direct calls in unit tests may not.\n if (!(request instanceof Request)) return (await handler(...args)) as Awaited<ReturnType<H>>;\n const ctx = requestContextFields(request.headers);\n const path = new URL(request.url).pathname;\n const start = performance.now();\n return await runWithStore(ctx, async (store): Promise<Awaited<ReturnType<H>>> => {\n const summary = (status: number, err: unknown) =>\n logHttpRequest(\n log,\n {\n method: request.method,\n route: opts.route,\n path,\n status,\n duration_ms: performance.now() - start,\n err,\n fields: store.fields,\n },\n opts,\n );\n try {\n const res = (await handler(...args)) as Awaited<ReturnType<H>>;\n summary((res as Response).status, store.error);\n trySetHeader(res as Response, \"x-request-id\", ctx.request_id);\n return res;\n } catch (caught) {\n const control = nextControlStatus(caught);\n // Non-objects cannot be marked as logged, so onRequestError would log them again.\n const err = control === undefined ? asError(caught) : caught;\n summary(control ?? 500, control === undefined ? err : store.error);\n throw err;\n }\n });\n };\n}\n\nexport interface NextRequestInfo {\n path?: string;\n method?: string;\n headers?: Record<string, string | string[] | undefined>;\n}\n\nexport interface NextErrorContext {\n routerKind?: string;\n routePath?: string;\n routeType?: string;\n}\n\n/** `export const onRequestError = nextOnRequestError(log)` in instrumentation.ts. */\nexport function nextOnRequestError(log: Logger, opts: HttpLogOptions = {}) {\n return async (err: unknown, request: NextRequestInfo, context: NextErrorContext): Promise<void> => {\n if (isLogged(err) || nextControlStatus(err) !== undefined) return;\n const digest = (err as { digest?: unknown } | null)?.digest;\n logHttpRequest(\n log,\n {\n method: request?.method ?? \"GET\",\n route: context?.routePath,\n path: request?.path ?? \"\",\n status: 500,\n err,\n fields: {\n ...requestContextFields(request?.headers ?? {}),\n next_route_type: context?.routeType,\n next_router_kind: context?.routerKind,\n next_digest: typeof digest === \"string\" ? digest : undefined,\n },\n },\n opts,\n );\n };\n}\n\n/** Call from `register()` in instrumentation.ts. Does nothing on the edge runtime. */\nexport function registerNext(log: Logger, fields?: Fields): void {\n if (process.env.NEXT_RUNTIME && process.env.NEXT_RUNTIME !== \"nodejs\") return;\n // Next keeps serving after an unhandled rejection, so do not exit.\n installProcessHandlers(log, { exitOnCrash: false });\n logStartup(log, { port: process.env.PORT ? Number(process.env.PORT) : undefined, ...fields });\n}\n\nexport interface WithActionOptions {\n /** Request headers source. Defaults to `headers()` from next/headers. */\n headers?: () => HeaderSource | Promise<HeaderSource>;\n}\n\nasync function nextHeaders(): Promise<HeaderSource> {\n try {\n const mod = (await import(\"next/headers\")) as { headers: () => HeaderSource | Promise<HeaderSource> };\n return await mod.headers();\n } catch {\n // Called outside a request (tests, scripts) or Next is not installed.\n return {};\n }\n}\n\n/**\n * Wraps a server action: request context (request_id from x-request-id) plus one\n * `action.completed` / `action.failed` line. redirect()/notFound() count as completed.\n */\nexport function withAction<A extends unknown[], R>(\n log: Logger,\n name: string,\n action: (...args: A) => Promise<R>,\n opts: WithActionOptions = {},\n): (...args: A) => Promise<R> {\n return async (...args) => {\n const headers = await (opts.headers ?? nextHeaders)();\n const start = performance.now();\n return runWithStore({ ...requestContextFields(headers), action_name: name }, async (store) => {\n const fields = () => ({ ...store.fields, duration_ms: Math.round(performance.now() - start) });\n try {\n const result = await action(...args);\n log.info(\"server action completed\", { ...fields(), event: \"action.completed\", err: store.error });\n return result;\n } catch (caught) {\n const control = nextControlStatus(caught);\n if (control !== undefined) {\n log.info(\"server action completed\", { ...fields(), event: \"action.completed\", next_control_status: control });\n throw caught;\n }\n const err = asError(caught);\n log.error(\"server action failed\", { ...fields(), event: \"action.failed\", err });\n markLogged(err);\n throw err;\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaO,SAAS,kBAAkB,KAAkC;AAClE,QAAM,SAAU,KAAqC;AACrD,MAAI,OAAO,WAAW,SAAU,QAAO;AACvC,MAAI,OAAO,WAAW,eAAe,GAAG;AACtC,UAAM,SAAS,OAAO,OAAO,MAAM,GAAG,EAAE,CAAC,CAAC;AAC1C,WAAO,OAAO,UAAU,MAAM,KAAK,UAAU,MAAM,SAAS;AAAA,EAC9D;AACA,MAAI,WAAW,iBAAkB,QAAO;AACxC,MAAI,OAAO,WAAW,2BAA2B,EAAG,QAAO,OAAO,OAAO,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK;AAC3F,SAAO;AACT;AAEA,SAAS,QAAQ,OAAyB;AACxC,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,SAAO,OAAO,OAAO,IAAI,MAAM,OAAO,KAAK,CAAC,GAAG,EAAE,MAAM,kBAAkB,QAAQ,MAAM,CAAC;AAC1F;AAEA,SAAS,aAAa,KAAe,MAAc,OAAqB;AACtE,MAAI;AACF,QAAI,QAAQ,IAAI,MAAM,KAAK;AAAA,EAC7B,QAAQ;AAAA,EAER;AACF;AAUO,SAAS,YACd,KACA,SACA,OAA2B,CAAC,GACiC;AAC7D,SAAO,UAAU,SAA0C;AACzD,UAAM,UAAmB,KAAK,CAAC;AAE/B,QAAI,EAAE,mBAAmB,SAAU,QAAQ,MAAM,QAAQ,GAAG,IAAI;AAChE,UAAM,MAAM,qBAAqB,QAAQ,OAAO;AAChD,UAAM,OAAO,IAAI,IAAI,QAAQ,GAAG,EAAE;AAClC,UAAM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F;","names":[]}
1
+ {"version":3,"sources":["../src/next.ts"],"sourcesContent":["import { runWithStore } from \"./context\";\nimport { isErrorLike, isLogged, markLogged } from \"./error\";\nimport { logHttpRequest, requestContextFields, type HeaderSource, type HttpLogOptions } from \"./http\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\nimport { installProcessHandlers, logStartup } from \"./process\";\n\nexport interface WithLoggingOptions extends HttpLogOptions {\n /** Route template, e.g. \"/api/orders/[id]\". Left empty when not given. */\n route?: string;\n}\n\n/** Status for Next's control-flow errors (redirect(), notFound(), forbidden()...), else undefined. */\nexport function nextControlStatus(err: unknown): number | undefined {\n const digest = (err as { digest?: unknown } | null)?.digest;\n if (typeof digest !== \"string\") return undefined;\n if (digest.startsWith(\"NEXT_REDIRECT\")) {\n const status = Number(digest.split(\";\")[3]);\n return Number.isInteger(status) && status >= 300 ? status : 307;\n }\n if (digest === \"NEXT_NOT_FOUND\") return 404;\n if (digest.startsWith(\"NEXT_HTTP_ERROR_FALLBACK;\")) return Number(digest.split(\";\")[1]) || 404;\n return undefined;\n}\n\nfunction asError(value: unknown): unknown {\n if (typeof value === \"object\" && value !== null) return value;\n return Object.assign(new Error(String(value)), { name: \"NonErrorThrown\", thrown: value });\n}\n\nfunction trySetHeader(res: Response, name: string, value: string): void {\n try {\n res.headers.set(name, value);\n } catch {\n // Some responses (Response.redirect, proxied fetch responses) have immutable headers.\n }\n}\n\n/** Any App Router route handler: `()`, `(request)` or `(request, { params })`. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type RouteHandler = (...args: any[]) => Response | Promise<Response>;\n\n/**\n * Wraps an App Router route handler: request context + one http.request line. The returned\n * function has exactly the handler's parameters, so Next's route type checks still pass.\n */\nexport function withLogging<H extends RouteHandler>(\n log: Logger,\n handler: H,\n opts: WithLoggingOptions = {},\n): (...args: Parameters<H>) => Promise<Awaited<ReturnType<H>>> {\n return async (...args): Promise<Awaited<ReturnType<H>>> => {\n const request: unknown = args[0];\n // Next always passes the request; direct calls in unit tests may not.\n if (!(request instanceof Request)) return (await handler(...args)) as Awaited<ReturnType<H>>;\n const ctx = requestContextFields(request.headers);\n const path = new URL(request.url).pathname;\n const start = performance.now();\n return await runWithStore(ctx, async (store): Promise<Awaited<ReturnType<H>>> => {\n const summary = (status: number, err: unknown) =>\n logHttpRequest(\n log,\n {\n method: request.method,\n route: opts.route,\n path,\n status,\n duration_ms: performance.now() - start,\n err,\n fields: store.fields,\n },\n opts,\n );\n try {\n const res = (await handler(...args)) as Awaited<ReturnType<H>>;\n summary((res as Response).status, store.error);\n trySetHeader(res as Response, \"x-request-id\", ctx.request_id);\n return res;\n } catch (caught) {\n const control = nextControlStatus(caught);\n // Non-objects cannot be marked as logged, so onRequestError would log them again.\n const err = control === undefined ? asError(caught) : caught;\n summary(control ?? 500, control === undefined ? err : store.error);\n throw err;\n }\n });\n };\n}\n\n/**\n * patchConsole skip predicate for Next.js: Next prints a render error with console.error right\n * before calling onRequestError, by then the error carries a digest. Dropping that console\n * call leaves the single, richer onRequestError line.\n */\nexport function nextConsoleSkip(args: unknown[]): boolean {\n return args.some((arg) => isErrorLike(arg) && typeof (arg as { digest?: unknown }).digest === \"string\");\n}\n\nexport interface NextRequestInfo {\n path?: string;\n method?: string;\n headers?: Record<string, string | string[] | undefined>;\n}\n\nexport interface NextErrorContext {\n routerKind?: string;\n routePath?: string;\n routeType?: string;\n}\n\n/** `export const onRequestError = nextOnRequestError(log)` in instrumentation.ts. */\nexport function nextOnRequestError(log: Logger, opts: HttpLogOptions = {}) {\n return async (err: unknown, request: NextRequestInfo, context: NextErrorContext): Promise<void> => {\n if (isLogged(err) || nextControlStatus(err) !== undefined) return;\n const digest = (err as { digest?: unknown } | null)?.digest;\n logHttpRequest(\n log,\n {\n method: request?.method ?? \"GET\",\n route: context?.routePath,\n path: request?.path ?? \"\",\n status: 500,\n err,\n fields: {\n ...requestContextFields(request?.headers ?? {}),\n next_route_type: context?.routeType,\n next_router_kind: context?.routerKind,\n next_digest: typeof digest === \"string\" ? digest : undefined,\n },\n },\n opts,\n );\n };\n}\n\n/** Call from `register()` in instrumentation.ts. Does nothing on the edge runtime. */\nexport function registerNext(log: Logger, fields?: Fields): void {\n if (process.env.NEXT_RUNTIME && process.env.NEXT_RUNTIME !== \"nodejs\") return;\n // Next keeps serving after an unhandled rejection, so do not exit.\n installProcessHandlers(log, { exitOnCrash: false });\n logStartup(log, { port: process.env.PORT ? Number(process.env.PORT) : undefined, ...fields });\n}\n\nexport interface WithActionOptions {\n /** Request headers source. Defaults to `headers()` from next/headers. */\n headers?: () => HeaderSource | Promise<HeaderSource>;\n}\n\nasync function nextHeaders(): Promise<HeaderSource> {\n try {\n const mod = (await import(\"next/headers\")) as { headers: () => HeaderSource | Promise<HeaderSource> };\n return await mod.headers();\n } catch {\n // Called outside a request (tests, scripts) or Next is not installed.\n return {};\n }\n}\n\n/**\n * Wraps a server action: request context (request_id from x-request-id) plus one\n * `action.completed` / `action.failed` line. redirect()/notFound() count as completed.\n */\nexport function withAction<A extends unknown[], R>(\n log: Logger,\n name: string,\n action: (...args: A) => Promise<R>,\n opts: WithActionOptions = {},\n): (...args: A) => Promise<R> {\n return async (...args) => {\n const headers = await (opts.headers ?? nextHeaders)();\n const start = performance.now();\n return runWithStore({ ...requestContextFields(headers), action_name: name }, async (store) => {\n const fields = () => ({ ...store.fields, duration_ms: Math.round(performance.now() - start) });\n try {\n const result = await action(...args);\n log.info(\"server action completed\", { ...fields(), event: \"action.completed\", err: store.error });\n return result;\n } catch (caught) {\n const control = nextControlStatus(caught);\n if (control !== undefined) {\n log.info(\"server action completed\", { ...fields(), event: \"action.completed\", next_control_status: control });\n throw caught;\n }\n const err = asError(caught);\n log.error(\"server action failed\", { ...fields(), event: \"action.failed\", err });\n markLogged(err);\n throw err;\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAaO,SAAS,kBAAkB,KAAkC;AAClE,QAAM,SAAU,KAAqC;AACrD,MAAI,OAAO,WA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C9F;AAOA,eAAe,cAAqC;AAClD,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,cAAc;AACxC,WAAO,MAAM,IAAI,QAAQ;AAAA,EAC3B,QAAQ;AAEN,WAAO,CAAC;AAAA,EACV;AACF;AAMO,SAAS,WACd,KACA,MACA,QACA,OAA0B,CAAC,GACC;AAC5B,SAAO,UAAU,SAAS;AACxB,UAAM,UAAU,OAAO,KAAK,WAAW,aAAa;AACpD,UAAM,QAAQ,YAAY,IAAI;AAC9B,WAAO,aAAa,EAAE,GAAG,qBAAqB,OAAO,GAAG,aAAa,KAAK,GAAG,OAAO,UAAU;AAC5F,YAAM,SAAS,OAAO,EAAE,GAAG,MAAM,QAAQ,aAAa,KAAK,MAAM,YAAY,IAAI,IAAI,KAAK,EAAE;AAC5F,UAAI;AACF,cAAM,SAAS,MAAM,OAAO,GAAG,IAAI;AACnC,YAAI,KAAK,2BAA2B,EAAE,GAAG,OAAO,GAAG,OAAO,oBAAoB,KAAK,MAAM,MAAM,CAAC;AAChG,eAAO;AAAA,MACT,SAAS,QAAQ;AACf,cAAM,UAAU,kBAAkB,MAAM;AACxC,YAAI,YAAY,QAAW;AACzB,cAAI,KAAK,2BAA2B,EAAE,GAAG,OAAO,GAAG,OAAO,oBAAoB,qBAAqB,QAAQ,CAAC;AAC5G,gBAAM;AAAA,QACR;AACA,cAAM,MAAM,QAAQ,MAAM;AAC1B,YAAI,MAAM,wBAAwB,EAAE,GAAG,OAAO,GAAG,OAAO,iBAAiB,IAAI,CAAC;AAC9E,mBAAW,GAAG;AACd,cAAM;AAAA,MACR;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
package/dist/strapi.cjs CHANGED
@@ -324,16 +324,25 @@ function forward(log, info) {
324
324
  log[level](typeof message === "string" ? message : String(message ?? ""), fields);
325
325
  }
326
326
  function strapiLoggerConfig(log) {
327
+ let parent;
328
+ const allowed = (info) => {
329
+ const rank = parent?.levels?.[String(info.level)];
330
+ const max = parent?.level === void 0 ? void 0 : parent.levels?.[parent.level];
331
+ return rank === void 0 || max === void 0 || rank <= max;
332
+ };
327
333
  const transport = new import_node_stream.Writable({
328
334
  objectMode: true,
329
335
  write(info, _encoding, callback) {
330
336
  try {
331
- forward(log, info);
337
+ if (allowed(info)) forward(log, info);
332
338
  } finally {
333
339
  callback();
334
340
  }
335
341
  }
336
342
  });
343
+ transport.on("pipe", (source) => {
344
+ parent = source;
345
+ });
337
346
  Object.assign(transport, {
338
347
  log(info, callback) {
339
348
  forward(log, info);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/strapi.ts","../src/context.ts","../src/global.ts","../src/redact.ts","../src/error.ts","../src/normalize.ts","../src/request-id.ts","../src/http.ts"],"sourcesContent":["import { Writable } from \"node:stream\";\nimport { currentStore, recordErrorIn, runWithStore } from \"./context\";\nimport { isErrorLike, isLogged, markLogged } from \"./error\";\nimport { logHttpRequest, newRequestId, parseTraceparent, REQUEST_ID_RE, type HttpLogOptions } from \"./http\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\n/** The parts of a Koa/Strapi context the middlewares use. */\nexport interface KoaContextLike {\n method: string;\n url: string;\n status: number;\n state: Record<string, unknown>;\n get(name: string): string;\n set(name: string, value: string): void;\n /** Full matched route template, set by @koa/router (includes router prefixes such as /api). */\n _matchedRoute?: unknown;\n}\n\nexport type KoaMiddleware = (ctx: KoaContextLike, next: () => Promise<unknown>) => Promise<void>;\n\nexport interface StrapiRequestLoggerOptions extends HttpLogOptions {\n log: Logger;\n /**\n * Use a valid incoming x-request-id as request_id. Off by default: the server issues its own\n * id (Strapi apps often use it for audit rows) and records the caller's id as\n * upstream_request_id, which still links the logs of both services.\n */\n trustIncomingRequestId?: boolean;\n /** ctx.state key shared with the app's own correlation middleware. Default \"requestId\". */\n stateKey?: string;\n}\n\nfunction routeOf(ctx: KoaContextLike): string | undefined {\n if (typeof ctx._matchedRoute === \"string\") return ctx._matchedRoute;\n const path = (ctx.state.route as { path?: unknown } | undefined)?.path;\n return typeof path === \"string\" ? path : undefined;\n}\n\n/**\n * Replaces 'strapi::logger' (put it first in config/middlewares): opens the request context and\n * writes one http.request line per request.\n */\nexport function strapiRequestLogger(opts: StrapiRequestLoggerOptions): KoaMiddleware {\n const stateKey = opts.stateKey ?? \"requestId\";\n return async (ctx, next) => {\n const incoming = ctx.get(\"x-request-id\");\n const caller = incoming && REQUEST_ID_RE.test(incoming) ? incoming : undefined;\n const existing = ctx.state[stateKey];\n const requestId =\n typeof existing === \"string\" && existing ? existing : opts.trustIncomingRequestId && caller ? caller : newRequestId();\n // A UUID v4 here is kept by correlation middlewares that only replace invalid ids.\n if (ctx.state[stateKey] === undefined) ctx.state[stateKey] = requestId;\n ctx.set(\"X-Request-ID\", requestId);\n\n const fields: Fields = { request_id: requestId };\n if (caller && caller !== requestId) fields.upstream_request_id = caller;\n const trace = parseTraceparent(ctx.get(\"traceparent\"));\n if (trace) Object.assign(fields, trace);\n\n const start = performance.now();\n await runWithStore(fields, async (store) => {\n let failed = false;\n try {\n await next();\n } catch (err) {\n // Only reached when no error middleware handled it; Koa answers 500.\n failed = true;\n recordErrorIn(store, err);\n throw err;\n } finally {\n logHttpRequest(\n opts.log,\n {\n method: ctx.method,\n route: routeOf(ctx),\n path: ctx.url,\n status: failed ? 500 : ctx.status,\n duration_ms: performance.now() - start,\n err: store.error,\n fields: store.fields,\n },\n opts,\n );\n }\n });\n };\n}\n\n/**\n * Put right after 'strapi::errors'. Records thrown errors on the request's http.request line and\n * marks them, so the copy strapi::errors logs through strapi.log.error is not written twice.\n */\nexport function strapiErrorCapture(): KoaMiddleware {\n return async (_ctx, next) => {\n try {\n await next();\n } catch (err) {\n const store = currentStore();\n if (store) recordErrorIn(store, err);\n markLogged(err);\n throw err;\n }\n };\n}\n\nconst LEVELS: Record<string, Level> = {\n error: \"error\",\n warn: \"warn\",\n info: \"info\",\n http: \"debug\",\n verbose: \"debug\",\n debug: \"debug\",\n silly: \"trace\",\n};\n\nconst META_SKIP = new Set([\"level\", \"message\", \"stack\"]);\n\nfunction forward(log: Logger, info: Record<string, unknown>): void {\n // Already carried by the request's http.request line (see strapiErrorCapture).\n if (isErrorLike(info) && isLogged(info)) return;\n const level = LEVELS[String(info.level)] ?? \"info\";\n const fields: Fields = {};\n for (const [key, value] of Object.entries(info)) if (!META_SKIP.has(key)) fields[key] = value;\n\n let message: unknown = info.message;\n if (isErrorLike(info)) {\n fields.err = info;\n } else if (isErrorLike(message)) {\n if (isLogged(message)) return;\n fields.err = message;\n message = message.message;\n } else if (typeof info.stack === \"string\") {\n fields.err_stack = info.stack;\n }\n if ((level === \"warn\" || level === \"error\") && fields.event === undefined) fields.event = \"strapi.log\";\n log[level](typeof message === \"string\" ? message : String(message ?? \"\"), fields);\n}\n\n/**\n * Winston configuration for Strapi's config/logger.ts: every strapi.log.* call (app code and\n * framework) becomes a contract JSON line with the request context. Level filtering is left to\n * the logger (LOG_LEVEL).\n */\nexport function strapiLoggerConfig(log: Logger) {\n const transport = new Writable({\n objectMode: true,\n write(info: Record<string, unknown>, _encoding, callback) {\n try {\n forward(log, info);\n } finally {\n callback();\n }\n },\n });\n // winston requires a `log(info, callback)` method on stream transports; writes go through write().\n Object.assign(transport, {\n log(info: Record<string, unknown>, callback: () => void) {\n forward(log, info);\n callback();\n },\n });\n return {\n level: \"silly\",\n // Identity format: replaces Strapi's prettyPrint so the transport receives raw info objects.\n format: { transform: <T>(info: T): T => info },\n transports: [transport],\n };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { globalSingleton } from \"./global\";\nimport type { Fields } from \"./normalize\";\n\nexport interface ContextStore {\n fields: Fields;\n error?: unknown;\n /** Route template captured while the router still knew it (Express error path). */\n route?: string;\n parent?: ContextStore;\n}\n\nconst als = globalSingleton(\"als\", () => new AsyncLocalStorage<ContextStore>());\n\nexport const STORE_KEY: symbol = Symbol.for(\"@tanngo11/log.store\");\n\nexport function runWithStore<T>(fields: Fields, fn: (store: ContextStore) => T): T {\n const parent = als.getStore();\n const store: ContextStore = { fields: { ...parent?.fields, ...fields }, parent };\n return als.run(store, () => fn(store));\n}\n\nexport function withContext<T>(fields: Fields, fn: () => T): T {\n return runWithStore(fields, () => fn());\n}\n\nexport function currentStore(): ContextStore | undefined {\n return als.getStore();\n}\n\nexport function getContext(): Fields {\n return als.getStore()?.fields ?? {};\n}\n\n// Applies to the current context and every enclosing one, so a field added inside a nested\n// withContext/runJob still reaches the request's http.request line.\nexport function addContext(fields: Fields): void {\n for (let s = als.getStore(); s; s = s.parent) Object.assign(s.fields, fields);\n}\n\n// Sets the error on the store and on enclosing stores that have none yet.\nexport function recordErrorIn(store: ContextStore, err: unknown): void {\n store.error = err;\n for (let s = store.parent; s; s = s.parent) if (s.error === undefined) s.error = err;\n}\n\n// Marks the error that the current request/job summary line should carry. Does not write a line.\nexport function recordError(err: unknown): void {\n const store = als.getStore();\n if (store) recordErrorIn(store, err);\n}\n\nexport function attachStore(target: object, store: ContextStore): void {\n (target as Record<symbol, ContextStore>)[STORE_KEY] = store;\n}\n\nexport function storeOf(target: unknown): ContextStore | undefined {\n if (typeof target !== \"object\" || target === null) return undefined;\n return (target as Record<symbol, ContextStore | undefined>)[STORE_KEY];\n}\n","// Singletons shared by every copy of this package loaded in the process (ESM and CJS builds,\n// or duplicated installs), so context and dedupe state never split.\nexport function globalSingleton<T>(name: string, make: () => T): T {\n const key = Symbol.for(`@tanngo11/log.${name}`);\n const g = globalThis as unknown as Record<symbol, T | undefined>;\n let value = g[key];\n if (value === undefined) {\n value = make();\n g[key] = value;\n }\n return value;\n}\n","// Redaction shared by the logger and the error serializer. The collector redacts again,\n// but it cannot see secrets inside JSON-encoded strings, so the app side must catch them.\n\nexport const DEFAULT_REDACT_KEYS = [\n \"password\", \"passwd\", \"pwd\", \"passphrase\", \"secret\", \"client_secret\",\n \"token\", \"access_token\", \"refresh_token\", \"id_token\", \"auth_token\",\n \"api_key\", \"apikey\", \"access_key\", \"secret_key\", \"private_key\",\n \"authorization\", \"cookie\", \"set_cookie\", \"session_id\", \"sessionid\",\n \"credential\", \"credentials\", \"dsn\", \"connection_string\", \"conn_string\", \"jwt\", \"bearer\",\n];\n\n/** Opt-in value patterns for `redactValues`. Not on by default: they can hit ordinary numbers. */\nexport const REDACT_PATTERNS = {\n /** Vietnamese mobile numbers: 0912345678, +84912345678, 84912345678. */\n phoneVN: /(?<![\\d+])(?:\\+?84|0)[35789]\\d{8}(?!\\d)/g,\n /** Visa, Mastercard, Amex, Discover-like card numbers, with optional spaces or dashes. */\n paymentCard: /(?<!\\d)(?:4\\d{3}|5[1-5]\\d{2}|2[2-7]\\d{2}|3[47]\\d{2}|6(?:011|5\\d{2}))(?:[ -]?\\d{4}){2}[ -]?\\d{1,4}(?!\\d)/g,\n /** IPv4 addresses. */\n ipv4: /(?<![\\d.])(?:\\d{1,3}\\.){3}\\d{1,3}(?![\\d.])/g,\n} as const;\n\n// Keys that only describe a secret (count, type, timestamps, flags) stay readable.\nconst SAFE_SUFFIXES = [\"_count\", \"_type\", \"_length\", \"_expires_at\", \"_expires_in\", \"_ttl\", \"_at\", \"_ms\", \"_enabled\"];\n\nexport const REDACTED = \"[REDACTED]\";\n\nexport function toSnakeCase(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .toLowerCase();\n}\n\nconst URL_CREDENTIALS_RE = /([a-z][a-z0-9+.-]*:\\/\\/)[^\\s/@:\"']+:[^\\s/@\"']+@/gi;\nconst BEARER_RE = /\\bBearer\\s+[A-Za-z0-9._~+/=-]+/gi;\nconst JWT_RE = /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+/g;\nconst EMAIL_RE = /[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,})/g;\n\nexport type KeyPattern = string | RegExp;\n\nexport interface RedactorOptions {\n /** Extra sensitive keys: names (matched like the defaults) or patterns tested on the snake_case key. */\n keys?: readonly KeyPattern[];\n /** Extra value patterns; every match inside any string becomes [REDACTED]. */\n values?: readonly RegExp[];\n}\n\nexport interface Redactor {\n isSensitive(key: string): boolean;\n /** Masks secrets and emails that appear inside free text. */\n scrub(s: string): string;\n /** JSON.stringify that redacts sensitive keys at any depth and never throws. */\n json(value: unknown): string;\n}\n\nfunction globalize(re: RegExp): RegExp {\n return re.flags.includes(\"g\") ? new RegExp(re.source, re.flags) : new RegExp(re.source, `${re.flags}g`);\n}\n\nexport function createRedactor(opts: RedactorOptions = {}): Redactor {\n const words = [...DEFAULT_REDACT_KEYS];\n const keyPatterns: RegExp[] = [];\n for (const k of opts.keys ?? []) {\n if (typeof k === \"string\") words.push(toSnakeCase(k));\n else keyPatterns.push(new RegExp(k.source, k.flags.replace(\"g\", \"\")));\n }\n const valuePatterns = (opts.values ?? []).map(globalize);\n\n const isSensitive = (key: string): boolean => {\n const k = toSnakeCase(key);\n if (keyPatterns.some((re) => re.test(k))) return true;\n if (!words.includes(k) && SAFE_SUFFIXES.some((s) => k.endsWith(s))) return false;\n return words.some((w) => k === w || k.startsWith(`${w}_`) || k.endsWith(`_${w}`) || k.includes(`_${w}_`));\n };\n\n const scrub = (s: string): string => {\n let out = s\n .replace(URL_CREDENTIALS_RE, `$1${REDACTED}@`)\n .replace(BEARER_RE, `Bearer ${REDACTED}`)\n .replace(JWT_RE, \"[REDACTED_JWT]\")\n .replace(EMAIL_RE, \"***@$1\");\n for (const re of valuePatterns) out = out.replace(re, REDACTED);\n return out;\n };\n\n const json = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n const text = JSON.stringify(value, (key, val: unknown) => {\n if (key && val !== null && val !== undefined && isSensitive(key)) return REDACTED;\n if (typeof val === \"bigint\") return val.toString();\n if (val instanceof Error) return { name: val.name, message: val.message };\n return val;\n });\n return text ?? String(value);\n } catch {\n return String(value);\n }\n };\n\n return { isSensitive, scrub, json };\n}\n\nexport const defaultRedactor: Redactor = createRedactor();\n","import { globalSingleton } from \"./global\";\nimport { defaultRedactor } from \"./redact\";\n\nexport interface ErrFields {\n err_type?: string;\n err_message?: string;\n err_code?: string;\n err_stack?: string;\n err_cause?: string;\n}\n\nconst MAX_CAUSE_DEPTH = 5;\n\nexport function isErrorLike(v: unknown): v is Error {\n if (v instanceof Error) return true;\n return (\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as { message?: unknown }).message === \"string\" &&\n (\"stack\" in v || \"name\" in v)\n );\n}\n\nfunction errorType(e: Error): string {\n if (e.name && e.name !== \"Error\") return e.name;\n const ctor = (e as { constructor?: { name?: string } }).constructor?.name;\n return ctor && ctor !== \"Object\" ? ctor : \"Error\";\n}\n\nexport function serializeError(err: unknown): ErrFields {\n if (!isErrorLike(err)) {\n if (typeof err === \"string\") return { err_type: \"string\", err_message: err };\n return { err_type: typeof err, err_message: defaultRedactor.json(err) };\n }\n const e = err as Error & { code?: unknown; cause?: unknown };\n const out: ErrFields = { err_type: errorType(e), err_message: String(e.message ?? \"\") };\n if (e.code !== undefined && e.code !== null) out.err_code = String(e.code);\n if (typeof e.stack === \"string\") out.err_stack = e.stack;\n\n const causes: string[] = [];\n let cause = e.cause;\n while (cause !== undefined && cause !== null && causes.length < MAX_CAUSE_DEPTH) {\n if (isErrorLike(cause)) {\n causes.push(`${errorType(cause)}: ${cause.message}`);\n cause = (cause as { cause?: unknown }).cause;\n } else {\n causes.push(defaultRedactor.json(cause));\n cause = undefined;\n }\n }\n if (causes.length > 0) out.err_cause = causes.join(\" <- \");\n return out;\n}\n\nconst logged = globalSingleton(\"logged\", () => new WeakSet<object>());\n\n// Marks an error as already written, so a later boundary (e.g. Next's onRequestError)\n// does not log it a second time.\nexport function markLogged(err: unknown): void {\n if (typeof err === \"object\" && err !== null) logged.add(err);\n}\n\nexport function isLogged(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && logged.has(err);\n}\n","import { isErrorLike, serializeError } from \"./error\";\nimport type { Level } from \"./levels\";\nimport { REDACTED, toSnakeCase, type Redactor } from \"./redact\";\n\nexport { DEFAULT_REDACT_KEYS, toSnakeCase } from \"./redact\";\n\n/** Final per-field hook: return a replacement, or undefined to drop the field. */\nexport type RedactHook = (key: string, value: Primitive) => unknown;\n\nexport type Fields = Record<string, unknown>;\nexport type Primitive = string | number | boolean | null;\nexport type LogRecord = Record<string, Primitive>;\n\nexport interface NormalizeOptions {\n snakeCase: boolean;\n redactor: Redactor;\n hook?: RedactHook;\n}\n\n// Fields the redact hook never sees, so every line keeps its level, message and event.\nconst HOOK_EXEMPT = new Set([\"level\", \"message\", \"event\"]);\n\n// Keys owned by Vector (overwritten or deleted on ingest) or by the logger itself.\nexport const RESERVED_KEYS = new Set([\n \"project\", \"service\", \"vps\", \"version\", \"container_name\", \"container_id\", \"image\", \"stream\",\n \"_timestamp\", \"label\", \"host\", \"source_type\", \"msg\", \"lvl\", \"severity\", \"level\", \"message\",\n]);\n\nexport const MAX_LINE_BYTES = 16000;\nconst MAX_MESSAGE = 500;\nconst MAX_STACK = 4000;\nconst MAX_STRING = 1000;\nconst MAX_DEPTH = 3;\nconst TRUNCATED = \"…[truncated]\";\n\n// Fields kept when a line is too large.\nconst KEEP_ON_SHRINK = new Set([\n \"level\", \"message\", \"event\", \"request_id\", \"trace_id\", \"span_id\", \"job_name\", \"job_id\", \"job_attempt\",\n \"user_id\", \"tenant_id\", \"err_type\", \"err_message\", \"err_code\",\n]);\n\nexport function stripUrl(url: string): string {\n const noQuery = url.split(/[?#]/, 1)[0] ?? \"\";\n return noQuery.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/@\\s]*@/i, \"$1\");\n}\n\nexport function truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max - TRUNCATED.length) + TRUNCATED : s;\n}\n\nfunction isPlainObject(v: unknown): v is Fields {\n if (typeof v !== \"object\" || v === null) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction isUrlKey(key: string): boolean {\n return key === \"http_path\" || key === \"http_url\" || key.endsWith(\"_url\");\n}\n\nfunction flattenInto(out: LogRecord, prefix: string, obj: Fields, depth: number, opts: NormalizeOptions): void {\n for (const [rawKey, value] of Object.entries(obj)) {\n const key = opts.snakeCase ? toSnakeCase(rawKey) : rawKey;\n const full = prefix ? `${prefix}_${key}` : key;\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") continue;\n if (value !== null && (opts.redactor.isSensitive(rawKey) || opts.redactor.isSensitive(full))) {\n out[full] = REDACTED;\n continue;\n }\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n out[full] = value;\n } else if (typeof value === \"number\") {\n out[full] = Number.isFinite(value) ? value : String(value);\n } else if (typeof value === \"bigint\") {\n out[full] = value.toString();\n } else if (value instanceof Date) {\n out[full] = Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n } else if (isErrorLike(value)) {\n out[full] = `${value.name}: ${value.message}`;\n } else if (isPlainObject(value) && depth < MAX_DEPTH - 1) {\n flattenInto(out, full, value, depth + 1, opts);\n } else {\n // Arrays, deep objects, class instances: stringified with sensitive keys redacted.\n out[full] = opts.redactor.json(value);\n }\n }\n}\n\nfunction finalize(key: string, value: Primitive, opts: NormalizeOptions): Primitive {\n if (typeof value !== \"string\") return value;\n const v = opts.redactor.scrub(isUrlKey(key) ? stripUrl(value) : value);\n return truncate(v, key === \"err_stack\" ? MAX_STACK : MAX_STRING);\n}\n\nexport function buildRecord(\n level: Level,\n message: unknown,\n sources: (Fields | undefined)[],\n opts: NormalizeOptions,\n): LogRecord {\n const merged: Fields = {};\n for (const source of sources) if (source) Object.assign(merged, source);\n\n let err: unknown;\n if (merged.err !== undefined && merged.err !== null) {\n err = merged.err;\n delete merged.err;\n } else if (isErrorLike(merged.error)) {\n err = merged.error;\n delete merged.error;\n }\n\n const flat: LogRecord = {};\n flattenInto(flat, \"\", merged, 0, opts);\n if (err !== undefined) Object.assign(flat, serializeError(err));\n\n const text = typeof message === \"string\" ? message : opts.redactor.json(message);\n const out: LogRecord = { level, message: truncate(opts.redactor.scrub(text), MAX_MESSAGE) };\n for (const [k, v] of Object.entries(flat)) {\n const key = RESERVED_KEYS.has(k) ? `app_${k}` : k;\n let value = finalize(key, v, opts);\n if (opts.hook && !HOOK_EXEMPT.has(key)) {\n const replaced = opts.hook(key, value);\n if (replaced === undefined) continue;\n value = typeof replaced === \"object\" && replaced !== null ? opts.redactor.json(replaced) : (replaced as Primitive);\n }\n out[key] = value;\n }\n return out;\n}\n\nfunction byteLength(s: string): number {\n // UTF-8 uses at most 3 bytes per UTF-16 code unit: skip encoding short lines.\n if (s.length * 3 <= MAX_LINE_BYTES) return s.length;\n return new TextEncoder().encode(s).length;\n}\n\nexport function serializeRecord(record: LogRecord): string {\n const line = JSON.stringify(record);\n if (byteLength(line) <= MAX_LINE_BYTES) return line;\n const small: LogRecord = {};\n for (const [k, v] of Object.entries(record)) {\n if (KEEP_ON_SHRINK.has(k) || k.startsWith(\"http_\")) small[k] = v;\n }\n small.log_truncated = true;\n return JSON.stringify(small);\n}\n","// No imports: this module is shared with the edge entry (next-edge).\nexport const REQUEST_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\nexport function newRequestId(): string {\n return globalThis.crypto.randomUUID();\n}\n\nfunction first(header?: string | string[] | null): string | undefined {\n return Array.isArray(header) ? header[0] : (header ?? undefined);\n}\n\nexport function resolveRequestId(header?: string | string[] | null): string {\n const value = first(header);\n return value && REQUEST_ID_RE.test(value) ? value : newRequestId();\n}\n\nexport function parseTraceparent(header?: string | string[] | null): { trace_id: string; span_id: string } | undefined {\n const value = first(header)?.trim().toLowerCase();\n const m = value ? TRACEPARENT_RE.exec(value) : null;\n if (!m) return undefined;\n const [, version, traceId, spanId] = m as unknown as [string, string, string, string];\n if (version === \"ff\" || /^0+$/.test(traceId) || /^0+$/.test(spanId)) return undefined;\n return { trace_id: traceId, span_id: spanId };\n}\n","import { getContext } from \"./context\";\nimport { markLogged, serializeError } from \"./error\";\nimport type { Logger } from \"./logger\";\nimport { stripUrl, type Fields } from \"./normalize\";\nimport { parseTraceparent, resolveRequestId } from \"./request-id\";\n\nexport { newRequestId, parseTraceparent, REQUEST_ID_RE, resolveRequestId } from \"./request-id\";\n\nexport type HeaderSource = Headers | Record<string, string | string[] | undefined>;\n\nfunction header(headers: HeaderSource, name: string): string | string[] | undefined {\n if (typeof (headers as Headers).get === \"function\") return (headers as Headers).get(name) ?? undefined;\n return (headers as Record<string, string | string[] | undefined>)[name];\n}\n\nexport function requestContextFields(headers: HeaderSource): { request_id: string; trace_id?: string; span_id?: string } {\n const out: { request_id: string; trace_id?: string; span_id?: string } = {\n request_id: resolveRequestId(header(headers, \"x-request-id\")),\n };\n const tp = parseTraceparent(header(headers, \"traceparent\"));\n if (tp) Object.assign(out, tp);\n return out;\n}\n\n// Headers to forward to services we own, so their logs share request_id / trace_id.\nexport function propagationHeaders(): Record<string, string> {\n const ctx = getContext();\n const out: Record<string, string> = {};\n if (typeof ctx.request_id === \"string\") out[\"x-request-id\"] = ctx.request_id;\n if (typeof ctx.trace_id === \"string\" && typeof ctx.span_id === \"string\") {\n out.traceparent = `00-${ctx.trace_id}-${ctx.span_id}-01`;\n }\n return out;\n}\n\nexport const DEFAULT_SKIP_PATHS: (string | RegExp)[] = [\n /^\\/(health|healthz|ready|readyz|livez)\\/?$/,\n \"/favicon.ico\",\n /^\\/_next\\/static\\//,\n];\n\nexport interface HttpLogOptions {\n skipPaths?: (string | RegExp)[];\n}\n\nexport interface HttpRequestInfo {\n method: string;\n route?: string;\n path: string;\n status: number;\n duration_ms?: number;\n err?: unknown;\n fields?: Fields;\n}\n\nexport function shouldSkip(method: string, path: string, skipPaths: (string | RegExp)[] = DEFAULT_SKIP_PATHS): boolean {\n if (method.toUpperCase() === \"OPTIONS\") return true;\n const p = stripUrl(path);\n return skipPaths.some((s) => (typeof s === \"string\" ? p === s : s.test(p)));\n}\n\n// Writes the one `http.request` summary line for an inbound request.\nexport function logHttpRequest(log: Logger, info: HttpRequestInfo, opts: HttpLogOptions = {}): void {\n if (shouldSkip(info.method, info.path, opts.skipPaths)) return;\n const level = info.status >= 500 ? \"error\" : info.status >= 400 ? \"warn\" : \"info\";\n const path = stripUrl(info.path);\n const errFields: Fields = {};\n if (info.err !== undefined && info.err !== null) {\n Object.assign(errFields, serializeError(info.err));\n if (info.status < 500) delete errFields.err_stack;\n markLogged(info.err);\n }\n // Route templates keep the message bounded; the raw path would make one message per URL.\n const message = info.route ? `${info.method} ${info.route} ${info.status}` : `${info.method} ${info.status}`;\n log[level](message, {\n ...info.fields,\n event: \"http.request\",\n http_method: info.method,\n http_route: info.route,\n http_path: path,\n http_status: info.status,\n duration_ms: info.duration_ms === undefined ? undefined : Math.round(info.duration_ms),\n ...errFields,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAyB;;;ACAzB,8BAAkC;;;ACE3B,SAAS,gBAAmB,MAAc,MAAkB;AACjE,QAAM,MAAM,uBAAO,IAAI,iBAAiB,IAAI,EAAE;AAC9C,QAAM,IAAI;AACV,MAAI,QAAQ,EAAE,GAAG;AACjB,MAAI,UAAU,QAAW;AACvB,YAAQ,KAAK;AACb,MAAE,GAAG,IAAI;AAAA,EACX;AACA,SAAO;AACT;;;ADCA,IAAM,MAAM,gBAAgB,OAAO,MAAM,IAAI,0CAAgC,CAAC;AAIvE,SAAS,aAAgB,QAAgB,IAAmC;AACjF,QAAM,SAAS,IAAI,SAAS;AAC5B,QAAM,QAAsB,EAAE,QAAQ,EAAE,GAAG,QAAQ,QAAQ,GAAG,OAAO,GAAG,OAAO;AAC/E,SAAO,IAAI,IAAI,OAAO,MAAM,GAAG,KAAK,CAAC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e,KAAK;AAAA,IAC7C,YAAY,CAAC,SAAS;AAAA,EACxB;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/strapi.ts","../src/context.ts","../src/global.ts","../src/redact.ts","../src/error.ts","../src/normalize.ts","../src/request-id.ts","../src/http.ts"],"sourcesContent":["import { Writable } from \"node:stream\";\nimport { currentStore, recordErrorIn, runWithStore } from \"./context\";\nimport { isErrorLike, isLogged, markLogged } from \"./error\";\nimport { logHttpRequest, newRequestId, parseTraceparent, REQUEST_ID_RE, type HttpLogOptions } from \"./http\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\n/** The parts of a Koa/Strapi context the middlewares use. */\nexport interface KoaContextLike {\n method: string;\n url: string;\n status: number;\n state: Record<string, unknown>;\n get(name: string): string;\n set(name: string, value: string): void;\n /** Full matched route template, set by @koa/router (includes router prefixes such as /api). */\n _matchedRoute?: unknown;\n}\n\nexport type KoaMiddleware = (ctx: KoaContextLike, next: () => Promise<unknown>) => Promise<void>;\n\nexport interface StrapiRequestLoggerOptions extends HttpLogOptions {\n log: Logger;\n /**\n * Use a valid incoming x-request-id as request_id. Off by default: the server issues its own\n * id (Strapi apps often use it for audit rows) and records the caller's id as\n * upstream_request_id, which still links the logs of both services.\n */\n trustIncomingRequestId?: boolean;\n /** ctx.state key shared with the app's own correlation middleware. Default \"requestId\". */\n stateKey?: string;\n}\n\nfunction routeOf(ctx: KoaContextLike): string | undefined {\n if (typeof ctx._matchedRoute === \"string\") return ctx._matchedRoute;\n const path = (ctx.state.route as { path?: unknown } | undefined)?.path;\n return typeof path === \"string\" ? path : undefined;\n}\n\n/**\n * Replaces 'strapi::logger' (put it first in config/middlewares): opens the request context and\n * writes one http.request line per request.\n */\nexport function strapiRequestLogger(opts: StrapiRequestLoggerOptions): KoaMiddleware {\n const stateKey = opts.stateKey ?? \"requestId\";\n return async (ctx, next) => {\n const incoming = ctx.get(\"x-request-id\");\n const caller = incoming && REQUEST_ID_RE.test(incoming) ? incoming : undefined;\n const existing = ctx.state[stateKey];\n const requestId =\n typeof existing === \"string\" && existing ? existing : opts.trustIncomingRequestId && caller ? caller : newRequestId();\n // A UUID v4 here is kept by correlation middlewares that only replace invalid ids.\n if (ctx.state[stateKey] === undefined) ctx.state[stateKey] = requestId;\n ctx.set(\"X-Request-ID\", requestId);\n\n const fields: Fields = { request_id: requestId };\n if (caller && caller !== requestId) fields.upstream_request_id = caller;\n const trace = parseTraceparent(ctx.get(\"traceparent\"));\n if (trace) Object.assign(fields, trace);\n\n const start = performance.now();\n await runWithStore(fields, async (store) => {\n let failed = false;\n try {\n await next();\n } catch (err) {\n // Only reached when no error middleware handled it; Koa answers 500.\n failed = true;\n recordErrorIn(store, err);\n throw err;\n } finally {\n logHttpRequest(\n opts.log,\n {\n method: ctx.method,\n route: routeOf(ctx),\n path: ctx.url,\n status: failed ? 500 : ctx.status,\n duration_ms: performance.now() - start,\n err: store.error,\n fields: store.fields,\n },\n opts,\n );\n }\n });\n };\n}\n\n/**\n * Put right after 'strapi::errors'. Records thrown errors on the request's http.request line and\n * marks them, so the copy strapi::errors logs through strapi.log.error is not written twice.\n */\nexport function strapiErrorCapture(): KoaMiddleware {\n return async (_ctx, next) => {\n try {\n await next();\n } catch (err) {\n const store = currentStore();\n if (store) recordErrorIn(store, err);\n markLogged(err);\n throw err;\n }\n };\n}\n\nconst LEVELS: Record<string, Level> = {\n error: \"error\",\n warn: \"warn\",\n info: \"info\",\n http: \"debug\",\n verbose: \"debug\",\n debug: \"debug\",\n silly: \"trace\",\n};\n\nconst META_SKIP = new Set([\"level\", \"message\", \"stack\"]);\n\nfunction forward(log: Logger, info: Record<string, unknown>): void {\n // Already carried by the request's http.request line (see strapiErrorCapture).\n if (isErrorLike(info) && isLogged(info)) return;\n const level = LEVELS[String(info.level)] ?? \"info\";\n const fields: Fields = {};\n for (const [key, value] of Object.entries(info)) if (!META_SKIP.has(key)) fields[key] = value;\n\n let message: unknown = info.message;\n if (isErrorLike(info)) {\n fields.err = info;\n } else if (isErrorLike(message)) {\n if (isLogged(message)) return;\n fields.err = message;\n message = message.message;\n } else if (typeof info.stack === \"string\") {\n fields.err_stack = info.stack;\n }\n if ((level === \"warn\" || level === \"error\") && fields.event === undefined) fields.event = \"strapi.log\";\n log[level](typeof message === \"string\" ? message : String(message ?? \"\"), fields);\n}\n\n/**\n * Winston configuration for Strapi's config/logger.ts: every strapi.log.* call (app code and\n * framework) becomes a contract JSON line with the request context. Level filtering is left to\n * the logger (LOG_LEVEL).\n */\nexport function strapiLoggerConfig(log: Logger) {\n // The winston logger that pipes into this transport; its level can change at runtime\n // (Strapi's data export/import commands set it to \"error\").\n let parent: { level?: string; levels?: Record<string, number> } | undefined;\n const allowed = (info: Record<string, unknown>): boolean => {\n const rank = parent?.levels?.[String(info.level)];\n const max = parent?.level === undefined ? undefined : parent.levels?.[parent.level];\n return rank === undefined || max === undefined || rank <= max;\n };\n const transport = new Writable({\n objectMode: true,\n write(info: Record<string, unknown>, _encoding, callback) {\n try {\n if (allowed(info)) forward(log, info);\n } finally {\n callback();\n }\n },\n });\n transport.on(\"pipe\", (source: unknown) => {\n parent = source as typeof parent;\n });\n // winston requires a `log(info, callback)` method on stream transports; writes go through write().\n Object.assign(transport, {\n log(info: Record<string, unknown>, callback: () => void) {\n forward(log, info);\n callback();\n },\n });\n return {\n level: \"silly\",\n // Identity format: replaces Strapi's prettyPrint so the transport receives raw info objects.\n format: { transform: <T>(info: T): T => info },\n transports: [transport],\n };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { globalSingleton } from \"./global\";\nimport type { Fields } from \"./normalize\";\n\nexport interface ContextStore {\n fields: Fields;\n error?: unknown;\n /** Route template captured while the router still knew it (Express error path). */\n route?: string;\n parent?: ContextStore;\n}\n\nconst als = globalSingleton(\"als\", () => new AsyncLocalStorage<ContextStore>());\n\nexport const STORE_KEY: symbol = Symbol.for(\"@tanngo11/log.store\");\n\nexport function runWithStore<T>(fields: Fields, fn: (store: ContextStore) => T): T {\n const parent = als.getStore();\n const store: ContextStore = { fields: { ...parent?.fields, ...fields }, parent };\n return als.run(store, () => fn(store));\n}\n\nexport function withContext<T>(fields: Fields, fn: () => T): T {\n return runWithStore(fields, () => fn());\n}\n\nexport function currentStore(): ContextStore | undefined {\n return als.getStore();\n}\n\nexport function getContext(): Fields {\n return als.getStore()?.fields ?? {};\n}\n\n// Applies to the current context and every enclosing one, so a field added inside a nested\n// withContext/runJob still reaches the request's http.request line.\nexport function addContext(fields: Fields): void {\n for (let s = als.getStore(); s; s = s.parent) Object.assign(s.fields, fields);\n}\n\n// Sets the error on the store and on enclosing stores that have none yet.\nexport function recordErrorIn(store: ContextStore, err: unknown): void {\n store.error = err;\n for (let s = store.parent; s; s = s.parent) if (s.error === undefined) s.error = err;\n}\n\n// Marks the error that the current request/job summary line should carry. Does not write a line.\nexport function recordError(err: unknown): void {\n const store = als.getStore();\n if (store) recordErrorIn(store, err);\n}\n\nexport function attachStore(target: object, store: ContextStore): void {\n (target as Record<symbol, ContextStore>)[STORE_KEY] = store;\n}\n\nexport function storeOf(target: unknown): ContextStore | undefined {\n if (typeof target !== \"object\" || target === null) return undefined;\n return (target as Record<symbol, ContextStore | undefined>)[STORE_KEY];\n}\n","// Singletons shared by every copy of this package loaded in the process (ESM and CJS builds,\n// or duplicated installs), so context and dedupe state never split.\nexport function globalSingleton<T>(name: string, make: () => T): T {\n const key = Symbol.for(`@tanngo11/log.${name}`);\n const g = globalThis as unknown as Record<symbol, T | undefined>;\n let value = g[key];\n if (value === undefined) {\n value = make();\n g[key] = value;\n }\n return value;\n}\n","// Redaction shared by the logger and the error serializer. The collector redacts again,\n// but it cannot see secrets inside JSON-encoded strings, so the app side must catch them.\n\nexport const DEFAULT_REDACT_KEYS = [\n \"password\", \"passwd\", \"pwd\", \"passphrase\", \"secret\", \"client_secret\",\n \"token\", \"access_token\", \"refresh_token\", \"id_token\", \"auth_token\",\n \"api_key\", \"apikey\", \"access_key\", \"secret_key\", \"private_key\",\n \"authorization\", \"cookie\", \"set_cookie\", \"session_id\", \"sessionid\",\n \"credential\", \"credentials\", \"dsn\", \"connection_string\", \"conn_string\", \"jwt\", \"bearer\",\n];\n\n/** Opt-in value patterns for `redactValues`. Not on by default: they can hit ordinary numbers. */\nexport const REDACT_PATTERNS = {\n /** Vietnamese mobile numbers: 0912345678, +84912345678, 84912345678. */\n phoneVN: /(?<![\\d+])(?:\\+?84|0)[35789]\\d{8}(?!\\d)/g,\n /** Visa, Mastercard, Amex, Discover-like card numbers, with optional spaces or dashes. */\n paymentCard: /(?<!\\d)(?:4\\d{3}|5[1-5]\\d{2}|2[2-7]\\d{2}|3[47]\\d{2}|6(?:011|5\\d{2}))(?:[ -]?\\d{4}){2}[ -]?\\d{1,4}(?!\\d)/g,\n /** IPv4 addresses. */\n ipv4: /(?<![\\d.])(?:\\d{1,3}\\.){3}\\d{1,3}(?![\\d.])/g,\n} as const;\n\n// Keys that only describe a secret (count, type, timestamps, flags) stay readable.\nconst SAFE_SUFFIXES = [\"_count\", \"_type\", \"_length\", \"_expires_at\", \"_expires_in\", \"_ttl\", \"_at\", \"_ms\", \"_enabled\"];\n\nexport const REDACTED = \"[REDACTED]\";\n\nexport function toSnakeCase(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/[^A-Za-z0-9_]+/g, \"_\")\n .toLowerCase();\n}\n\nconst URL_CREDENTIALS_RE = /([a-z][a-z0-9+.-]*:\\/\\/)[^\\s/@:\"']+:[^\\s/@\"']+@/gi;\nconst BEARER_RE = /\\bBearer\\s+[A-Za-z0-9._~+/=-]+/gi;\nconst JWT_RE = /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+/g;\nconst EMAIL_RE = /[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,})/g;\n\nexport type KeyPattern = string | RegExp;\n\nexport interface RedactorOptions {\n /** Extra sensitive keys: names (matched like the defaults) or patterns tested on the snake_case key. */\n keys?: readonly KeyPattern[];\n /** Extra value patterns; every match inside any string becomes [REDACTED]. */\n values?: readonly RegExp[];\n}\n\nexport interface Redactor {\n isSensitive(key: string): boolean;\n /** Masks secrets and emails that appear inside free text. */\n scrub(s: string): string;\n /** JSON.stringify that redacts sensitive keys at any depth and never throws. */\n json(value: unknown): string;\n}\n\nfunction globalize(re: RegExp): RegExp {\n return re.flags.includes(\"g\") ? new RegExp(re.source, re.flags) : new RegExp(re.source, `${re.flags}g`);\n}\n\nexport function createRedactor(opts: RedactorOptions = {}): Redactor {\n const words = [...DEFAULT_REDACT_KEYS];\n const keyPatterns: RegExp[] = [];\n for (const k of opts.keys ?? []) {\n if (typeof k === \"string\") words.push(toSnakeCase(k));\n else keyPatterns.push(new RegExp(k.source, k.flags.replace(\"g\", \"\")));\n }\n const valuePatterns = (opts.values ?? []).map(globalize);\n\n const isSensitive = (key: string): boolean => {\n const k = toSnakeCase(key);\n if (keyPatterns.some((re) => re.test(k))) return true;\n if (!words.includes(k) && SAFE_SUFFIXES.some((s) => k.endsWith(s))) return false;\n return words.some((w) => k === w || k.startsWith(`${w}_`) || k.endsWith(`_${w}`) || k.includes(`_${w}_`));\n };\n\n const scrub = (s: string): string => {\n let out = s\n .replace(URL_CREDENTIALS_RE, `$1${REDACTED}@`)\n .replace(BEARER_RE, `Bearer ${REDACTED}`)\n .replace(JWT_RE, \"[REDACTED_JWT]\")\n .replace(EMAIL_RE, \"***@$1\");\n for (const re of valuePatterns) out = out.replace(re, REDACTED);\n return out;\n };\n\n const json = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n try {\n const text = JSON.stringify(value, (key, val: unknown) => {\n if (key && val !== null && val !== undefined && isSensitive(key)) return REDACTED;\n if (typeof val === \"bigint\") return val.toString();\n if (val instanceof Error) return { name: val.name, message: val.message };\n return val;\n });\n return text ?? String(value);\n } catch {\n return String(value);\n }\n };\n\n return { isSensitive, scrub, json };\n}\n\nexport const defaultRedactor: Redactor = createRedactor();\n","import { globalSingleton } from \"./global\";\nimport { defaultRedactor } from \"./redact\";\n\nexport interface ErrFields {\n err_type?: string;\n err_message?: string;\n err_code?: string;\n err_stack?: string;\n err_cause?: string;\n}\n\nconst MAX_CAUSE_DEPTH = 5;\n\nexport function isErrorLike(v: unknown): v is Error {\n if (v instanceof Error) return true;\n return (\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as { message?: unknown }).message === \"string\" &&\n (\"stack\" in v || \"name\" in v)\n );\n}\n\nfunction errorType(e: Error): string {\n if (e.name && e.name !== \"Error\") return e.name;\n const ctor = (e as { constructor?: { name?: string } }).constructor?.name;\n return ctor && ctor !== \"Object\" ? ctor : \"Error\";\n}\n\nexport function serializeError(err: unknown): ErrFields {\n if (!isErrorLike(err)) {\n if (typeof err === \"string\") return { err_type: \"string\", err_message: err };\n return { err_type: typeof err, err_message: defaultRedactor.json(err) };\n }\n const e = err as Error & { code?: unknown; cause?: unknown };\n const out: ErrFields = { err_type: errorType(e), err_message: String(e.message ?? \"\") };\n if (e.code !== undefined && e.code !== null) out.err_code = String(e.code);\n if (typeof e.stack === \"string\") out.err_stack = e.stack;\n\n const causes: string[] = [];\n let cause = e.cause;\n while (cause !== undefined && cause !== null && causes.length < MAX_CAUSE_DEPTH) {\n if (isErrorLike(cause)) {\n causes.push(`${errorType(cause)}: ${cause.message}`);\n cause = (cause as { cause?: unknown }).cause;\n } else {\n causes.push(defaultRedactor.json(cause));\n cause = undefined;\n }\n }\n if (causes.length > 0) out.err_cause = causes.join(\" <- \");\n return out;\n}\n\nconst logged = globalSingleton(\"logged\", () => new WeakSet<object>());\n\n// Marks an error as already written, so a later boundary (e.g. Next's onRequestError)\n// does not log it a second time.\nexport function markLogged(err: unknown): void {\n if (typeof err === \"object\" && err !== null) logged.add(err);\n}\n\nexport function isLogged(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && logged.has(err);\n}\n","import { isErrorLike, serializeError } from \"./error\";\nimport type { Level } from \"./levels\";\nimport { REDACTED, toSnakeCase, type Redactor } from \"./redact\";\n\nexport { DEFAULT_REDACT_KEYS, toSnakeCase } from \"./redact\";\n\n/** Final per-field hook: return a replacement, or undefined to drop the field. */\nexport type RedactHook = (key: string, value: Primitive) => unknown;\n\nexport type Fields = Record<string, unknown>;\nexport type Primitive = string | number | boolean | null;\nexport type LogRecord = Record<string, Primitive>;\n\nexport interface NormalizeOptions {\n snakeCase: boolean;\n redactor: Redactor;\n hook?: RedactHook;\n}\n\n// Fields the redact hook never sees, so every line keeps its level, message and event.\nconst HOOK_EXEMPT = new Set([\"level\", \"message\", \"event\"]);\n\n// Keys owned by Vector (overwritten or deleted on ingest) or by the logger itself.\nexport const RESERVED_KEYS = new Set([\n \"project\", \"service\", \"vps\", \"version\", \"container_name\", \"container_id\", \"image\", \"stream\",\n \"_timestamp\", \"label\", \"host\", \"source_type\", \"msg\", \"lvl\", \"severity\", \"level\", \"message\",\n]);\n\nexport const MAX_LINE_BYTES = 16000;\nconst MAX_MESSAGE = 500;\nconst MAX_STACK = 4000;\nconst MAX_STRING = 1000;\nconst MAX_DEPTH = 3;\nconst TRUNCATED = \"…[truncated]\";\n\n// Fields kept when a line is too large.\nconst KEEP_ON_SHRINK = new Set([\n \"level\", \"message\", \"event\", \"request_id\", \"trace_id\", \"span_id\", \"job_name\", \"job_id\", \"job_attempt\",\n \"user_id\", \"tenant_id\", \"err_type\", \"err_message\", \"err_code\",\n]);\n\nexport function stripUrl(url: string): string {\n const noQuery = url.split(/[?#]/, 1)[0] ?? \"\";\n return noQuery.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/@\\s]*@/i, \"$1\");\n}\n\nexport function truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max - TRUNCATED.length) + TRUNCATED : s;\n}\n\nfunction isPlainObject(v: unknown): v is Fields {\n if (typeof v !== \"object\" || v === null) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction isUrlKey(key: string): boolean {\n return key === \"http_path\" || key === \"http_url\" || key.endsWith(\"_url\");\n}\n\nfunction flattenInto(out: LogRecord, prefix: string, obj: Fields, depth: number, opts: NormalizeOptions): void {\n for (const [rawKey, value] of Object.entries(obj)) {\n const key = opts.snakeCase ? toSnakeCase(rawKey) : rawKey;\n const full = prefix ? `${prefix}_${key}` : key;\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") continue;\n if (value !== null && (opts.redactor.isSensitive(rawKey) || opts.redactor.isSensitive(full))) {\n out[full] = REDACTED;\n continue;\n }\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n out[full] = value;\n } else if (typeof value === \"number\") {\n out[full] = Number.isFinite(value) ? value : String(value);\n } else if (typeof value === \"bigint\") {\n out[full] = value.toString();\n } else if (value instanceof Date) {\n out[full] = Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n } else if (isErrorLike(value)) {\n out[full] = `${value.name}: ${value.message}`;\n } else if (isPlainObject(value) && depth < MAX_DEPTH - 1) {\n flattenInto(out, full, value, depth + 1, opts);\n } else {\n // Arrays, deep objects, class instances: stringified with sensitive keys redacted.\n out[full] = opts.redactor.json(value);\n }\n }\n}\n\nfunction finalize(key: string, value: Primitive, opts: NormalizeOptions): Primitive {\n if (typeof value !== \"string\") return value;\n const v = opts.redactor.scrub(isUrlKey(key) ? stripUrl(value) : value);\n return truncate(v, key === \"err_stack\" ? MAX_STACK : MAX_STRING);\n}\n\nexport function buildRecord(\n level: Level,\n message: unknown,\n sources: (Fields | undefined)[],\n opts: NormalizeOptions,\n): LogRecord {\n const merged: Fields = {};\n for (const source of sources) if (source) Object.assign(merged, source);\n\n let err: unknown;\n if (merged.err !== undefined && merged.err !== null) {\n err = merged.err;\n delete merged.err;\n } else if (isErrorLike(merged.error)) {\n err = merged.error;\n delete merged.error;\n }\n\n const flat: LogRecord = {};\n flattenInto(flat, \"\", merged, 0, opts);\n if (err !== undefined) Object.assign(flat, serializeError(err));\n\n const text = typeof message === \"string\" ? message : opts.redactor.json(message);\n const out: LogRecord = { level, message: truncate(opts.redactor.scrub(text), MAX_MESSAGE) };\n for (const [k, v] of Object.entries(flat)) {\n const key = RESERVED_KEYS.has(k) ? `app_${k}` : k;\n let value = finalize(key, v, opts);\n if (opts.hook && !HOOK_EXEMPT.has(key)) {\n const replaced = opts.hook(key, value);\n if (replaced === undefined) continue;\n value = typeof replaced === \"object\" && replaced !== null ? opts.redactor.json(replaced) : (replaced as Primitive);\n }\n out[key] = value;\n }\n return out;\n}\n\nfunction byteLength(s: string): number {\n // UTF-8 uses at most 3 bytes per UTF-16 code unit: skip encoding short lines.\n if (s.length * 3 <= MAX_LINE_BYTES) return s.length;\n return new TextEncoder().encode(s).length;\n}\n\nexport function serializeRecord(record: LogRecord): string {\n const line = JSON.stringify(record);\n if (byteLength(line) <= MAX_LINE_BYTES) return line;\n const small: LogRecord = {};\n for (const [k, v] of Object.entries(record)) {\n if (KEEP_ON_SHRINK.has(k) || k.startsWith(\"http_\")) small[k] = v;\n }\n small.log_truncated = true;\n return JSON.stringify(small);\n}\n","// No imports: this module is shared with the edge entry (next-edge).\nexport const REQUEST_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;\nconst TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\nexport function newRequestId(): string {\n return globalThis.crypto.randomUUID();\n}\n\nfunction first(header?: string | string[] | null): string | undefined {\n return Array.isArray(header) ? header[0] : (header ?? undefined);\n}\n\nexport function resolveRequestId(header?: string | string[] | null): string {\n const value = first(header);\n return value && REQUEST_ID_RE.test(value) ? value : newRequestId();\n}\n\nexport function parseTraceparent(header?: string | string[] | null): { trace_id: string; span_id: string } | undefined {\n const value = first(header)?.trim().toLowerCase();\n const m = value ? TRACEPARENT_RE.exec(value) : null;\n if (!m) return undefined;\n const [, version, traceId, spanId] = m as unknown as [string, string, string, string];\n if (version === \"ff\" || /^0+$/.test(traceId) || /^0+$/.test(spanId)) return undefined;\n return { trace_id: traceId, span_id: spanId };\n}\n","import { getContext } from \"./context\";\nimport { markLogged, serializeError } from \"./error\";\nimport type { Logger } from \"./logger\";\nimport { stripUrl, type Fields } from \"./normalize\";\nimport { parseTraceparent, resolveRequestId } from \"./request-id\";\n\nexport { newRequestId, parseTraceparent, REQUEST_ID_RE, resolveRequestId } from \"./request-id\";\n\nexport type HeaderSource = Headers | Record<string, string | string[] | undefined>;\n\nfunction header(headers: HeaderSource, name: string): string | string[] | undefined {\n if (typeof (headers as Headers).get === \"function\") return (headers as Headers).get(name) ?? undefined;\n return (headers as Record<string, string | string[] | undefined>)[name];\n}\n\nexport function requestContextFields(headers: HeaderSource): { request_id: string; trace_id?: string; span_id?: string } {\n const out: { request_id: string; trace_id?: string; span_id?: string } = {\n request_id: resolveRequestId(header(headers, \"x-request-id\")),\n };\n const tp = parseTraceparent(header(headers, \"traceparent\"));\n if (tp) Object.assign(out, tp);\n return out;\n}\n\n// Headers to forward to services we own, so their logs share request_id / trace_id.\nexport function propagationHeaders(): Record<string, string> {\n const ctx = getContext();\n const out: Record<string, string> = {};\n if (typeof ctx.request_id === \"string\") out[\"x-request-id\"] = ctx.request_id;\n if (typeof ctx.trace_id === \"string\" && typeof ctx.span_id === \"string\") {\n out.traceparent = `00-${ctx.trace_id}-${ctx.span_id}-01`;\n }\n return out;\n}\n\nexport const DEFAULT_SKIP_PATHS: (string | RegExp)[] = [\n /^\\/(health|healthz|ready|readyz|livez)\\/?$/,\n \"/favicon.ico\",\n /^\\/_next\\/static\\//,\n];\n\nexport interface HttpLogOptions {\n skipPaths?: (string | RegExp)[];\n}\n\nexport interface HttpRequestInfo {\n method: string;\n route?: string;\n path: string;\n status: number;\n duration_ms?: number;\n err?: unknown;\n fields?: Fields;\n}\n\nexport function shouldSkip(method: string, path: string, skipPaths: (string | RegExp)[] = DEFAULT_SKIP_PATHS): boolean {\n if (method.toUpperCase() === \"OPTIONS\") return true;\n const p = stripUrl(path);\n return skipPaths.some((s) => (typeof s === \"string\" ? p === s : s.test(p)));\n}\n\n// Writes the one `http.request` summary line for an inbound request.\nexport function logHttpRequest(log: Logger, info: HttpRequestInfo, opts: HttpLogOptions = {}): void {\n if (shouldSkip(info.method, info.path, opts.skipPaths)) return;\n const level = info.status >= 500 ? \"error\" : info.status >= 400 ? \"warn\" : \"info\";\n const path = stripUrl(info.path);\n const errFields: Fields = {};\n if (info.err !== undefined && info.err !== null) {\n Object.assign(errFields, serializeError(info.err));\n if (info.status < 500) delete errFields.err_stack;\n markLogged(info.err);\n }\n // Route templates keep the message bounded; the raw path would make one message per URL.\n const message = info.route ? `${info.method} ${info.route} ${info.status}` : `${info.method} ${info.status}`;\n log[level](message, {\n ...info.fields,\n event: \"http.request\",\n http_method: info.method,\n http_route: info.route,\n http_path: path,\n http_status: info.status,\n duration_ms: info.duration_ms === undefined ? undefined : Math.round(info.duration_ms),\n ...errFields,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAyB;;;ACAzB,8BAAkC;;;ACE3B,SAAS,gBAAmB,MAAc,MAAkB;AACjE,QAAM,MAAM,uBAAO,IAAI,iBAAiB,IAAI,EAAE;AAC9C,QAAM,IAAI;AACV,MAAI,QAAQ,EAAE,GAAG;AACjB,MAAI,UAAU,QAAW;AACvB,YAAQ,KAAK;AACb,MAAE,GAAG,IAAI;AAAA,EACX;AACA,SAAO;AACT;;;ADCA,IAAM,MAAM,gBAAgB,OAAO,MAAM,IAAI,0CAAgC,CAAC;AAIvE,SAAS,aAAgB,QAAgB,IAAmC;AACjF,QAAM,SAAS,IAAI,SAAS;AAC5B,QAAM,QAAsB,EAAE,QAAQ,EAAE,GAAG,QAAQ,QAAQ,GAAG,OAAO,GAAG,OAAO;AAC/E,SAAO,IAAI,IAAI,OAAO,MAAM,GAAG,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,MACtC,UAAE;AACA,iBAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF,CAAC;AACD,YAAU,GAAG,QAAQ,CAAC,WAAoB;AACxC,aAAS;AAAA,EACX,CAAC;AAED,SAAO,OAAO,WAAW;AAAA,IACvB,IAAI,MAA+B,UAAsB;AACvD,cAAQ,KAAK,IAAI;AACjB,eAAS;AAAA,IACX;AAAA,EACF,CAAC;AACD,SAAO;AAAA,IACL,OAAO;AAAA;AAAA,IAEP,QAAQ,EAAE,WAAW,CAAI,SAAe,KAAK;AAAA,IAC7C,YAAY,CAAC,SAAS;AAAA,EACxB;AACF;","names":[]}
package/dist/strapi.js CHANGED
@@ -103,16 +103,25 @@ function forward(log, info) {
103
103
  log[level](typeof message === "string" ? message : String(message ?? ""), fields);
104
104
  }
105
105
  function strapiLoggerConfig(log) {
106
+ let parent;
107
+ const allowed = (info) => {
108
+ const rank = parent?.levels?.[String(info.level)];
109
+ const max = parent?.level === void 0 ? void 0 : parent.levels?.[parent.level];
110
+ return rank === void 0 || max === void 0 || rank <= max;
111
+ };
106
112
  const transport = new Writable({
107
113
  objectMode: true,
108
114
  write(info, _encoding, callback) {
109
115
  try {
110
- forward(log, info);
116
+ if (allowed(info)) forward(log, info);
111
117
  } finally {
112
118
  callback();
113
119
  }
114
120
  }
115
121
  });
122
+ transport.on("pipe", (source) => {
123
+ parent = source;
124
+ });
116
125
  Object.assign(transport, {
117
126
  log(info, callback) {
118
127
  forward(log, info);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/strapi.ts"],"sourcesContent":["import { Writable } from \"node:stream\";\nimport { currentStore, recordErrorIn, runWithStore } from \"./context\";\nimport { isErrorLike, isLogged, markLogged } from \"./error\";\nimport { logHttpRequest, newRequestId, parseTraceparent, REQUEST_ID_RE, type HttpLogOptions } from \"./http\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\n/** The parts of a Koa/Strapi context the middlewares use. */\nexport interface KoaContextLike {\n method: string;\n url: string;\n status: number;\n state: Record<string, unknown>;\n get(name: string): string;\n set(name: string, value: string): void;\n /** Full matched route template, set by @koa/router (includes router prefixes such as /api). */\n _matchedRoute?: unknown;\n}\n\nexport type KoaMiddleware = (ctx: KoaContextLike, next: () => Promise<unknown>) => Promise<void>;\n\nexport interface StrapiRequestLoggerOptions extends HttpLogOptions {\n log: Logger;\n /**\n * Use a valid incoming x-request-id as request_id. Off by default: the server issues its own\n * id (Strapi apps often use it for audit rows) and records the caller's id as\n * upstream_request_id, which still links the logs of both services.\n */\n trustIncomingRequestId?: boolean;\n /** ctx.state key shared with the app's own correlation middleware. Default \"requestId\". */\n stateKey?: string;\n}\n\nfunction routeOf(ctx: KoaContextLike): string | undefined {\n if (typeof ctx._matchedRoute === \"string\") return ctx._matchedRoute;\n const path = (ctx.state.route as { path?: unknown } | undefined)?.path;\n return typeof path === \"string\" ? path : undefined;\n}\n\n/**\n * Replaces 'strapi::logger' (put it first in config/middlewares): opens the request context and\n * writes one http.request line per request.\n */\nexport function strapiRequestLogger(opts: StrapiRequestLoggerOptions): KoaMiddleware {\n const stateKey = opts.stateKey ?? \"requestId\";\n return async (ctx, next) => {\n const incoming = ctx.get(\"x-request-id\");\n const caller = incoming && REQUEST_ID_RE.test(incoming) ? incoming : undefined;\n const existing = ctx.state[stateKey];\n const requestId =\n typeof existing === \"string\" && existing ? existing : opts.trustIncomingRequestId && caller ? caller : newRequestId();\n // A UUID v4 here is kept by correlation middlewares that only replace invalid ids.\n if (ctx.state[stateKey] === undefined) ctx.state[stateKey] = requestId;\n ctx.set(\"X-Request-ID\", requestId);\n\n const fields: Fields = { request_id: requestId };\n if (caller && caller !== requestId) fields.upstream_request_id = caller;\n const trace = parseTraceparent(ctx.get(\"traceparent\"));\n if (trace) Object.assign(fields, trace);\n\n const start = performance.now();\n await runWithStore(fields, async (store) => {\n let failed = false;\n try {\n await next();\n } catch (err) {\n // Only reached when no error middleware handled it; Koa answers 500.\n failed = true;\n recordErrorIn(store, err);\n throw err;\n } finally {\n logHttpRequest(\n opts.log,\n {\n method: ctx.method,\n route: routeOf(ctx),\n path: ctx.url,\n status: failed ? 500 : ctx.status,\n duration_ms: performance.now() - start,\n err: store.error,\n fields: store.fields,\n },\n opts,\n );\n }\n });\n };\n}\n\n/**\n * Put right after 'strapi::errors'. Records thrown errors on the request's http.request line and\n * marks them, so the copy strapi::errors logs through strapi.log.error is not written twice.\n */\nexport function strapiErrorCapture(): KoaMiddleware {\n return async (_ctx, next) => {\n try {\n await next();\n } catch (err) {\n const store = currentStore();\n if (store) recordErrorIn(store, err);\n markLogged(err);\n throw err;\n }\n };\n}\n\nconst LEVELS: Record<string, Level> = {\n error: \"error\",\n warn: \"warn\",\n info: \"info\",\n http: \"debug\",\n verbose: \"debug\",\n debug: \"debug\",\n silly: \"trace\",\n};\n\nconst META_SKIP = new Set([\"level\", \"message\", \"stack\"]);\n\nfunction forward(log: Logger, info: Record<string, unknown>): void {\n // Already carried by the request's http.request line (see strapiErrorCapture).\n if (isErrorLike(info) && isLogged(info)) return;\n const level = LEVELS[String(info.level)] ?? \"info\";\n const fields: Fields = {};\n for (const [key, value] of Object.entries(info)) if (!META_SKIP.has(key)) fields[key] = value;\n\n let message: unknown = info.message;\n if (isErrorLike(info)) {\n fields.err = info;\n } else if (isErrorLike(message)) {\n if (isLogged(message)) return;\n fields.err = message;\n message = message.message;\n } else if (typeof info.stack === \"string\") {\n fields.err_stack = info.stack;\n }\n if ((level === \"warn\" || level === \"error\") && fields.event === undefined) fields.event = \"strapi.log\";\n log[level](typeof message === \"string\" ? message : String(message ?? \"\"), fields);\n}\n\n/**\n * Winston configuration for Strapi's config/logger.ts: every strapi.log.* call (app code and\n * framework) becomes a contract JSON line with the request context. Level filtering is left to\n * the logger (LOG_LEVEL).\n */\nexport function strapiLoggerConfig(log: Logger) {\n const transport = new Writable({\n objectMode: true,\n write(info: Record<string, unknown>, _encoding, callback) {\n try {\n forward(log, info);\n } finally {\n callback();\n }\n },\n });\n // winston requires a `log(info, callback)` method on stream transports; writes go through write().\n Object.assign(transport, {\n log(info: Record<string, unknown>, callback: () => void) {\n forward(log, info);\n callback();\n },\n });\n return {\n level: \"silly\",\n // Identity format: replaces Strapi's prettyPrint so the transport receives raw info objects.\n format: { transform: <T>(info: T): T => info },\n transports: [transport],\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AAkCzB,SAAS,QAAQ,KAAyC;AACxD,MAAI,OAAO,IAAI,kBAAkB,SAAU,QAAO,IAAI;AACtD,QAAM,OAAQ,IAAI,MAAM,OAA0C;AAClE,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;AAMO,SAAS,oBAAoB,MAAiD;AACnF,QAAM,WAAW,KAAK,YAAY;AAClC,SAAO,OAAO,KAAK,SAAS;AAC1B,UAAM,WAAW,IAAI,IAAI,cAAc;AACvC,UAAM,SAAS,YAAY,cAAc,KAAK,QAAQ,IAAI,WAAW;AACrE,UAAM,WAAW,IAAI,MAAM,QAAQ;AACnC,UAAM,YACJ,OAAO,aAAa,YAAY,WAAW,WAAW,KAAK,0BAA0B,SAAS,SAAS,aAAa;AAEtH,QAAI,IAAI,MAAM,QAAQ,MAAM,OAAW,KAAI,MAAM,QAAQ,IAAI;AAC7D,QAAI,IAAI,gBAAgB,SAAS;AAEjC,UAAM,SAAiB,EAAE,YAAY,UAAU;AAC/C,QAAI,UAAU,WAAW,UAAW,QAAO,sBAAsB;AACjE,UAAM,QAAQ,iBAAiB,IAAI,IAAI,aAAa,CAAC;AACrD,QAAI,MAAO,QAAO,OAAO,QAAQ,KAAK;AAEtC,UAAM,QAAQ,YAAY,IAAI;AAC9B,UAAM,aAAa,QAAQ,OAAO,UAAU;AAC1C,UAAI,SAAS;AACb,UAAI;AACF,cAAM,KAAK;AAAA,MACb,SAAS,KAAK;AAEZ,iBAAS;AACT,sBAAc,OAAO,GAAG;AACxB,cAAM;AAAA,MACR,UAAE;AACA;AAAA,UACE,KAAK;AA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AAK;AAAA,EAC1B;AACA,OAAK,UAAU,UAAU,UAAU,YAAY,OAAO,UAAU,OAAW,QAAO,QAAQ;AAC1F,MAAI,KAAK,EAAE,OAAO,YAAY,WAAW,UAAU,OAAO,WAAW,EAAE,GAAG,MAAM;AAClF;AAOO,SAAS,mBAAmB,KAAa;AAC9C,QAAM,YAAY,IAAI,SAAS;AAAA,IAC7B,YAAY;AAAA,IACZ,MAAM,MAA+B,WAAW,UAAU;AACxD,UAAI;AACF,gBAAQ,KAAK,IAAI;AAAA,MACnB,UAAE;AACA,iBAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF,CAAC;AAED,SAAO,OAAO,WAAW;AAAA,IACvB,IAAI,MAA+B,UAAsB;AACvD,cAAQ,KAAK,IAAI;AACjB,eAAS;AAAA,IACX;AAAA,EACF,CAAC;AACD,SAAO;AAAA,IACL,OAAO;AAAA;AAAA,IAEP,QAAQ,EAAE,WAAW,CAAI,SAAe,KAAK;AAAA,IAC7C,YAAY,CAAC,SAAS;AAAA,EACxB;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/strapi.ts"],"sourcesContent":["import { Writable } from \"node:stream\";\nimport { currentStore, recordErrorIn, runWithStore } from \"./context\";\nimport { isErrorLike, isLogged, markLogged } from \"./error\";\nimport { logHttpRequest, newRequestId, parseTraceparent, REQUEST_ID_RE, type HttpLogOptions } from \"./http\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\n/** The parts of a Koa/Strapi context the middlewares use. */\nexport interface KoaContextLike {\n method: string;\n url: string;\n status: number;\n state: Record<string, unknown>;\n get(name: string): string;\n set(name: string, value: string): void;\n /** Full matched route template, set by @koa/router (includes router prefixes such as /api). */\n _matchedRoute?: unknown;\n}\n\nexport type KoaMiddleware = (ctx: KoaContextLike, next: () => Promise<unknown>) => Promise<void>;\n\nexport interface StrapiRequestLoggerOptions extends HttpLogOptions {\n log: Logger;\n /**\n * Use a valid incoming x-request-id as request_id. Off by default: the server issues its own\n * id (Strapi apps often use it for audit rows) and records the caller's id as\n * upstream_request_id, which still links the logs of both services.\n */\n trustIncomingRequestId?: boolean;\n /** ctx.state key shared with the app's own correlation middleware. Default \"requestId\". */\n stateKey?: string;\n}\n\nfunction routeOf(ctx: KoaContextLike): string | undefined {\n if (typeof ctx._matchedRoute === \"string\") return ctx._matchedRoute;\n const path = (ctx.state.route as { path?: unknown } | undefined)?.path;\n return typeof path === \"string\" ? path : undefined;\n}\n\n/**\n * Replaces 'strapi::logger' (put it first in config/middlewares): opens the request context and\n * writes one http.request line per request.\n */\nexport function strapiRequestLogger(opts: StrapiRequestLoggerOptions): KoaMiddleware {\n const stateKey = opts.stateKey ?? \"requestId\";\n return async (ctx, next) => {\n const incoming = ctx.get(\"x-request-id\");\n const caller = incoming && REQUEST_ID_RE.test(incoming) ? incoming : undefined;\n const existing = ctx.state[stateKey];\n const requestId =\n typeof existing === \"string\" && existing ? existing : opts.trustIncomingRequestId && caller ? caller : newRequestId();\n // A UUID v4 here is kept by correlation middlewares that only replace invalid ids.\n if (ctx.state[stateKey] === undefined) ctx.state[stateKey] = requestId;\n ctx.set(\"X-Request-ID\", requestId);\n\n const fields: Fields = { request_id: requestId };\n if (caller && caller !== requestId) fields.upstream_request_id = caller;\n const trace = parseTraceparent(ctx.get(\"traceparent\"));\n if (trace) Object.assign(fields, trace);\n\n const start = performance.now();\n await runWithStore(fields, async (store) => {\n let failed = false;\n try {\n await next();\n } catch (err) {\n // Only reached when no error middleware handled it; Koa answers 500.\n failed = true;\n recordErrorIn(store, err);\n throw err;\n } finally {\n logHttpRequest(\n opts.log,\n {\n method: ctx.method,\n route: routeOf(ctx),\n path: ctx.url,\n status: failed ? 500 : ctx.status,\n duration_ms: performance.now() - start,\n err: store.error,\n fields: store.fields,\n },\n opts,\n );\n }\n });\n };\n}\n\n/**\n * Put right after 'strapi::errors'. Records thrown errors on the request's http.request line and\n * marks them, so the copy strapi::errors logs through strapi.log.error is not written twice.\n */\nexport function strapiErrorCapture(): KoaMiddleware {\n return async (_ctx, next) => {\n try {\n await next();\n } catch (err) {\n const store = currentStore();\n if (store) recordErrorIn(store, err);\n markLogged(err);\n throw err;\n }\n };\n}\n\nconst LEVELS: Record<string, Level> = {\n error: \"error\",\n warn: \"warn\",\n info: \"info\",\n http: \"debug\",\n verbose: \"debug\",\n debug: \"debug\",\n silly: \"trace\",\n};\n\nconst META_SKIP = new Set([\"level\", \"message\", \"stack\"]);\n\nfunction forward(log: Logger, info: Record<string, unknown>): void {\n // Already carried by the request's http.request line (see strapiErrorCapture).\n if (isErrorLike(info) && isLogged(info)) return;\n const level = LEVELS[String(info.level)] ?? \"info\";\n const fields: Fields = {};\n for (const [key, value] of Object.entries(info)) if (!META_SKIP.has(key)) fields[key] = value;\n\n let message: unknown = info.message;\n if (isErrorLike(info)) {\n fields.err = info;\n } else if (isErrorLike(message)) {\n if (isLogged(message)) return;\n fields.err = message;\n message = message.message;\n } else if (typeof info.stack === \"string\") {\n fields.err_stack = info.stack;\n }\n if ((level === \"warn\" || level === \"error\") && fields.event === undefined) fields.event = \"strapi.log\";\n log[level](typeof message === \"string\" ? message : String(message ?? \"\"), fields);\n}\n\n/**\n * Winston configuration for Strapi's config/logger.ts: every strapi.log.* call (app code and\n * framework) becomes a contract JSON line with the request context. Level filtering is left to\n * the logger (LOG_LEVEL).\n */\nexport function strapiLoggerConfig(log: Logger) {\n // The winston logger that pipes into this transport; its level can change at runtime\n // (Strapi's data export/import commands set it to \"error\").\n let parent: { level?: string; levels?: Record<string, number> } | undefined;\n const allowed = (info: Record<string, unknown>): boolean => {\n const rank = parent?.levels?.[String(info.level)];\n const max = parent?.level === undefined ? undefined : parent.levels?.[parent.level];\n return rank === undefined || max === undefined || rank <= max;\n };\n const transport = new Writable({\n objectMode: true,\n write(info: Record<string, unknown>, _encoding, callback) {\n try {\n if (allowed(info)) forward(log, info);\n } finally {\n callback();\n }\n },\n });\n transport.on(\"pipe\", (source: unknown) => {\n parent = source as typeof parent;\n });\n // winston requires a `log(info, callback)` method on stream transports; writes go through write().\n Object.assign(transport, {\n log(info: Record<string, unknown>, callback: () => void) {\n forward(log, info);\n callback();\n },\n });\n return {\n level: \"silly\",\n // Identity format: replaces Strapi's prettyPrint so the transport receives raw info objects.\n format: { transform: <T>(info: T): T => info },\n transports: [transport],\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AAkCzB,SAAS,QAAQ,KAAyC;AACxD,MAAI,OAAO,IAAI,kBAAkB,SAAU,QAAO,IAAI;AACtD,QAAM,OAAQ,IAAI,MAAM,OAA0C;AAClE,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;AAMO,SAAS,oBAAoB,MAAiD;AACnF,QAAM,WAAW,KAAK,YAAY;AAClC,SAAO,OAAO,KAAK,SAAS;AAC1B,UAAM,WAAW,IAAI,IAAI,cAAc;AACvC,UAAM,SAAS,YAAY,cAAc,KAAK,QAAQ,IAAI,WAAW;AACrE,UAAM,WAAW,IAAI,MAAM,QAAQ;AACnC,UAAM,YACJ,OAAO,aAAa,YAAY,WAAW,WAAW,KAAK,0BAA0B,SAAS,SAAS,aAAa;AAEtH,QAAI,IAAI,MAAM,QAAQ,MAAM,OAAW,KAAI,MAAM,QAAQ,IAAI;AAC7D,QAAI,IAAI,gBAAgB,SAAS;AAEjC,UAAM,SAAiB,EAAE,YAAY,UAAU;AAC/C,QAAI,UAAU,WAAW,UAAW,QAAO,sBAAsB;AACjE,UAAM,QAAQ,iBAAiB,IAAI,IAAI,aAAa,CAAC;AACrD,QAAI,MAAO,QAAO,OAAO,QAAQ,KAAK;AAEtC,UAAM,QAAQ,YAAY,IAAI;AAC9B,UAAM,aAAa,QAAQ,OAAO,UAAU;AAC1C,UAAI,SAAS;AACb,UAAI;AACF,cAAM,KAAK;AAAA,MACb,SAAS,KAAK;AAEZ,iBAAS;AACT,sBAAc,OAAO,GAAG;AACxB,cAAM;AAAA,MACR,UAAE;AACA;AAAA,UACE,K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YAAY,KAAK;AAAA,EAC1B;AACA,OAAK,UAAU,UAAU,UAAU,YAAY,OAAO,UAAU,OAAW,QAAO,QAAQ;AAC1F,MAAI,KAAK,EAAE,OAAO,YAAY,WAAW,UAAU,OAAO,WAAW,EAAE,GAAG,MAAM;AAClF;AAOO,SAAS,mBAAmB,KAAa;AAG9C,MAAI;AACJ,QAAM,UAAU,CAAC,SAA2C;AAC1D,UAAM,OAAO,QAAQ,SAAS,OAAO,KAAK,KAAK,CAAC;AAChD,UAAM,MAAM,QAAQ,UAAU,SAAY,SAAY,OAAO,SAAS,OAAO,KAAK;AAClF,WAAO,SAAS,UAAa,QAAQ,UAAa,QAAQ;AAAA,EAC5D;AACA,QAAM,YAAY,IAAI,SAAS;AAAA,IAC7B,YAAY;AAAA,IACZ,MAAM,MAA+B,WAAW,UAAU;AACxD,UAAI;AACF,YAAI,QAAQ,IAAI,EAAG,SAAQ,KAAK,IAAI;AAAA,MACtC,UAAE;AACA,iBAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF,CAAC;AACD,YAAU,GAAG,QAAQ,CAAC,WAAoB;AACxC,aAAS;AAAA,EACX,CAAC;AAED,SAAO,OAAO,WAAW;AAAA,IACvB,IAAI,MAA+B,UAAsB;AACvD,cAAQ,KAAK,IAAI;AACjB,eAAS;AAAA,IACX;AAAA,EACF,CAAC;AACD,SAAO;AAAA,IACL,OAAO;AAAA;AAAA,IAEP,QAAQ,EAAE,WAAW,CAAI,SAAe,KAAK;AAAA,IAC7C,YAAY,CAAC,SAAS;AAAA,EACxB;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanngo11/log",
3
- "version": "0.4.2",
3
+ "version": "0.4.3",
4
4
  "description": "Structured JSON logging for Node services, implementing log contract v1",
5
5
  "license": "MIT",
6
6
  "repository": {