unnbound-logger-sdk 3.0.26 → 3.0.28
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/package.json +17 -16
- package/LICENSE +0 -21
- package/dist/file.d.ts +0 -175
- package/dist/file.js +0 -362
package/package.json
CHANGED
|
@@ -1,9 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "unnbound-logger-sdk",
|
|
3
3
|
"description": "A structured logging library with TypeScript support using Pino. Provides consistent, well-typed logging with automatic logId, workflowId, traceId, and deploymentId tracking across operational contexts.",
|
|
4
|
-
"version": "3.0.
|
|
4
|
+
"version": "3.0.28",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"build": "tsc",
|
|
9
|
+
"test": "jest",
|
|
10
|
+
"test:coverage": "jest --coverage",
|
|
11
|
+
"test:watch": "jest --watch",
|
|
12
|
+
"typecheck": "tsc -noEmit",
|
|
13
|
+
"lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .",
|
|
14
|
+
"lint:fix": "pnpm lint --fix",
|
|
15
|
+
"format": "prettier --write .",
|
|
16
|
+
"format:check": "prettier --check .",
|
|
17
|
+
"prepublishOnly": "pnpm build",
|
|
18
|
+
"start:example": "npx --yes tsx --watch examples/node-express.ts",
|
|
19
|
+
"version:bump": "npm version patch"
|
|
20
|
+
},
|
|
7
21
|
"keywords": [
|
|
8
22
|
"logging",
|
|
9
23
|
"typescript",
|
|
@@ -57,18 +71,5 @@
|
|
|
57
71
|
"engines": {
|
|
58
72
|
"node": ">=22"
|
|
59
73
|
},
|
|
60
|
-
"sideEffects": false
|
|
61
|
-
|
|
62
|
-
"build": "tsc",
|
|
63
|
-
"test": "jest",
|
|
64
|
-
"test:coverage": "jest --coverage",
|
|
65
|
-
"test:watch": "jest --watch",
|
|
66
|
-
"typecheck": "tsc -noEmit",
|
|
67
|
-
"lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .",
|
|
68
|
-
"lint:fix": "pnpm lint --fix",
|
|
69
|
-
"format": "prettier --write .",
|
|
70
|
-
"format:check": "prettier --check .",
|
|
71
|
-
"start:example": "npx --yes tsx --watch examples/node-express.ts",
|
|
72
|
-
"version:bump": "npm version patch"
|
|
73
|
-
}
|
|
74
|
-
}
|
|
74
|
+
"sideEffects": false
|
|
75
|
+
}
|
package/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025 Unnbound Team
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
package/dist/file.d.ts
DELETED
|
@@ -1,175 +0,0 @@
|
|
|
1
|
-
import { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios';
|
|
2
|
-
export declare const hidden: (data: object) => unknown;
|
|
3
|
-
export declare const internal: () => Record<string, unknown>;
|
|
4
|
-
type GetAxiosPayload = (config: AxiosRequestConfig, res?: AxiosResponse) => object;
|
|
5
|
-
/**
|
|
6
|
-
* Wraps an axios instance to add tracing and span tracking
|
|
7
|
-
* @param axios - The axios instance to wrap
|
|
8
|
-
* @param options - Configuration options for HTTP tracing
|
|
9
|
-
* @returns The wrapped axios instance with span tracking
|
|
10
|
-
*/
|
|
11
|
-
export declare const traceAxios: (client: AxiosInstance, { ignoreTraceRoutes, traceHeaderKey, getPayload, }?: HttpOptions<GetAxiosPayload>) => AxiosInstance;
|
|
12
|
-
export declare const encode: (value: string) => string;
|
|
13
|
-
export declare const decode: (value: string) => string;
|
|
14
|
-
import pino from 'pino';
|
|
15
|
-
export interface UnnboundLogger extends Omit<pino.Logger, 'trace' | 'debug' | 'error' | 'info' | 'warn'> {
|
|
16
|
-
trace(object: {}, message: string): void;
|
|
17
|
-
trace(message: string): void;
|
|
18
|
-
debug(object: {}, message: string): void;
|
|
19
|
-
debug(message: string): void;
|
|
20
|
-
info(object: {}, message: string): void;
|
|
21
|
-
info(message: string): void;
|
|
22
|
-
warn(object: {}, message: string): void;
|
|
23
|
-
warn(message: string): void;
|
|
24
|
-
error<O extends {
|
|
25
|
-
err: unknown;
|
|
26
|
-
}>(object: O, message: string): void;
|
|
27
|
-
}
|
|
28
|
-
export declare const logger: UnnboundLogger;
|
|
29
|
-
import { Request, RequestHandler } from 'express';
|
|
30
|
-
interface Response {
|
|
31
|
-
status: number;
|
|
32
|
-
headers?: Record<string, string | undefined>;
|
|
33
|
-
body?: unknown;
|
|
34
|
-
}
|
|
35
|
-
type GetHttpPayload = (config: Request, res?: Response) => object;
|
|
36
|
-
export declare const traceMiddleware: ({ ignoreTraceRoutes, traceHeaderKey, messageHeaderKey, getPayload, }?: HttpOptions<GetHttpPayload>) => RequestHandler;
|
|
37
|
-
type LogPayloadGetterOptions<T> = {
|
|
38
|
-
error: unknown;
|
|
39
|
-
result?: never;
|
|
40
|
-
} | {
|
|
41
|
-
error?: never;
|
|
42
|
-
result: T;
|
|
43
|
-
};
|
|
44
|
-
type LogPayloadGetter<T> = object | ((o?: LogPayloadGetterOptions<T>) => object);
|
|
45
|
-
/**
|
|
46
|
-
* Starts a span that tracks the duration of a callback
|
|
47
|
-
* @param spanName - The span name to use for logging
|
|
48
|
-
* @param callback - The async callback to execute
|
|
49
|
-
* @returns The result of the callback
|
|
50
|
-
*/
|
|
51
|
-
export declare const startSpan: <T>(spanName: string, callback: () => Promise<T>, getter?: LogPayloadGetter<T>) => Promise<T>;
|
|
52
|
-
import { AsyncLocalStorage } from 'async_hooks';
|
|
53
|
-
export interface Context {
|
|
54
|
-
traceId?: string;
|
|
55
|
-
spanId?: string;
|
|
56
|
-
messageId?: string;
|
|
57
|
-
}
|
|
58
|
-
export declare const storage: AsyncLocalStorage<Context>;
|
|
59
|
-
/**
|
|
60
|
-
* Generates a trace ID
|
|
61
|
-
* @returns A trace ID
|
|
62
|
-
*/
|
|
63
|
-
export declare const getTraceId: () => string;
|
|
64
|
-
/**
|
|
65
|
-
* Generates a message ID
|
|
66
|
-
* @returns A message ID
|
|
67
|
-
*/
|
|
68
|
-
export declare const getMessageId: () => string;
|
|
69
|
-
/**
|
|
70
|
-
* Runs a callback with a trace ID
|
|
71
|
-
* @param callback - The callback to run
|
|
72
|
-
* @param extra - Extra context to add to the trace
|
|
73
|
-
* @returns The result of the callback
|
|
74
|
-
*/
|
|
75
|
-
export declare const withTrace: <T, E extends {
|
|
76
|
-
traceId?: string;
|
|
77
|
-
messageId?: string;
|
|
78
|
-
}>(callback: () => T, extra?: E) => T;
|
|
79
|
-
/**
|
|
80
|
-
* Type definitions for structured logging library
|
|
81
|
-
*/
|
|
82
|
-
/**
|
|
83
|
-
* Available log levels
|
|
84
|
-
*/
|
|
85
|
-
export type LogLevel = 'info' | 'debug' | 'error' | 'warn';
|
|
86
|
-
/**
|
|
87
|
-
* Available log types
|
|
88
|
-
*/
|
|
89
|
-
export type LogType = 'general' | 'http' | 'sftp' | 'edi';
|
|
90
|
-
/**
|
|
91
|
-
* HTTP methods supported for HTTP logging
|
|
92
|
-
*/
|
|
93
|
-
export type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head';
|
|
94
|
-
export interface Log<T extends LogType = 'general'> {
|
|
95
|
-
logId: string;
|
|
96
|
-
level: LogLevel;
|
|
97
|
-
message: string;
|
|
98
|
-
type: T;
|
|
99
|
-
traceId?: string;
|
|
100
|
-
spanId?: string;
|
|
101
|
-
serviceId?: string;
|
|
102
|
-
deploymentId?: string;
|
|
103
|
-
workflowId?: string;
|
|
104
|
-
http: T extends 'http' ? HttpPayload : never;
|
|
105
|
-
sftp: T extends 'sftp' ? SftpPayload : never;
|
|
106
|
-
edi: T extends 'edi' ? EdiPayload : never;
|
|
107
|
-
duration?: number;
|
|
108
|
-
err?: unknown;
|
|
109
|
-
}
|
|
110
|
-
export interface HttpPayload {
|
|
111
|
-
url: string;
|
|
112
|
-
method: HttpMethod;
|
|
113
|
-
ip?: string;
|
|
114
|
-
request: {
|
|
115
|
-
headers: Record<string, string | string[]>;
|
|
116
|
-
body?: unknown;
|
|
117
|
-
};
|
|
118
|
-
response?: {
|
|
119
|
-
headers: Record<string, string | string[]>;
|
|
120
|
-
status: number;
|
|
121
|
-
body?: unknown;
|
|
122
|
-
};
|
|
123
|
-
}
|
|
124
|
-
export type SftpOperation = 'connect' | 'upload' | 'download' | 'list' | 'delete' | 'rename' | 'stat' | 'exists' | 'realPath' | 'get' | 'put' | 'cwd' | 'mkdir' | 'rmdir' | 'chmod' | 'append' | 'uploadDir' | 'downloadDir' | 'close';
|
|
125
|
-
export interface SftpPayload {
|
|
126
|
-
host: string;
|
|
127
|
-
operation: SftpOperation;
|
|
128
|
-
path?: string;
|
|
129
|
-
bytes?: number;
|
|
130
|
-
destinationPath?: string;
|
|
131
|
-
files?: string[];
|
|
132
|
-
content?: string;
|
|
133
|
-
exists?: string | false;
|
|
134
|
-
}
|
|
135
|
-
export type EdiX12Operation = 'fromX12' | 'toX12' | 'validateX12' | 'acknowledgeX12';
|
|
136
|
-
export type EdiOperation = EdiX12Operation;
|
|
137
|
-
export type EdiFormat = 'x12';
|
|
138
|
-
export interface EdiX12Payload {
|
|
139
|
-
input: unknown;
|
|
140
|
-
output: unknown;
|
|
141
|
-
}
|
|
142
|
-
export interface EdiPayload {
|
|
143
|
-
operation: EdiOperation;
|
|
144
|
-
type: EdiFormat;
|
|
145
|
-
x12?: EdiX12Payload;
|
|
146
|
-
}
|
|
147
|
-
export interface HttpOptions<G extends Function> {
|
|
148
|
-
ignoreTraceRoutes?: string[];
|
|
149
|
-
traceHeaderKey?: string;
|
|
150
|
-
messageHeaderKey?: string;
|
|
151
|
-
getPayload?: G;
|
|
152
|
-
}
|
|
153
|
-
export declare const defaultIgnoreTraceRoutes: string[];
|
|
154
|
-
export declare const defaultTraceHeaderKey = "x-unnbound-trace-id";
|
|
155
|
-
export declare const defaultMessageHeaderKey = "x-message-id";
|
|
156
|
-
/**
|
|
157
|
-
* Checks if a path matches any of the ignore patterns
|
|
158
|
-
* @param path - The path to check
|
|
159
|
-
* @param patterns - Array of glob patterns to match against
|
|
160
|
-
* @returns boolean indicating if the path should be ignored
|
|
161
|
-
*/
|
|
162
|
-
export declare const shouldIgnorePath: (path: string, patterns: string[]) => boolean;
|
|
163
|
-
/**
|
|
164
|
-
* Safely parses JSON strings, returning the original data if parsing fails or if it's not a string.
|
|
165
|
-
* @param data The data to potentially parse as JSON.
|
|
166
|
-
* @returns Parsed JSON object or the original data.
|
|
167
|
-
*/
|
|
168
|
-
export declare function safeJsonParse(data: any): any;
|
|
169
|
-
/**
|
|
170
|
-
* Normalizes IP addresses by removing IPv6 mapping prefix for IPv4 addresses.
|
|
171
|
-
* @param ip The IP address to normalize.
|
|
172
|
-
* @returns Normalized IP address string.
|
|
173
|
-
*/
|
|
174
|
-
export declare function normalizeIp(ip: string | undefined): string | undefined;
|
|
175
|
-
export {};
|
package/dist/file.js
DELETED
|
@@ -1,362 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.shouldIgnorePath = exports.defaultMessageHeaderKey = exports.defaultTraceHeaderKey = exports.defaultIgnoreTraceRoutes = exports.withTrace = exports.getMessageId = exports.getTraceId = exports.storage = exports.startSpan = exports.traceMiddleware = exports.logger = exports.decode = exports.encode = exports.traceAxios = exports.internal = exports.hidden = void 0;
|
|
7
|
-
exports.safeJsonParse = safeJsonParse;
|
|
8
|
-
exports.normalizeIp = normalizeIp;
|
|
9
|
-
const axios_1 = require("axios");
|
|
10
|
-
const o = { _internal: true };
|
|
11
|
-
// Internal logs should be hidden in sandbox
|
|
12
|
-
// TODO: Find a better way to detect sandbox
|
|
13
|
-
if (process.env.UNNBOUND_IDLE_TIMEOUT)
|
|
14
|
-
o._hide = true;
|
|
15
|
-
const hidden = (data) => '_hide' in data && data._hide;
|
|
16
|
-
exports.hidden = hidden;
|
|
17
|
-
const internal = () => o;
|
|
18
|
-
exports.internal = internal;
|
|
19
|
-
const getAxiosNoopPayload = () => ({});
|
|
20
|
-
const extractAxiosQueryParams = (url, config) => {
|
|
21
|
-
const object = new URL(url);
|
|
22
|
-
const query = { ...Object.fromEntries(object.searchParams.entries()), ...config.params };
|
|
23
|
-
const keys = Object.keys(query);
|
|
24
|
-
keys.forEach((key) => object.searchParams.delete(key));
|
|
25
|
-
return { url: object.toString(), query: keys.length > 0 ? query : undefined };
|
|
26
|
-
};
|
|
27
|
-
const buildOutgoingAxiosHttpPayload = (config, res) => ({
|
|
28
|
-
type: 'http',
|
|
29
|
-
http: {
|
|
30
|
-
...extractAxiosQueryParams([config.baseURL, config.url].filter(Boolean).join(''), config),
|
|
31
|
-
method: config.method?.toLowerCase() ?? 'get',
|
|
32
|
-
incoming: false,
|
|
33
|
-
request: {
|
|
34
|
-
headers: config.headers,
|
|
35
|
-
body: safeJsonParse(config.data),
|
|
36
|
-
},
|
|
37
|
-
response: res
|
|
38
|
-
? {
|
|
39
|
-
headers: res?.headers,
|
|
40
|
-
status: res.status,
|
|
41
|
-
body: safeJsonParse(res.data),
|
|
42
|
-
}
|
|
43
|
-
: undefined,
|
|
44
|
-
},
|
|
45
|
-
});
|
|
46
|
-
/**
|
|
47
|
-
* Wraps an axios instance to add tracing and span tracking
|
|
48
|
-
* @param axios - The axios instance to wrap
|
|
49
|
-
* @param options - Configuration options for HTTP tracing
|
|
50
|
-
* @returns The wrapped axios instance with span tracking
|
|
51
|
-
*/
|
|
52
|
-
const traceAxios = (client, { ignoreTraceRoutes = exports.defaultIgnoreTraceRoutes, traceHeaderKey = exports.defaultTraceHeaderKey, getPayload = getAxiosNoopPayload, } = {
|
|
53
|
-
ignoreTraceRoutes: exports.defaultIgnoreTraceRoutes,
|
|
54
|
-
traceHeaderKey: exports.defaultTraceHeaderKey,
|
|
55
|
-
getPayload: getAxiosNoopPayload,
|
|
56
|
-
}) => {
|
|
57
|
-
const createSpanWrappedRequest = (originalMethod, method) => {
|
|
58
|
-
const { headers: defaultHeaders, ...partialDefaultConfig } = client.defaults;
|
|
59
|
-
const headers = { ...defaultHeaders.common, ...(method && defaultHeaders[method]) };
|
|
60
|
-
const defaultConfig = { ...partialDefaultConfig, headers };
|
|
61
|
-
return async (config) => {
|
|
62
|
-
config = (0, axios_1.mergeConfig)(defaultConfig, config);
|
|
63
|
-
// Determine the actual config and URL
|
|
64
|
-
const url = [config.baseURL, config.url].filter(Boolean).join('');
|
|
65
|
-
// Check if this request should be ignored
|
|
66
|
-
if ((0, exports.shouldIgnorePath)(url, ignoreTraceRoutes))
|
|
67
|
-
return originalMethod(config);
|
|
68
|
-
const traceId = exports.storage.getStore()?.traceId;
|
|
69
|
-
config = { ...config, headers: { ...config.headers, [traceHeaderKey]: traceId } };
|
|
70
|
-
// Execute the request within a span
|
|
71
|
-
return (0, exports.startSpan)(`Outgoing HTTP request`, () => originalMethod(config), (options) => {
|
|
72
|
-
const response = options
|
|
73
|
-
? options.error
|
|
74
|
-
? (0, axios_1.isAxiosError)(options.error)
|
|
75
|
-
? options.error.response
|
|
76
|
-
: undefined
|
|
77
|
-
: options.result
|
|
78
|
-
: undefined;
|
|
79
|
-
return {
|
|
80
|
-
...buildOutgoingAxiosHttpPayload(config, response),
|
|
81
|
-
...getPayload(config, response),
|
|
82
|
-
};
|
|
83
|
-
});
|
|
84
|
-
};
|
|
85
|
-
};
|
|
86
|
-
const request = client.request.bind(client);
|
|
87
|
-
const tracedRequest = createSpanWrappedRequest(request);
|
|
88
|
-
client.request = tracedRequest;
|
|
89
|
-
['post', 'put', 'patch'].forEach((method) => {
|
|
90
|
-
const func = createSpanWrappedRequest(request, method);
|
|
91
|
-
client[method] = (url, data, config) => func({ ...config, method, url, data });
|
|
92
|
-
});
|
|
93
|
-
['delete', 'get', 'head', 'options'].forEach((method) => {
|
|
94
|
-
const func = createSpanWrappedRequest(request, method);
|
|
95
|
-
client[method] = (url, config) => func({ ...config, method, url });
|
|
96
|
-
});
|
|
97
|
-
return client;
|
|
98
|
-
};
|
|
99
|
-
exports.traceAxios = traceAxios;
|
|
100
|
-
const encode = (value) => value.replaceAll('\n', '\r');
|
|
101
|
-
exports.encode = encode;
|
|
102
|
-
const decode = (value) => value.replaceAll('\r', '\n');
|
|
103
|
-
exports.decode = decode;
|
|
104
|
-
const pino_1 = __importDefault(require("pino"));
|
|
105
|
-
const levels = new Set(['debug', 'info', 'warn', 'error']);
|
|
106
|
-
const formatLevel = (level) => ({ level });
|
|
107
|
-
const formatLog = (log) => {
|
|
108
|
-
Object.entries(log).forEach(([key, value]) => {
|
|
109
|
-
if (value && typeof value === 'object') {
|
|
110
|
-
log[key] = formatLog(value);
|
|
111
|
-
return;
|
|
112
|
-
}
|
|
113
|
-
if (typeof value === 'string') {
|
|
114
|
-
log[key] = (0, exports.encode)(value);
|
|
115
|
-
return;
|
|
116
|
-
}
|
|
117
|
-
});
|
|
118
|
-
return log;
|
|
119
|
-
};
|
|
120
|
-
exports.logger = (0, pino_1.default)({
|
|
121
|
-
level: process.env.LOG_LEVEL ?? 'debug',
|
|
122
|
-
base: {
|
|
123
|
-
environment: process.env.ENVIRONMENT,
|
|
124
|
-
workflowId: process.env.UNNBOUND_WORKFLOW_ID,
|
|
125
|
-
serviceId: process.env.UNNBOUND_SERVICE_ID,
|
|
126
|
-
deploymentId: process.env.UNNBOUND_DEPLOYMENT_ID,
|
|
127
|
-
},
|
|
128
|
-
mixin: () => ({ ...exports.storage.getStore(), logId: (0, uuid_1.v4)() }),
|
|
129
|
-
serializers: {
|
|
130
|
-
req: pino_1.default.stdSerializers.req,
|
|
131
|
-
res: pino_1.default.stdSerializers.res,
|
|
132
|
-
err: pino_1.default.stdSerializers.err,
|
|
133
|
-
message: exports.encode,
|
|
134
|
-
},
|
|
135
|
-
// Let CloudWatch handle timestamps
|
|
136
|
-
timestamp: false,
|
|
137
|
-
// Change message field from 'msg' to 'message'
|
|
138
|
-
messageKey: 'message',
|
|
139
|
-
formatters: { level: formatLevel, log: formatLog },
|
|
140
|
-
hooks: {
|
|
141
|
-
logMethod(args, method) {
|
|
142
|
-
const firstArg = args[0];
|
|
143
|
-
if (!!firstArg && typeof firstArg === 'object') {
|
|
144
|
-
// If the log entry is considered hidden, don't log it
|
|
145
|
-
if ((0, exports.hidden)(firstArg))
|
|
146
|
-
return;
|
|
147
|
-
// Dynamic log level by allowing overwriting the log level
|
|
148
|
-
if ('level' in firstArg &&
|
|
149
|
-
typeof firstArg.level === 'string' &&
|
|
150
|
-
levels.has(firstArg.level)) {
|
|
151
|
-
method = this[firstArg.level];
|
|
152
|
-
firstArg.level = undefined;
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
method.apply(this, args);
|
|
156
|
-
},
|
|
157
|
-
},
|
|
158
|
-
redact: {
|
|
159
|
-
paths: [
|
|
160
|
-
'http.request.headers.authorization',
|
|
161
|
-
'http.response.headers.authorization',
|
|
162
|
-
'http.request.headers.Authorization',
|
|
163
|
-
'http.response.headers.Authorization',
|
|
164
|
-
'err.config',
|
|
165
|
-
],
|
|
166
|
-
remove: true,
|
|
167
|
-
},
|
|
168
|
-
});
|
|
169
|
-
process.on('uncaughtException', (err, origin) => {
|
|
170
|
-
exports.logger.error({ err, origin }, `Uncaught exception.`);
|
|
171
|
-
});
|
|
172
|
-
const extractQueryParams = (url) => {
|
|
173
|
-
const object = new URL(url);
|
|
174
|
-
const query = Object.fromEntries(object.searchParams.entries());
|
|
175
|
-
const keys = Object.keys(query);
|
|
176
|
-
keys.forEach((key) => object.searchParams.delete(key));
|
|
177
|
-
return { url: object.toString(), query: keys.length > 0 ? query : undefined };
|
|
178
|
-
};
|
|
179
|
-
const getFullUrl = (req) => {
|
|
180
|
-
const url = req.originalUrl || req.url;
|
|
181
|
-
if (url?.startsWith('http://') || url?.startsWith('https://'))
|
|
182
|
-
return url;
|
|
183
|
-
// Check if we have a workflow URL configured (preferred method)
|
|
184
|
-
if (process.env.UNNBOUND_WORKFLOW_URL) {
|
|
185
|
-
// Use workflow URL as the base URL
|
|
186
|
-
return `https://${process.env.UNNBOUND_WORKFLOW_URL.replace(/\/$/, '')}${url}`;
|
|
187
|
-
}
|
|
188
|
-
// Fallback to constructing from request info for incoming requests
|
|
189
|
-
const protocol = req.protocol || (req.secure ? 'https' : 'http');
|
|
190
|
-
const host = req.get('host') || req.get('x-forwarded-host') || 'localhost';
|
|
191
|
-
return `${protocol}://${host}${url}`;
|
|
192
|
-
};
|
|
193
|
-
const buildHttpIncomingHttpPayload = (req, res) => ({
|
|
194
|
-
type: 'http',
|
|
195
|
-
http: {
|
|
196
|
-
...extractQueryParams(getFullUrl(req)),
|
|
197
|
-
method: req.method.toLowerCase(),
|
|
198
|
-
ip: normalizeIp(req.ip),
|
|
199
|
-
incoming: true,
|
|
200
|
-
request: {
|
|
201
|
-
headers: req.headers,
|
|
202
|
-
body: safeJsonParse(req.body),
|
|
203
|
-
},
|
|
204
|
-
response: res
|
|
205
|
-
? {
|
|
206
|
-
headers: res.headers,
|
|
207
|
-
status: res.status,
|
|
208
|
-
body: safeJsonParse(res.body),
|
|
209
|
-
}
|
|
210
|
-
: undefined,
|
|
211
|
-
},
|
|
212
|
-
});
|
|
213
|
-
const getHttpNoopPayload = () => ({});
|
|
214
|
-
const traceMiddleware = ({ ignoreTraceRoutes = exports.defaultIgnoreTraceRoutes, traceHeaderKey = exports.defaultTraceHeaderKey, messageHeaderKey = exports.defaultMessageHeaderKey, getPayload = getHttpNoopPayload, } = {
|
|
215
|
-
ignoreTraceRoutes: exports.defaultIgnoreTraceRoutes,
|
|
216
|
-
traceHeaderKey: exports.defaultTraceHeaderKey,
|
|
217
|
-
messageHeaderKey: exports.defaultMessageHeaderKey,
|
|
218
|
-
getPayload: getHttpNoopPayload,
|
|
219
|
-
}) => async (req, res, next) => {
|
|
220
|
-
if ((0, exports.shouldIgnorePath)(req.path, ignoreTraceRoutes))
|
|
221
|
-
return next();
|
|
222
|
-
const traceId = req.header(traceHeaderKey) || (0, exports.getTraceId)();
|
|
223
|
-
const messageId = req.header(messageHeaderKey) || undefined;
|
|
224
|
-
res.setHeader(traceHeaderKey, traceId);
|
|
225
|
-
return await (0, exports.withTrace)(async () => {
|
|
226
|
-
return await (0, exports.startSpan)('Incoming HTTP request', async () => {
|
|
227
|
-
return new Promise((resolve) => {
|
|
228
|
-
// Capture response body for logging
|
|
229
|
-
const send = res.send.bind(res);
|
|
230
|
-
res.send = (body) => {
|
|
231
|
-
res.locals.body = body;
|
|
232
|
-
return send(body);
|
|
233
|
-
};
|
|
234
|
-
res.on('finish', () => resolve());
|
|
235
|
-
return next();
|
|
236
|
-
});
|
|
237
|
-
}, (o) => {
|
|
238
|
-
const response = o
|
|
239
|
-
? {
|
|
240
|
-
status: res.statusCode,
|
|
241
|
-
headers: res.getHeaders(),
|
|
242
|
-
body: res.locals.body,
|
|
243
|
-
}
|
|
244
|
-
: undefined;
|
|
245
|
-
return { ...buildHttpIncomingHttpPayload(req, response), ...getPayload(req, response) };
|
|
246
|
-
});
|
|
247
|
-
}, messageId ? { traceId, messageId } : { traceId });
|
|
248
|
-
};
|
|
249
|
-
exports.traceMiddleware = traceMiddleware;
|
|
250
|
-
/**
|
|
251
|
-
* Starts a span that tracks the duration of a callback
|
|
252
|
-
* @param spanName - The span name to use for logging
|
|
253
|
-
* @param callback - The async callback to execute
|
|
254
|
-
* @returns The result of the callback
|
|
255
|
-
*/
|
|
256
|
-
const startSpan = async (spanName, callback, getter) => {
|
|
257
|
-
const spanId = (0, uuid_1.v4)();
|
|
258
|
-
const start = performance.now();
|
|
259
|
-
const previous = exports.storage.getStore();
|
|
260
|
-
return exports.storage.run({
|
|
261
|
-
...previous,
|
|
262
|
-
traceId: previous?.traceId ?? (0, exports.getTraceId)(),
|
|
263
|
-
spanId: previous?.spanId ? `${spanId} ${previous?.spanId}` : spanId,
|
|
264
|
-
}, async () => {
|
|
265
|
-
exports.logger.info({ ...getLogPayload(getter) }, `${spanName} started.`);
|
|
266
|
-
try {
|
|
267
|
-
const result = await callback();
|
|
268
|
-
exports.logger.info({ ...getLogPayload(getter, { result }), duration: getDuration(start) }, `${spanName} completed.`);
|
|
269
|
-
return result;
|
|
270
|
-
}
|
|
271
|
-
catch (error) {
|
|
272
|
-
exports.logger.error({ ...getLogPayload(getter, { error }), err: error, duration: getDuration(start) }, `${spanName} failed.`);
|
|
273
|
-
throw error;
|
|
274
|
-
}
|
|
275
|
-
});
|
|
276
|
-
};
|
|
277
|
-
exports.startSpan = startSpan;
|
|
278
|
-
const getLogPayload = (getter, o) => {
|
|
279
|
-
if (typeof getter !== 'function')
|
|
280
|
-
return getter;
|
|
281
|
-
return getter(o);
|
|
282
|
-
};
|
|
283
|
-
const getDuration = (start) => Math.round(performance.now() - start);
|
|
284
|
-
const async_hooks_1 = require("async_hooks");
|
|
285
|
-
exports.storage = new async_hooks_1.AsyncLocalStorage();
|
|
286
|
-
const uuid_1 = require("uuid");
|
|
287
|
-
/**
|
|
288
|
-
* Generates a trace ID
|
|
289
|
-
* @returns A trace ID
|
|
290
|
-
*/
|
|
291
|
-
const getTraceId = () => (0, uuid_1.v4)();
|
|
292
|
-
exports.getTraceId = getTraceId;
|
|
293
|
-
/**
|
|
294
|
-
* Generates a message ID
|
|
295
|
-
* @returns A message ID
|
|
296
|
-
*/
|
|
297
|
-
const getMessageId = () => (0, uuid_1.v4)();
|
|
298
|
-
exports.getMessageId = getMessageId;
|
|
299
|
-
/**
|
|
300
|
-
* Runs a callback with a trace ID
|
|
301
|
-
* @param callback - The callback to run
|
|
302
|
-
* @param extra - Extra context to add to the trace
|
|
303
|
-
* @returns The result of the callback
|
|
304
|
-
*/
|
|
305
|
-
const withTrace = (callback, extra) => {
|
|
306
|
-
const previous = exports.storage.getStore();
|
|
307
|
-
const traceId = extra?.traceId ?? previous?.traceId ?? (0, exports.getTraceId)();
|
|
308
|
-
const messageId = extra?.messageId ?? previous?.messageId ?? (0, exports.getMessageId)();
|
|
309
|
-
return exports.storage.run({ ...previous, ...extra, traceId, messageId }, callback);
|
|
310
|
-
};
|
|
311
|
-
exports.withTrace = withTrace;
|
|
312
|
-
exports.defaultIgnoreTraceRoutes = ['/health', '/healthcheck'];
|
|
313
|
-
exports.defaultTraceHeaderKey = 'x-unnbound-trace-id';
|
|
314
|
-
exports.defaultMessageHeaderKey = 'x-message-id';
|
|
315
|
-
/**
|
|
316
|
-
* Checks if a path matches any of the ignore patterns
|
|
317
|
-
* @param path - The path to check
|
|
318
|
-
* @param patterns - Array of glob patterns to match against
|
|
319
|
-
* @returns boolean indicating if the path should be ignored
|
|
320
|
-
*/
|
|
321
|
-
const shouldIgnorePath = (path, patterns) => {
|
|
322
|
-
return patterns.some((pattern) => {
|
|
323
|
-
// Convert glob pattern to regex
|
|
324
|
-
const regexPattern = pattern
|
|
325
|
-
.replace(/\./g, '\\.') // Escape dots
|
|
326
|
-
.replace(/\*/g, '.*') // Convert * to .*
|
|
327
|
-
.replace(/\?/g, '.'); // Convert ? to .
|
|
328
|
-
const regex = new RegExp(`^${regexPattern}$`);
|
|
329
|
-
return regex.test(path);
|
|
330
|
-
});
|
|
331
|
-
};
|
|
332
|
-
exports.shouldIgnorePath = shouldIgnorePath;
|
|
333
|
-
/**
|
|
334
|
-
* Safely parses JSON strings, returning the original data if parsing fails or if it's not a string.
|
|
335
|
-
* @param data The data to potentially parse as JSON.
|
|
336
|
-
* @returns Parsed JSON object or the original data.
|
|
337
|
-
*/
|
|
338
|
-
function safeJsonParse(data) {
|
|
339
|
-
if (typeof data === 'string') {
|
|
340
|
-
try {
|
|
341
|
-
return JSON.parse(data);
|
|
342
|
-
}
|
|
343
|
-
catch {
|
|
344
|
-
return data;
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
return data;
|
|
348
|
-
}
|
|
349
|
-
/**
|
|
350
|
-
* Normalizes IP addresses by removing IPv6 mapping prefix for IPv4 addresses.
|
|
351
|
-
* @param ip The IP address to normalize.
|
|
352
|
-
* @returns Normalized IP address string.
|
|
353
|
-
*/
|
|
354
|
-
function normalizeIp(ip) {
|
|
355
|
-
if (!ip)
|
|
356
|
-
return ip;
|
|
357
|
-
// Remove IPv4-mapped IPv6 prefix (::ffff:) to get clean IPv4 address
|
|
358
|
-
if (ip.startsWith('::ffff:')) {
|
|
359
|
-
return ip.substring(7);
|
|
360
|
-
}
|
|
361
|
-
return ip;
|
|
362
|
-
}
|