@tanngo11/log 0.3.0

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.
Files changed (71) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/CONTRACT.md +135 -0
  3. package/LICENSE +21 -0
  4. package/README.md +291 -0
  5. package/dist/bullmq.cjs +108 -0
  6. package/dist/bullmq.cjs.map +1 -0
  7. package/dist/bullmq.d.cts +14 -0
  8. package/dist/bullmq.d.ts +14 -0
  9. package/dist/bullmq.js +29 -0
  10. package/dist/bullmq.js.map +1 -0
  11. package/dist/chunk-BP264YAM.js +72 -0
  12. package/dist/chunk-BP264YAM.js.map +1 -0
  13. package/dist/chunk-BVKAY2OK.js +53 -0
  14. package/dist/chunk-BVKAY2OK.js.map +1 -0
  15. package/dist/chunk-DO5HNNTP.js +66 -0
  16. package/dist/chunk-DO5HNNTP.js.map +1 -0
  17. package/dist/chunk-KD5H5G6Y.js +209 -0
  18. package/dist/chunk-KD5H5G6Y.js.map +1 -0
  19. package/dist/chunk-KLBL7QEN.js +29 -0
  20. package/dist/chunk-KLBL7QEN.js.map +1 -0
  21. package/dist/chunk-QMC6BWGK.js +203 -0
  22. package/dist/chunk-QMC6BWGK.js.map +1 -0
  23. package/dist/chunk-UXKPPF4G.js +41 -0
  24. package/dist/chunk-UXKPPF4G.js.map +1 -0
  25. package/dist/express.cjs +316 -0
  26. package/dist/express.cjs.map +1 -0
  27. package/dist/express.d.cts +10 -0
  28. package/dist/express.d.ts +10 -0
  29. package/dist/express.js +12 -0
  30. package/dist/express.js.map +1 -0
  31. package/dist/fastify.cjs +309 -0
  32. package/dist/fastify.cjs.map +1 -0
  33. package/dist/fastify.d.cts +10 -0
  34. package/dist/fastify.d.ts +10 -0
  35. package/dist/fastify.js +10 -0
  36. package/dist/fastify.js.map +1 -0
  37. package/dist/http-BI6ARZlD.d.ts +25 -0
  38. package/dist/http-BXAiU-rN.d.cts +25 -0
  39. package/dist/index.cjs +677 -0
  40. package/dist/index.cjs.map +1 -0
  41. package/dist/index.d.cts +69 -0
  42. package/dist/index.d.ts +69 -0
  43. package/dist/index.js +214 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/logger-CFMTzjsm.d.cts +47 -0
  46. package/dist/logger-CFMTzjsm.d.ts +47 -0
  47. package/dist/nest.cjs +458 -0
  48. package/dist/nest.cjs.map +1 -0
  49. package/dist/nest.d.cts +41 -0
  50. package/dist/nest.d.ts +41 -0
  51. package/dist/nest.js +107 -0
  52. package/dist/nest.js.map +1 -0
  53. package/dist/next-edge.cjs +44 -0
  54. package/dist/next-edge.cjs.map +1 -0
  55. package/dist/next-edge.d.cts +7 -0
  56. package/dist/next-edge.d.ts +7 -0
  57. package/dist/next-edge.js +16 -0
  58. package/dist/next-edge.js.map +1 -0
  59. package/dist/next.cjs +423 -0
  60. package/dist/next.cjs.map +1 -0
  61. package/dist/next.d.cts +36 -0
  62. package/dist/next.d.ts +36 -0
  63. package/dist/next.js +138 -0
  64. package/dist/next.js.map +1 -0
  65. package/dist/prisma.cjs +63 -0
  66. package/dist/prisma.cjs.map +1 -0
  67. package/dist/prisma.d.cts +31 -0
  68. package/dist/prisma.d.ts +31 -0
  69. package/dist/prisma.js +38 -0
  70. package/dist/prisma.js.map +1 -0
  71. package/package.json +138 -0
package/dist/nest.js ADDED
@@ -0,0 +1,107 @@
1
+ import {
2
+ requestLogger
3
+ } from "./chunk-BP264YAM.js";
4
+ import {
5
+ fastifyLogger
6
+ } from "./chunk-DO5HNNTP.js";
7
+ import "./chunk-KD5H5G6Y.js";
8
+ import "./chunk-KLBL7QEN.js";
9
+ import {
10
+ currentStore,
11
+ recordError,
12
+ recordErrorIn,
13
+ storeOf
14
+ } from "./chunk-QMC6BWGK.js";
15
+
16
+ // src/nest.ts
17
+ import { catchError, throwError } from "rxjs";
18
+ var STACK_RE = /\n\s+at /;
19
+ var NestLogger = class {
20
+ constructor(logger) {
21
+ this.logger = logger;
22
+ }
23
+ logger;
24
+ log(message, ...params) {
25
+ this.emit("info", message, params);
26
+ }
27
+ error(message, ...params) {
28
+ this.emit("error", message, params);
29
+ }
30
+ warn(message, ...params) {
31
+ this.emit("warn", message, params);
32
+ }
33
+ debug(message, ...params) {
34
+ this.emit("debug", message, params);
35
+ }
36
+ verbose(message, ...params) {
37
+ this.emit("trace", message, params);
38
+ }
39
+ fatal(message, ...params) {
40
+ this.emit("fatal", message, params);
41
+ }
42
+ emit(level, message, params) {
43
+ const rest = [...params];
44
+ const last = rest[rest.length - 1];
45
+ const nestContext = typeof last === "string" && !STACK_RE.test(last) ? rest.pop() : void 0;
46
+ const stack = typeof rest[0] === "string" && STACK_RE.test(rest[0]) ? rest.shift() : void 0;
47
+ const store = currentStore();
48
+ if (nestContext === "ExceptionsHandler" && store?.fields.request_id !== void 0) {
49
+ if (store.error === void 0) {
50
+ const e = message instanceof Error ? message : Object.assign(new Error(String(message)), { stack });
51
+ recordErrorIn(store, e);
52
+ }
53
+ return;
54
+ }
55
+ const fields = { nest_context: nestContext };
56
+ const extras = [];
57
+ for (const arg of rest) {
58
+ if (arg instanceof Error && fields.err === void 0) fields.err = arg;
59
+ else if (typeof arg === "object" && arg !== null && !Array.isArray(arg)) Object.assign(fields, arg);
60
+ else extras.push(arg);
61
+ }
62
+ if (extras.length > 0) fields.nest_args = extras;
63
+ let text;
64
+ if (message instanceof Error) {
65
+ fields.err = message;
66
+ text = message.message;
67
+ } else if (typeof message === "object" && message !== null) {
68
+ fields.nest_payload = message;
69
+ text = "nest log";
70
+ } else {
71
+ text = String(message);
72
+ }
73
+ if (stack !== void 0) fields.err_stack = stack;
74
+ this.logger[level](text, fields);
75
+ }
76
+ };
77
+ var ErrorRecorderInterceptor = class {
78
+ intercept(context, next) {
79
+ return next.handle().pipe(
80
+ catchError((err) => {
81
+ const store = storeOf(context.switchToHttp().getResponse());
82
+ if (store) recordErrorIn(store, err);
83
+ else recordError(err);
84
+ return throwError(() => err);
85
+ })
86
+ );
87
+ }
88
+ };
89
+ async function setupNestLogging(app, log, opts = {}) {
90
+ const type = app.getHttpAdapter().getType();
91
+ if (type === "fastify") {
92
+ if (!app.register) throw new Error("setupNestLogging: Fastify app has no register()");
93
+ await app.register(fastifyLogger, { ...opts, log });
94
+ } else {
95
+ if (!app.use) throw new Error("setupNestLogging: app has no use()");
96
+ app.use(requestLogger(log, opts));
97
+ }
98
+ app.useGlobalInterceptors(new ErrorRecorderInterceptor());
99
+ }
100
+ export {
101
+ ErrorRecorderInterceptor,
102
+ NestLogger,
103
+ fastifyLogger,
104
+ requestLogger,
105
+ setupNestLogging
106
+ };
107
+ //# sourceMappingURL=nest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/nest.ts"],"sourcesContent":["import type { CallHandler, ExecutionContext, LoggerService, NestInterceptor } from \"@nestjs/common\";\nimport { catchError, throwError, type Observable } from \"rxjs\";\nimport { currentStore, recordError, recordErrorIn, storeOf } from \"./context\";\nimport { requestLogger as expressRequestLogger } from \"./express\";\nimport { fastifyLogger } from \"./fastify\";\nimport type { HttpLogOptions } from \"./http\";\nimport type { Level } from \"./levels\";\nimport type { Logger } from \"./logger\";\nimport type { Fields } from \"./normalize\";\n\nexport { requestLogger } from \"./express\";\nexport { fastifyLogger } from \"./fastify\";\n\nconst STACK_RE = /\\n\\s+at /;\n\n/** Routes Nest's own logs (bootstrap, ExceptionsHandler, Logger calls) into the JSON logger. */\nexport class NestLogger implements LoggerService {\n constructor(private readonly logger: Logger) {}\n\n log(message: unknown, ...params: unknown[]): void {\n this.emit(\"info\", message, params);\n }\n error(message: unknown, ...params: unknown[]): void {\n this.emit(\"error\", message, params);\n }\n warn(message: unknown, ...params: unknown[]): void {\n this.emit(\"warn\", message, params);\n }\n debug(message: unknown, ...params: unknown[]): void {\n this.emit(\"debug\", message, params);\n }\n verbose(message: unknown, ...params: unknown[]): void {\n this.emit(\"trace\", message, params);\n }\n fatal(message: unknown, ...params: unknown[]): void {\n this.emit(\"fatal\", message, params);\n }\n\n private emit(level: Level, message: unknown, params: unknown[]): void {\n const rest = [...params];\n const last = rest[rest.length - 1];\n const nestContext = typeof last === \"string\" && !STACK_RE.test(last) ? (rest.pop() as string) : undefined;\n const stack = typeof rest[0] === \"string\" && STACK_RE.test(rest[0]) ? (rest.shift() as string) : undefined;\n\n // Nest's ExceptionsHandler logs unhandled errors; the http.request line already carries\n // them, so hand the error to the request instead of writing a second error line.\n const store = currentStore();\n if (nestContext === \"ExceptionsHandler\" && store?.fields.request_id !== undefined) {\n if (store.error === undefined) {\n const e = message instanceof Error ? message : Object.assign(new Error(String(message)), { stack });\n recordErrorIn(store, e);\n }\n return;\n }\n\n const fields: Fields = { nest_context: nestContext };\n // Extra arguments: objects become fields, errors become err, anything else goes to nest_args.\n const extras: unknown[] = [];\n for (const arg of rest) {\n if (arg instanceof Error && fields.err === undefined) fields.err = arg;\n else if (typeof arg === \"object\" && arg !== null && !Array.isArray(arg)) Object.assign(fields, arg);\n else extras.push(arg);\n }\n if (extras.length > 0) fields.nest_args = extras;\n let text: string;\n if (message instanceof Error) {\n fields.err = message;\n text = message.message;\n } else if (typeof message === \"object\" && message !== null) {\n fields.nest_payload = message;\n text = \"nest log\";\n } else {\n text = String(message);\n }\n if (stack !== undefined) fields.err_stack = stack;\n this.logger[level](text, fields);\n }\n}\n\n/** Records request errors for the http.request line, then rethrows to Nest's exception filters. */\nexport class ErrorRecorderInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {\n return next.handle().pipe(\n catchError((err: unknown) => {\n const store = storeOf(context.switchToHttp().getResponse());\n if (store) recordErrorIn(store, err);\n else recordError(err);\n return throwError(() => err);\n }),\n );\n }\n}\n\n\n/** The parts of a Nest application that setupNestLogging needs, for either HTTP adapter. */\nexport interface NestAppLike {\n getHttpAdapter(): { getType(): string };\n useGlobalInterceptors(...interceptors: NestInterceptor[]): unknown;\n use?(...args: unknown[]): unknown;\n register?(...args: unknown[]): Promise<unknown>;\n}\n\n/**\n * One-call setup for Express and Fastify Nest apps: request context, the http.request line and\n * error recording. Call before `app.listen()`.\n */\nexport async function setupNestLogging(app: NestAppLike, log: Logger, opts: HttpLogOptions = {}): Promise<void> {\n const type = app.getHttpAdapter().getType();\n if (type === \"fastify\") {\n if (!app.register) throw new Error(\"setupNestLogging: Fastify app has no register()\");\n await app.register(fastifyLogger, { ...opts, log });\n } else {\n if (!app.use) throw new Error(\"setupNestLogging: app has no use()\");\n app.use(expressRequestLogger(log, opts));\n }\n app.useGlobalInterceptors(new ErrorRecorderInterceptor());\n}\n"],"mappings":"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","names":[]}
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/next-edge.ts
21
+ var next_edge_exports = {};
22
+ __export(next_edge_exports, {
23
+ withRequestId: () => withRequestId
24
+ });
25
+ module.exports = __toCommonJS(next_edge_exports);
26
+
27
+ // src/request-id.ts
28
+ var REQUEST_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
29
+ function newRequestId() {
30
+ return globalThis.crypto.randomUUID();
31
+ }
32
+
33
+ // src/next-edge.ts
34
+ function withRequestId(request) {
35
+ const headers = new Headers(request.headers);
36
+ const current = headers.get("x-request-id");
37
+ if (!current || !REQUEST_ID_RE.test(current)) headers.set("x-request-id", newRequestId());
38
+ return headers;
39
+ }
40
+ // Annotate the CommonJS export names for ESM import in node:
41
+ 0 && (module.exports = {
42
+ withRequestId
43
+ });
44
+ //# sourceMappingURL=next-edge.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/next-edge.ts","../src/request-id.ts"],"sourcesContent":["import { newRequestId, REQUEST_ID_RE } from \"./request-id\";\n\n/**\n * For middleware.ts (edge runtime). Returns request headers that carry a valid x-request-id:\n * `return NextResponse.next({ request: { headers: withRequestId(request) } })`.\n */\nexport function withRequestId(request: Request): Headers {\n const headers = new Headers(request.headers);\n const current = headers.get(\"x-request-id\");\n if (!current || !REQUEST_ID_RE.test(current)) headers.set(\"x-request-id\", newRequestId());\n return headers;\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,gBAAgB;AAGtB,SAAS,eAAuB;AACrC,SAAO,WAAW,OAAO,WAAW;AACtC;;;ADAO,SAAS,cAAc,SAA2B;AACvD,QAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;AAC3C,QAAM,UAAU,QAAQ,IAAI,cAAc;AAC1C,MAAI,CAAC,WAAW,CAAC,cAAc,KAAK,OAAO,EAAG,SAAQ,IAAI,gBAAgB,aAAa,CAAC;AACxF,SAAO;AACT;","names":[]}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * For middleware.ts (edge runtime). Returns request headers that carry a valid x-request-id:
3
+ * `return NextResponse.next({ request: { headers: withRequestId(request) } })`.
4
+ */
5
+ declare function withRequestId(request: Request): Headers;
6
+
7
+ export { withRequestId };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * For middleware.ts (edge runtime). Returns request headers that carry a valid x-request-id:
3
+ * `return NextResponse.next({ request: { headers: withRequestId(request) } })`.
4
+ */
5
+ declare function withRequestId(request: Request): Headers;
6
+
7
+ export { withRequestId };
@@ -0,0 +1,16 @@
1
+ import {
2
+ REQUEST_ID_RE,
3
+ newRequestId
4
+ } from "./chunk-KLBL7QEN.js";
5
+
6
+ // src/next-edge.ts
7
+ function withRequestId(request) {
8
+ const headers = new Headers(request.headers);
9
+ const current = headers.get("x-request-id");
10
+ if (!current || !REQUEST_ID_RE.test(current)) headers.set("x-request-id", newRequestId());
11
+ return headers;
12
+ }
13
+ export {
14
+ withRequestId
15
+ };
16
+ //# sourceMappingURL=next-edge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/next-edge.ts"],"sourcesContent":["import { newRequestId, REQUEST_ID_RE } from \"./request-id\";\n\n/**\n * For middleware.ts (edge runtime). Returns request headers that carry a valid x-request-id:\n * `return NextResponse.next({ request: { headers: withRequestId(request) } })`.\n */\nexport function withRequestId(request: Request): Headers {\n const headers = new Headers(request.headers);\n const current = headers.get(\"x-request-id\");\n if (!current || !REQUEST_ID_RE.test(current)) headers.set(\"x-request-id\", newRequestId());\n return headers;\n}\n"],"mappings":";;;;;;AAMO,SAAS,cAAc,SAA2B;AACvD,QAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;AAC3C,QAAM,UAAU,QAAQ,IAAI,cAAc;AAC1C,MAAI,CAAC,WAAW,CAAC,cAAc,KAAK,OAAO,EAAG,SAAQ,IAAI,gBAAgB,aAAa,CAAC;AACxF,SAAO;AACT;","names":[]}
package/dist/next.cjs ADDED
@@ -0,0 +1,423 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/next.ts
31
+ var next_exports = {};
32
+ __export(next_exports, {
33
+ nextControlStatus: () => nextControlStatus,
34
+ nextOnRequestError: () => nextOnRequestError,
35
+ registerNext: () => registerNext,
36
+ withAction: () => withAction,
37
+ withLogging: () => withLogging
38
+ });
39
+ module.exports = __toCommonJS(next_exports);
40
+
41
+ // src/context.ts
42
+ var import_node_async_hooks = require("async_hooks");
43
+
44
+ // src/global.ts
45
+ function globalSingleton(name, make) {
46
+ const key = /* @__PURE__ */ Symbol.for(`@tanngo11/log.${name}`);
47
+ const g = globalThis;
48
+ let value = g[key];
49
+ if (value === void 0) {
50
+ value = make();
51
+ g[key] = value;
52
+ }
53
+ return value;
54
+ }
55
+
56
+ // src/context.ts
57
+ var als = globalSingleton("als", () => new import_node_async_hooks.AsyncLocalStorage());
58
+ function runWithStore(fields, fn) {
59
+ const parent = als.getStore();
60
+ const store = { fields: { ...parent?.fields, ...fields }, parent };
61
+ return als.run(store, () => fn(store));
62
+ }
63
+
64
+ // src/redact.ts
65
+ var DEFAULT_REDACT_KEYS = [
66
+ "password",
67
+ "passwd",
68
+ "pwd",
69
+ "passphrase",
70
+ "secret",
71
+ "client_secret",
72
+ "token",
73
+ "access_token",
74
+ "refresh_token",
75
+ "id_token",
76
+ "auth_token",
77
+ "api_key",
78
+ "apikey",
79
+ "access_key",
80
+ "secret_key",
81
+ "private_key",
82
+ "authorization",
83
+ "cookie",
84
+ "set_cookie",
85
+ "session_id",
86
+ "sessionid",
87
+ "credential",
88
+ "credentials",
89
+ "dsn",
90
+ "connection_string",
91
+ "conn_string",
92
+ "jwt",
93
+ "bearer"
94
+ ];
95
+ var SAFE_SUFFIXES = ["_count", "_type", "_length", "_expires_at", "_expires_in", "_ttl", "_at", "_ms", "_enabled"];
96
+ var REDACTED = "[REDACTED]";
97
+ function toSnakeCase(key) {
98
+ return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/[^A-Za-z0-9_]+/g, "_").toLowerCase();
99
+ }
100
+ var URL_CREDENTIALS_RE = /([a-z][a-z0-9+.-]*:\/\/)[^\s/@:"']+:[^\s/@"']+@/gi;
101
+ var BEARER_RE = /\bBearer\s+[A-Za-z0-9._~+/=-]+/gi;
102
+ var JWT_RE = /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
103
+ var EMAIL_RE = /[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,})/g;
104
+ function globalize(re) {
105
+ return re.flags.includes("g") ? new RegExp(re.source, re.flags) : new RegExp(re.source, `${re.flags}g`);
106
+ }
107
+ function createRedactor(opts = {}) {
108
+ const words = [...DEFAULT_REDACT_KEYS];
109
+ const keyPatterns = [];
110
+ for (const k of opts.keys ?? []) {
111
+ if (typeof k === "string") words.push(toSnakeCase(k));
112
+ else keyPatterns.push(new RegExp(k.source, k.flags.replace("g", "")));
113
+ }
114
+ const valuePatterns = (opts.values ?? []).map(globalize);
115
+ const isSensitive = (key) => {
116
+ const k = toSnakeCase(key);
117
+ if (keyPatterns.some((re) => re.test(k))) return true;
118
+ if (!words.includes(k) && SAFE_SUFFIXES.some((s) => k.endsWith(s))) return false;
119
+ return words.some((w) => k === w || k.startsWith(`${w}_`) || k.endsWith(`_${w}`) || k.includes(`_${w}_`));
120
+ };
121
+ const scrub = (s) => {
122
+ let out = s.replace(URL_CREDENTIALS_RE, `$1${REDACTED}@`).replace(BEARER_RE, `Bearer ${REDACTED}`).replace(JWT_RE, "[REDACTED_JWT]").replace(EMAIL_RE, "***@$1");
123
+ for (const re of valuePatterns) out = out.replace(re, REDACTED);
124
+ return out;
125
+ };
126
+ const json = (value) => {
127
+ if (typeof value === "string") return value;
128
+ try {
129
+ const text = JSON.stringify(value, (key, val) => {
130
+ if (key && val !== null && val !== void 0 && isSensitive(key)) return REDACTED;
131
+ if (typeof val === "bigint") return val.toString();
132
+ if (val instanceof Error) return { name: val.name, message: val.message };
133
+ return val;
134
+ });
135
+ return text ?? String(value);
136
+ } catch {
137
+ return String(value);
138
+ }
139
+ };
140
+ return { isSensitive, scrub, json };
141
+ }
142
+ var defaultRedactor = createRedactor();
143
+
144
+ // src/error.ts
145
+ var MAX_CAUSE_DEPTH = 5;
146
+ function isErrorLike(v) {
147
+ if (v instanceof Error) return true;
148
+ return typeof v === "object" && v !== null && typeof v.message === "string" && ("stack" in v || "name" in v);
149
+ }
150
+ function errorType(e) {
151
+ if (e.name && e.name !== "Error") return e.name;
152
+ const ctor = e.constructor?.name;
153
+ return ctor && ctor !== "Object" ? ctor : "Error";
154
+ }
155
+ function serializeError(err) {
156
+ if (!isErrorLike(err)) {
157
+ if (typeof err === "string") return { err_type: "string", err_message: err };
158
+ return { err_type: typeof err, err_message: defaultRedactor.json(err) };
159
+ }
160
+ const e = err;
161
+ const out = { err_type: errorType(e), err_message: String(e.message ?? "") };
162
+ if (e.code !== void 0 && e.code !== null) out.err_code = String(e.code);
163
+ if (typeof e.stack === "string") out.err_stack = e.stack;
164
+ const causes = [];
165
+ let cause = e.cause;
166
+ while (cause !== void 0 && cause !== null && causes.length < MAX_CAUSE_DEPTH) {
167
+ if (isErrorLike(cause)) {
168
+ causes.push(`${errorType(cause)}: ${cause.message}`);
169
+ cause = cause.cause;
170
+ } else {
171
+ causes.push(defaultRedactor.json(cause));
172
+ cause = void 0;
173
+ }
174
+ }
175
+ if (causes.length > 0) out.err_cause = causes.join(" <- ");
176
+ return out;
177
+ }
178
+ var logged = globalSingleton("logged", () => /* @__PURE__ */ new WeakSet());
179
+ function markLogged(err) {
180
+ if (typeof err === "object" && err !== null) logged.add(err);
181
+ }
182
+ function isLogged(err) {
183
+ return typeof err === "object" && err !== null && logged.has(err);
184
+ }
185
+
186
+ // src/normalize.ts
187
+ function stripUrl(url) {
188
+ const noQuery = url.split(/[?#]/, 1)[0] ?? "";
189
+ return noQuery.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@\s]*@/i, "$1");
190
+ }
191
+
192
+ // src/request-id.ts
193
+ var REQUEST_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
194
+ var TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
195
+ function newRequestId() {
196
+ return globalThis.crypto.randomUUID();
197
+ }
198
+ function first(header2) {
199
+ return Array.isArray(header2) ? header2[0] : header2 ?? void 0;
200
+ }
201
+ function resolveRequestId(header2) {
202
+ const value = first(header2);
203
+ return value && REQUEST_ID_RE.test(value) ? value : newRequestId();
204
+ }
205
+ function parseTraceparent(header2) {
206
+ const value = first(header2)?.trim().toLowerCase();
207
+ const m = value ? TRACEPARENT_RE.exec(value) : null;
208
+ if (!m) return void 0;
209
+ const [, version, traceId, spanId] = m;
210
+ if (version === "ff" || /^0+$/.test(traceId) || /^0+$/.test(spanId)) return void 0;
211
+ return { trace_id: traceId, span_id: spanId };
212
+ }
213
+
214
+ // src/http.ts
215
+ function header(headers, name) {
216
+ if (typeof headers.get === "function") return headers.get(name) ?? void 0;
217
+ return headers[name];
218
+ }
219
+ function requestContextFields(headers) {
220
+ const out = {
221
+ request_id: resolveRequestId(header(headers, "x-request-id"))
222
+ };
223
+ const tp = parseTraceparent(header(headers, "traceparent"));
224
+ if (tp) Object.assign(out, tp);
225
+ return out;
226
+ }
227
+ var DEFAULT_SKIP_PATHS = [
228
+ /^\/(health|healthz|ready|readyz|livez)\/?$/,
229
+ "/favicon.ico",
230
+ /^\/_next\/static\//
231
+ ];
232
+ function shouldSkip(method, path, skipPaths = DEFAULT_SKIP_PATHS) {
233
+ if (method.toUpperCase() === "OPTIONS") return true;
234
+ const p = stripUrl(path);
235
+ return skipPaths.some((s) => typeof s === "string" ? p === s : s.test(p));
236
+ }
237
+ function logHttpRequest(log, info, opts = {}) {
238
+ if (shouldSkip(info.method, info.path, opts.skipPaths)) return;
239
+ const level = info.status >= 500 ? "error" : info.status >= 400 ? "warn" : "info";
240
+ const path = stripUrl(info.path);
241
+ const errFields = {};
242
+ if (info.err !== void 0 && info.err !== null) {
243
+ Object.assign(errFields, serializeError(info.err));
244
+ if (info.status < 500) delete errFields.err_stack;
245
+ markLogged(info.err);
246
+ }
247
+ const message = info.route ? `${info.method} ${info.route} ${info.status}` : `${info.method} ${info.status}`;
248
+ log[level](message, {
249
+ ...info.fields,
250
+ event: "http.request",
251
+ http_method: info.method,
252
+ http_route: info.route,
253
+ http_path: path,
254
+ http_status: info.status,
255
+ duration_ms: info.duration_ms === void 0 ? void 0 : Math.round(info.duration_ms),
256
+ ...errFields
257
+ });
258
+ }
259
+
260
+ // src/process.ts
261
+ function logStartup(log, fields = {}) {
262
+ log.info("app started", {
263
+ event: "app.started",
264
+ runtime_version: `node ${process.versions.node}`,
265
+ log_level: log.level,
266
+ ...fields
267
+ });
268
+ }
269
+ function crashHandlers(log, opts = {}) {
270
+ const exitOnCrash = opts.exitOnCrash ?? true;
271
+ const exitDelayMs = opts.exitDelayMs ?? 1e3;
272
+ const exit = opts.exit ?? ((code) => process.exit(code));
273
+ let exiting = false;
274
+ const crash = (source, err) => {
275
+ if (!exitOnCrash) {
276
+ log.error("unhandled error", { event: "app.unhandled_error", crash_source: source, err });
277
+ return;
278
+ }
279
+ log.fatal("app crashed", { event: "app.crashed", crash_source: source, err });
280
+ if (exiting) return;
281
+ exiting = true;
282
+ if (typeof process !== "undefined") process.exitCode = 1;
283
+ const timer = setTimeout(() => exit(1), exitDelayMs);
284
+ timer.unref?.();
285
+ };
286
+ return {
287
+ onUncaught: (err) => crash("uncaughtException", err),
288
+ onRejection: (reason) => crash("unhandledRejection", reason)
289
+ };
290
+ }
291
+ var state = globalSingleton("process", () => ({ installed: false }));
292
+ function installProcessHandlers(log, opts = {}) {
293
+ if (state.installed || typeof process === "undefined" || typeof process.on !== "function") return;
294
+ state.installed = true;
295
+ const h = crashHandlers(log, opts);
296
+ process.on("uncaughtException", h.onUncaught);
297
+ process.on("unhandledRejection", h.onRejection);
298
+ }
299
+
300
+ // src/next.ts
301
+ function nextControlStatus(err) {
302
+ const digest = err?.digest;
303
+ if (typeof digest !== "string") return void 0;
304
+ if (digest.startsWith("NEXT_REDIRECT")) {
305
+ const status = Number(digest.split(";")[3]);
306
+ return Number.isInteger(status) && status >= 300 ? status : 307;
307
+ }
308
+ if (digest === "NEXT_NOT_FOUND") return 404;
309
+ if (digest.startsWith("NEXT_HTTP_ERROR_FALLBACK;")) return Number(digest.split(";")[1]) || 404;
310
+ return void 0;
311
+ }
312
+ function asError(value) {
313
+ if (typeof value === "object" && value !== null) return value;
314
+ return Object.assign(new Error(String(value)), { name: "NonErrorThrown", thrown: value });
315
+ }
316
+ function trySetHeader(res, name, value) {
317
+ try {
318
+ res.headers.set(name, value);
319
+ } catch {
320
+ }
321
+ }
322
+ function withLogging(log, handler, opts = {}) {
323
+ return (request, context) => {
324
+ const ctx = requestContextFields(request.headers);
325
+ const path = new URL(request.url).pathname;
326
+ const start = performance.now();
327
+ return runWithStore(ctx, async (store) => {
328
+ const summary = (status, err) => logHttpRequest(
329
+ log,
330
+ {
331
+ method: request.method,
332
+ route: opts.route,
333
+ path,
334
+ status,
335
+ duration_ms: performance.now() - start,
336
+ err,
337
+ fields: store.fields
338
+ },
339
+ opts
340
+ );
341
+ try {
342
+ const res = await handler(request, context);
343
+ summary(res.status, store.error);
344
+ trySetHeader(res, "x-request-id", ctx.request_id);
345
+ return res;
346
+ } catch (caught) {
347
+ const control = nextControlStatus(caught);
348
+ const err = control === void 0 ? asError(caught) : caught;
349
+ summary(control ?? 500, control === void 0 ? err : store.error);
350
+ throw err;
351
+ }
352
+ });
353
+ };
354
+ }
355
+ function nextOnRequestError(log, opts = {}) {
356
+ return async (err, request, context) => {
357
+ if (isLogged(err) || nextControlStatus(err) !== void 0) return;
358
+ const digest = err?.digest;
359
+ logHttpRequest(
360
+ log,
361
+ {
362
+ method: request?.method ?? "GET",
363
+ route: context?.routePath,
364
+ path: request?.path ?? "",
365
+ status: 500,
366
+ err,
367
+ fields: {
368
+ ...requestContextFields(request?.headers ?? {}),
369
+ next_route_type: context?.routeType,
370
+ next_router_kind: context?.routerKind,
371
+ next_digest: typeof digest === "string" ? digest : void 0
372
+ }
373
+ },
374
+ opts
375
+ );
376
+ };
377
+ }
378
+ function registerNext(log, fields) {
379
+ if (process.env.NEXT_RUNTIME && process.env.NEXT_RUNTIME !== "nodejs") return;
380
+ installProcessHandlers(log, { exitOnCrash: false });
381
+ logStartup(log, { port: process.env.PORT ? Number(process.env.PORT) : void 0, ...fields });
382
+ }
383
+ async function nextHeaders() {
384
+ try {
385
+ const mod = await import("next/headers");
386
+ return await mod.headers();
387
+ } catch {
388
+ return {};
389
+ }
390
+ }
391
+ function withAction(log, name, action, opts = {}) {
392
+ return async (...args) => {
393
+ const headers = await (opts.headers ?? nextHeaders)();
394
+ const start = performance.now();
395
+ return runWithStore({ ...requestContextFields(headers), action_name: name }, async (store) => {
396
+ const fields = () => ({ ...store.fields, duration_ms: Math.round(performance.now() - start) });
397
+ try {
398
+ const result = await action(...args);
399
+ log.info("server action completed", { ...fields(), event: "action.completed", err: store.error });
400
+ return result;
401
+ } catch (caught) {
402
+ const control = nextControlStatus(caught);
403
+ if (control !== void 0) {
404
+ log.info("server action completed", { ...fields(), event: "action.completed", next_control_status: control });
405
+ throw caught;
406
+ }
407
+ const err = asError(caught);
408
+ log.error("server action failed", { ...fields(), event: "action.failed", err });
409
+ markLogged(err);
410
+ throw err;
411
+ }
412
+ });
413
+ };
414
+ }
415
+ // Annotate the CommonJS export names for ESM import in node:
416
+ 0 && (module.exports = {
417
+ nextControlStatus,
418
+ nextOnRequestError,
419
+ registerNext,
420
+ withAction,
421
+ withLogging
422
+ });
423
+ //# sourceMappingURL=next.cjs.map