apitally 0.6.0 → 0.7.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.
- package/dist/common/client.cjs +514 -0
- package/dist/common/client.cjs.map +1 -0
- package/dist/common/client.d.cts +36 -0
- package/{lib/types → dist}/common/client.d.ts +13 -9
- package/dist/common/client.js +481 -0
- package/dist/common/client.js.map +1 -0
- package/dist/common/logging.cjs +41 -0
- package/dist/common/logging.cjs.map +1 -0
- package/dist/common/logging.d.cts +11 -0
- package/{lib/types → dist}/common/logging.d.ts +6 -3
- package/dist/common/logging.js +18 -0
- package/dist/common/logging.js.map +1 -0
- package/dist/common/packageVersions.cjs +42 -0
- package/dist/common/packageVersions.cjs.map +1 -0
- package/dist/common/packageVersions.d.cts +3 -0
- package/dist/common/packageVersions.d.ts +3 -0
- package/dist/common/packageVersions.js +18 -0
- package/dist/common/packageVersions.js.map +1 -0
- package/dist/common/paramValidation.cjs +43 -0
- package/dist/common/paramValidation.cjs.map +1 -0
- package/dist/common/paramValidation.d.cts +4 -0
- package/dist/common/paramValidation.d.ts +4 -0
- package/dist/common/paramValidation.js +19 -0
- package/dist/common/paramValidation.js.map +1 -0
- package/dist/common/requestCounter.cjs +111 -0
- package/dist/common/requestCounter.cjs.map +1 -0
- package/dist/common/requestCounter.d.cts +18 -0
- package/{lib/types → dist}/common/requestCounter.d.ts +7 -3
- package/dist/common/requestCounter.js +92 -0
- package/dist/common/requestCounter.js.map +1 -0
- package/dist/common/serverErrorCounter.cjs +133 -0
- package/dist/common/serverErrorCounter.cjs.map +1 -0
- package/dist/common/serverErrorCounter.d.cts +20 -0
- package/{lib/types → dist}/common/serverErrorCounter.d.ts +7 -3
- package/dist/common/serverErrorCounter.js +104 -0
- package/dist/common/serverErrorCounter.js.map +1 -0
- package/dist/common/types.cjs +19 -0
- package/dist/common/types.cjs.map +1 -0
- package/dist/common/types.d.cts +76 -0
- package/{lib/types → dist}/common/types.d.ts +17 -14
- package/dist/common/types.js +1 -0
- package/dist/common/types.js.map +1 -0
- package/dist/common/validationErrorCounter.cjs +76 -0
- package/dist/common/validationErrorCounter.cjs.map +1 -0
- package/dist/common/validationErrorCounter.d.cts +14 -0
- package/{lib/types → dist}/common/validationErrorCounter.d.ts +7 -3
- package/dist/common/validationErrorCounter.js +57 -0
- package/dist/common/validationErrorCounter.js.map +1 -0
- package/dist/express/index.cjs +837 -0
- package/dist/express/index.cjs.map +1 -0
- package/dist/express/index.d.cts +5 -0
- package/dist/express/index.d.ts +5 -0
- package/dist/express/index.js +801 -0
- package/dist/express/index.js.map +1 -0
- package/dist/express/listEndpoints.cjs +144 -0
- package/dist/express/listEndpoints.cjs.map +1 -0
- package/dist/express/listEndpoints.d.cts +3 -0
- package/dist/express/listEndpoints.d.ts +3 -0
- package/dist/express/listEndpoints.js +125 -0
- package/dist/express/listEndpoints.js.map +1 -0
- package/dist/express/middleware.cjs +835 -0
- package/dist/express/middleware.cjs.map +1 -0
- package/dist/express/middleware.d.cts +14 -0
- package/dist/express/middleware.d.ts +14 -0
- package/dist/express/middleware.js +801 -0
- package/dist/express/middleware.js.map +1 -0
- package/dist/fastify/index.cjs +685 -0
- package/dist/fastify/index.cjs.map +1 -0
- package/dist/fastify/index.d.cts +5 -0
- package/dist/fastify/index.d.ts +5 -0
- package/dist/fastify/index.js +649 -0
- package/dist/fastify/index.js.map +1 -0
- package/dist/fastify/plugin.cjs +679 -0
- package/dist/fastify/plugin.cjs.map +1 -0
- package/dist/fastify/plugin.d.cts +18 -0
- package/{lib/types → dist}/fastify/plugin.d.ts +7 -4
- package/dist/fastify/plugin.js +649 -0
- package/dist/fastify/plugin.js.map +1 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -0
- package/dist/koa/index.cjs +655 -0
- package/dist/koa/index.cjs.map +1 -0
- package/dist/koa/index.d.cts +5 -0
- package/dist/koa/index.d.ts +5 -0
- package/dist/koa/index.js +619 -0
- package/dist/koa/index.js.map +1 -0
- package/dist/koa/middleware.cjs +655 -0
- package/dist/koa/middleware.cjs.map +1 -0
- package/dist/koa/middleware.d.cts +8 -0
- package/dist/koa/middleware.d.ts +8 -0
- package/dist/koa/middleware.js +619 -0
- package/dist/koa/middleware.js.map +1 -0
- package/dist/nestjs/index.cjs +837 -0
- package/dist/nestjs/index.cjs.map +1 -0
- package/dist/nestjs/index.d.cts +5 -0
- package/dist/nestjs/index.d.ts +5 -0
- package/dist/nestjs/index.js +801 -0
- package/dist/nestjs/index.js.map +1 -0
- package/package.json +55 -92
- package/lib/cjs/common/client.cjs +0 -323
- package/lib/cjs/common/client.cjs.map +0 -1
- package/lib/cjs/common/logging.cjs +0 -17
- package/lib/cjs/common/logging.cjs.map +0 -1
- package/lib/cjs/common/packageVersions.cjs +0 -16
- package/lib/cjs/common/packageVersions.cjs.map +0 -1
- package/lib/cjs/common/paramValidation.cjs +0 -16
- package/lib/cjs/common/paramValidation.cjs.map +0 -1
- package/lib/cjs/common/requestCounter.cjs +0 -108
- package/lib/cjs/common/requestCounter.cjs.map +0 -1
- package/lib/cjs/common/serverErrorCounter.cjs +0 -154
- package/lib/cjs/common/serverErrorCounter.cjs.map +0 -1
- package/lib/cjs/common/types.cjs +0 -6
- package/lib/cjs/common/types.cjs.map +0 -1
- package/lib/cjs/common/validationErrorCounter.cjs +0 -60
- package/lib/cjs/common/validationErrorCounter.cjs.map +0 -1
- package/lib/cjs/express/index.cjs +0 -13
- package/lib/cjs/express/index.cjs.map +0 -1
- package/lib/cjs/express/listEndpoints.cjs +0 -177
- package/lib/cjs/express/listEndpoints.cjs.map +0 -1
- package/lib/cjs/express/middleware.cjs +0 -189
- package/lib/cjs/express/middleware.cjs.map +0 -1
- package/lib/cjs/fastify/index.cjs +0 -14
- package/lib/cjs/fastify/index.cjs.map +0 -1
- package/lib/cjs/fastify/plugin.cjs +0 -171
- package/lib/cjs/fastify/plugin.cjs.map +0 -1
- package/lib/cjs/index.cjs +0 -6
- package/lib/cjs/index.cjs.map +0 -1
- package/lib/cjs/koa/index.cjs +0 -13
- package/lib/cjs/koa/index.cjs.map +0 -1
- package/lib/cjs/koa/middleware.cjs +0 -139
- package/lib/cjs/koa/middleware.cjs.map +0 -1
- package/lib/cjs/nestjs/index.cjs +0 -13
- package/lib/cjs/nestjs/index.cjs.map +0 -1
- package/lib/esm/common/client.js +0 -313
- package/lib/esm/common/client.js.map +0 -1
- package/lib/esm/common/logging.js +0 -11
- package/lib/esm/common/logging.js.map +0 -1
- package/lib/esm/common/packageVersions.js +0 -10
- package/lib/esm/common/packageVersions.js.map +0 -1
- package/lib/esm/common/paramValidation.js +0 -9
- package/lib/esm/common/paramValidation.js.map +0 -1
- package/lib/esm/common/requestCounter.js +0 -102
- package/lib/esm/common/requestCounter.js.map +0 -1
- package/lib/esm/common/serverErrorCounter.js +0 -143
- package/lib/esm/common/serverErrorCounter.js.map +0 -1
- package/lib/esm/common/types.js +0 -1
- package/lib/esm/common/types.js.map +0 -1
- package/lib/esm/common/validationErrorCounter.js +0 -54
- package/lib/esm/common/validationErrorCounter.js.map +0 -1
- package/lib/esm/express/index.js +0 -1
- package/lib/esm/express/index.js.map +0 -1
- package/lib/esm/express/listEndpoints.js +0 -170
- package/lib/esm/express/listEndpoints.js.map +0 -1
- package/lib/esm/express/middleware.js +0 -182
- package/lib/esm/express/middleware.js.map +0 -1
- package/lib/esm/fastify/index.js +0 -1
- package/lib/esm/fastify/index.js.map +0 -1
- package/lib/esm/fastify/plugin.js +0 -164
- package/lib/esm/fastify/plugin.js.map +0 -1
- package/lib/esm/index.js +0 -1
- package/lib/esm/index.js.map +0 -1
- package/lib/esm/koa/index.js +0 -1
- package/lib/esm/koa/index.js.map +0 -1
- package/lib/esm/koa/middleware.js +0 -132
- package/lib/esm/koa/middleware.js.map +0 -1
- package/lib/esm/nestjs/index.js +0 -1
- package/lib/esm/nestjs/index.js.map +0 -1
- package/lib/types/common/client.d.ts.map +0 -1
- package/lib/types/common/logging.d.ts.map +0 -1
- package/lib/types/common/packageVersions.d.ts +0 -2
- package/lib/types/common/packageVersions.d.ts.map +0 -1
- package/lib/types/common/paramValidation.d.ts +0 -3
- package/lib/types/common/paramValidation.d.ts.map +0 -1
- package/lib/types/common/requestCounter.d.ts.map +0 -1
- package/lib/types/common/serverErrorCounter.d.ts.map +0 -1
- package/lib/types/common/types.d.ts.map +0 -1
- package/lib/types/common/validationErrorCounter.d.ts.map +0 -1
- package/lib/types/express/index.d.ts +0 -2
- package/lib/types/express/index.d.ts.map +0 -1
- package/lib/types/express/listEndpoints.d.ts +0 -3
- package/lib/types/express/listEndpoints.d.ts.map +0 -1
- package/lib/types/express/middleware.d.ts +0 -10
- package/lib/types/express/middleware.d.ts.map +0 -1
- package/lib/types/fastify/index.d.ts +0 -2
- package/lib/types/fastify/index.d.ts.map +0 -1
- package/lib/types/fastify/plugin.d.ts.map +0 -1
- package/lib/types/index.d.ts +0 -2
- package/lib/types/index.d.ts.map +0 -1
- package/lib/types/koa/index.d.ts +0 -2
- package/lib/types/koa/index.d.ts.map +0 -1
- package/lib/types/koa/middleware.d.ts +0 -4
- package/lib/types/koa/middleware.d.ts.map +0 -1
- package/lib/types/nestjs/index.d.ts +0 -2
- package/lib/types/nestjs/index.d.ts.map +0 -1
|
@@ -0,0 +1,801 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
4
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
5
|
+
|
|
6
|
+
// src/express/middleware.ts
|
|
7
|
+
import { performance } from "perf_hooks";
|
|
8
|
+
|
|
9
|
+
// src/common/client.ts
|
|
10
|
+
import { randomUUID } from "crypto";
|
|
11
|
+
import fetchRetry from "fetch-retry";
|
|
12
|
+
|
|
13
|
+
// src/common/logging.ts
|
|
14
|
+
import { createLogger, format, transports } from "winston";
|
|
15
|
+
var getLogger = /* @__PURE__ */ __name(() => {
|
|
16
|
+
return createLogger({
|
|
17
|
+
level: process.env.APITALLY_DEBUG ? "debug" : "warn",
|
|
18
|
+
format: format.combine(format.colorize(), format.timestamp(), format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`)),
|
|
19
|
+
transports: [
|
|
20
|
+
new transports.Console()
|
|
21
|
+
]
|
|
22
|
+
});
|
|
23
|
+
}, "getLogger");
|
|
24
|
+
|
|
25
|
+
// src/common/paramValidation.ts
|
|
26
|
+
function isValidClientId(clientId) {
|
|
27
|
+
const regexExp = /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
28
|
+
return regexExp.test(clientId);
|
|
29
|
+
}
|
|
30
|
+
__name(isValidClientId, "isValidClientId");
|
|
31
|
+
function isValidEnv(env) {
|
|
32
|
+
const regexExp = /^[\w-]{1,32}$/;
|
|
33
|
+
return regexExp.test(env);
|
|
34
|
+
}
|
|
35
|
+
__name(isValidEnv, "isValidEnv");
|
|
36
|
+
|
|
37
|
+
// src/common/requestCounter.ts
|
|
38
|
+
var _RequestCounter = class _RequestCounter {
|
|
39
|
+
requestCounts;
|
|
40
|
+
requestSizeSums;
|
|
41
|
+
responseSizeSums;
|
|
42
|
+
responseTimes;
|
|
43
|
+
requestSizes;
|
|
44
|
+
responseSizes;
|
|
45
|
+
constructor() {
|
|
46
|
+
this.requestCounts = /* @__PURE__ */ new Map();
|
|
47
|
+
this.requestSizeSums = /* @__PURE__ */ new Map();
|
|
48
|
+
this.responseSizeSums = /* @__PURE__ */ new Map();
|
|
49
|
+
this.responseTimes = /* @__PURE__ */ new Map();
|
|
50
|
+
this.requestSizes = /* @__PURE__ */ new Map();
|
|
51
|
+
this.responseSizes = /* @__PURE__ */ new Map();
|
|
52
|
+
}
|
|
53
|
+
getKey(requestInfo) {
|
|
54
|
+
return [
|
|
55
|
+
requestInfo.consumer || "",
|
|
56
|
+
requestInfo.method.toUpperCase(),
|
|
57
|
+
requestInfo.path,
|
|
58
|
+
requestInfo.statusCode
|
|
59
|
+
].join("|");
|
|
60
|
+
}
|
|
61
|
+
addRequest(requestInfo) {
|
|
62
|
+
const key = this.getKey(requestInfo);
|
|
63
|
+
this.requestCounts.set(key, (this.requestCounts.get(key) || 0) + 1);
|
|
64
|
+
if (!this.responseTimes.has(key)) {
|
|
65
|
+
this.responseTimes.set(key, /* @__PURE__ */ new Map());
|
|
66
|
+
}
|
|
67
|
+
const responseTimeMap = this.responseTimes.get(key);
|
|
68
|
+
const responseTimeMsBin = Math.floor(requestInfo.responseTime / 10) * 10;
|
|
69
|
+
responseTimeMap.set(responseTimeMsBin, (responseTimeMap.get(responseTimeMsBin) || 0) + 1);
|
|
70
|
+
if (requestInfo.requestSize !== void 0) {
|
|
71
|
+
requestInfo.requestSize = Number(requestInfo.requestSize);
|
|
72
|
+
this.requestSizeSums.set(key, (this.requestSizeSums.get(key) || 0) + requestInfo.requestSize);
|
|
73
|
+
if (!this.requestSizes.has(key)) {
|
|
74
|
+
this.requestSizes.set(key, /* @__PURE__ */ new Map());
|
|
75
|
+
}
|
|
76
|
+
const requestSizeMap = this.requestSizes.get(key);
|
|
77
|
+
const requestSizeKbBin = Math.floor(requestInfo.requestSize / 1e3);
|
|
78
|
+
requestSizeMap.set(requestSizeKbBin, (requestSizeMap.get(requestSizeKbBin) || 0) + 1);
|
|
79
|
+
}
|
|
80
|
+
if (requestInfo.responseSize !== void 0) {
|
|
81
|
+
requestInfo.responseSize = Number(requestInfo.responseSize);
|
|
82
|
+
this.responseSizeSums.set(key, (this.responseSizeSums.get(key) || 0) + requestInfo.responseSize);
|
|
83
|
+
if (!this.responseSizes.has(key)) {
|
|
84
|
+
this.responseSizes.set(key, /* @__PURE__ */ new Map());
|
|
85
|
+
}
|
|
86
|
+
const responseSizeMap = this.responseSizes.get(key);
|
|
87
|
+
const responseSizeKbBin = Math.floor(requestInfo.responseSize / 1e3);
|
|
88
|
+
responseSizeMap.set(responseSizeKbBin, (responseSizeMap.get(responseSizeKbBin) || 0) + 1);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
getAndResetRequests() {
|
|
92
|
+
const data = [];
|
|
93
|
+
this.requestCounts.forEach((count, key) => {
|
|
94
|
+
const [consumer, method, path, statusCodeStr] = key.split("|");
|
|
95
|
+
const responseTimes = this.responseTimes.get(key) || /* @__PURE__ */ new Map();
|
|
96
|
+
const requestSizes = this.requestSizes.get(key) || /* @__PURE__ */ new Map();
|
|
97
|
+
const responseSizes = this.responseSizes.get(key) || /* @__PURE__ */ new Map();
|
|
98
|
+
data.push({
|
|
99
|
+
consumer: consumer || null,
|
|
100
|
+
method,
|
|
101
|
+
path,
|
|
102
|
+
status_code: parseInt(statusCodeStr),
|
|
103
|
+
request_count: count,
|
|
104
|
+
request_size_sum: this.requestSizeSums.get(key) || 0,
|
|
105
|
+
response_size_sum: this.responseSizeSums.get(key) || 0,
|
|
106
|
+
response_times: Object.fromEntries(responseTimes),
|
|
107
|
+
request_sizes: Object.fromEntries(requestSizes),
|
|
108
|
+
response_sizes: Object.fromEntries(responseSizes)
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
this.requestCounts.clear();
|
|
112
|
+
this.requestSizeSums.clear();
|
|
113
|
+
this.responseSizeSums.clear();
|
|
114
|
+
this.responseTimes.clear();
|
|
115
|
+
this.requestSizes.clear();
|
|
116
|
+
this.responseSizes.clear();
|
|
117
|
+
return data;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
__name(_RequestCounter, "RequestCounter");
|
|
121
|
+
var RequestCounter = _RequestCounter;
|
|
122
|
+
|
|
123
|
+
// src/common/serverErrorCounter.ts
|
|
124
|
+
import { createHash } from "crypto";
|
|
125
|
+
var MAX_MSG_LENGTH = 2048;
|
|
126
|
+
var MAX_STACKTRACE_LENGTH = 65536;
|
|
127
|
+
var _ServerErrorCounter = class _ServerErrorCounter {
|
|
128
|
+
errorCounts;
|
|
129
|
+
errorDetails;
|
|
130
|
+
sentryEventIds;
|
|
131
|
+
sentry;
|
|
132
|
+
constructor() {
|
|
133
|
+
this.errorCounts = /* @__PURE__ */ new Map();
|
|
134
|
+
this.errorDetails = /* @__PURE__ */ new Map();
|
|
135
|
+
this.sentryEventIds = /* @__PURE__ */ new Map();
|
|
136
|
+
this.tryImportSentry();
|
|
137
|
+
}
|
|
138
|
+
addServerError(serverError) {
|
|
139
|
+
const key = this.getKey(serverError);
|
|
140
|
+
if (!this.errorDetails.has(key)) {
|
|
141
|
+
this.errorDetails.set(key, serverError);
|
|
142
|
+
}
|
|
143
|
+
this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
|
|
144
|
+
this.captureSentryEventId(key);
|
|
145
|
+
}
|
|
146
|
+
getAndResetServerErrors() {
|
|
147
|
+
const data = [];
|
|
148
|
+
this.errorCounts.forEach((count, key) => {
|
|
149
|
+
const serverError = this.errorDetails.get(key);
|
|
150
|
+
if (serverError) {
|
|
151
|
+
data.push({
|
|
152
|
+
consumer: serverError.consumer || null,
|
|
153
|
+
method: serverError.method,
|
|
154
|
+
path: serverError.path,
|
|
155
|
+
type: serverError.type,
|
|
156
|
+
msg: this.getTruncatedMessage(serverError.msg),
|
|
157
|
+
traceback: this.getTruncatedStack(serverError.traceback),
|
|
158
|
+
sentry_event_id: this.sentryEventIds.get(key) || null,
|
|
159
|
+
error_count: count
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
this.errorCounts.clear();
|
|
164
|
+
this.errorDetails.clear();
|
|
165
|
+
return data;
|
|
166
|
+
}
|
|
167
|
+
getKey(serverError) {
|
|
168
|
+
const hashInput = [
|
|
169
|
+
serverError.consumer || "",
|
|
170
|
+
serverError.method.toUpperCase(),
|
|
171
|
+
serverError.path,
|
|
172
|
+
serverError.type,
|
|
173
|
+
serverError.msg.trim(),
|
|
174
|
+
serverError.traceback.trim()
|
|
175
|
+
].join("|");
|
|
176
|
+
return createHash("md5").update(hashInput).digest("hex");
|
|
177
|
+
}
|
|
178
|
+
getTruncatedMessage(msg) {
|
|
179
|
+
msg = msg.trim();
|
|
180
|
+
if (msg.length <= MAX_MSG_LENGTH) {
|
|
181
|
+
return msg;
|
|
182
|
+
}
|
|
183
|
+
const suffix = "... (truncated)";
|
|
184
|
+
const cutoff = MAX_MSG_LENGTH - suffix.length;
|
|
185
|
+
return msg.substring(0, cutoff) + suffix;
|
|
186
|
+
}
|
|
187
|
+
getTruncatedStack(stack) {
|
|
188
|
+
const suffix = "... (truncated) ...";
|
|
189
|
+
const cutoff = MAX_STACKTRACE_LENGTH - suffix.length;
|
|
190
|
+
const lines = stack.trim().split("\n");
|
|
191
|
+
const truncatedLines = [];
|
|
192
|
+
let length = 0;
|
|
193
|
+
for (const line of lines) {
|
|
194
|
+
if (length + line.length + 1 > cutoff) {
|
|
195
|
+
truncatedLines.push(suffix);
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
truncatedLines.push(line);
|
|
199
|
+
length += line.length + 1;
|
|
200
|
+
}
|
|
201
|
+
return truncatedLines.join("\n");
|
|
202
|
+
}
|
|
203
|
+
captureSentryEventId(serverErrorKey) {
|
|
204
|
+
if (this.sentry && this.sentry.lastEventId) {
|
|
205
|
+
const eventId = this.sentry.lastEventId();
|
|
206
|
+
if (eventId) {
|
|
207
|
+
this.sentryEventIds.set(serverErrorKey, eventId);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
async tryImportSentry() {
|
|
212
|
+
try {
|
|
213
|
+
this.sentry = await import("@sentry/node");
|
|
214
|
+
} catch (e) {
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
__name(_ServerErrorCounter, "ServerErrorCounter");
|
|
219
|
+
var ServerErrorCounter = _ServerErrorCounter;
|
|
220
|
+
|
|
221
|
+
// src/common/validationErrorCounter.ts
|
|
222
|
+
import { createHash as createHash2 } from "crypto";
|
|
223
|
+
var _ValidationErrorCounter = class _ValidationErrorCounter {
|
|
224
|
+
errorCounts;
|
|
225
|
+
errorDetails;
|
|
226
|
+
constructor() {
|
|
227
|
+
this.errorCounts = /* @__PURE__ */ new Map();
|
|
228
|
+
this.errorDetails = /* @__PURE__ */ new Map();
|
|
229
|
+
}
|
|
230
|
+
addValidationError(validationError) {
|
|
231
|
+
const key = this.getKey(validationError);
|
|
232
|
+
if (!this.errorDetails.has(key)) {
|
|
233
|
+
this.errorDetails.set(key, validationError);
|
|
234
|
+
}
|
|
235
|
+
this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
|
|
236
|
+
}
|
|
237
|
+
getAndResetValidationErrors() {
|
|
238
|
+
const data = [];
|
|
239
|
+
this.errorCounts.forEach((count, key) => {
|
|
240
|
+
const validationError = this.errorDetails.get(key);
|
|
241
|
+
if (validationError) {
|
|
242
|
+
data.push({
|
|
243
|
+
consumer: validationError.consumer || null,
|
|
244
|
+
method: validationError.method,
|
|
245
|
+
path: validationError.path,
|
|
246
|
+
loc: validationError.loc.split("."),
|
|
247
|
+
msg: validationError.msg,
|
|
248
|
+
type: validationError.type,
|
|
249
|
+
error_count: count
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
this.errorCounts.clear();
|
|
254
|
+
this.errorDetails.clear();
|
|
255
|
+
return data;
|
|
256
|
+
}
|
|
257
|
+
getKey(validationError) {
|
|
258
|
+
const hashInput = [
|
|
259
|
+
validationError.consumer || "",
|
|
260
|
+
validationError.method.toUpperCase(),
|
|
261
|
+
validationError.path,
|
|
262
|
+
validationError.loc,
|
|
263
|
+
validationError.msg.trim(),
|
|
264
|
+
validationError.type
|
|
265
|
+
].join("|");
|
|
266
|
+
return createHash2("md5").update(hashInput).digest("hex");
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
__name(_ValidationErrorCounter, "ValidationErrorCounter");
|
|
270
|
+
var ValidationErrorCounter = _ValidationErrorCounter;
|
|
271
|
+
|
|
272
|
+
// src/common/client.ts
|
|
273
|
+
var SYNC_INTERVAL = 6e4;
|
|
274
|
+
var INITIAL_SYNC_INTERVAL = 1e4;
|
|
275
|
+
var INITIAL_SYNC_INTERVAL_DURATION = 36e5;
|
|
276
|
+
var MAX_QUEUE_TIME = 36e5;
|
|
277
|
+
var _a;
|
|
278
|
+
var HTTPError = (_a = class extends Error {
|
|
279
|
+
response;
|
|
280
|
+
constructor(response) {
|
|
281
|
+
const reason = response.status ? `status code ${response.status}` : "an unknown error";
|
|
282
|
+
super(`Request failed with ${reason}`);
|
|
283
|
+
this.response = response;
|
|
284
|
+
}
|
|
285
|
+
}, __name(_a, "HTTPError"), _a);
|
|
286
|
+
var _ApitallyClient = class _ApitallyClient {
|
|
287
|
+
clientId;
|
|
288
|
+
env;
|
|
289
|
+
instanceUuid;
|
|
290
|
+
requestsDataQueue;
|
|
291
|
+
syncIntervalId;
|
|
292
|
+
appInfo;
|
|
293
|
+
appInfoSent = false;
|
|
294
|
+
requestCounter;
|
|
295
|
+
validationErrorCounter;
|
|
296
|
+
serverErrorCounter;
|
|
297
|
+
logger;
|
|
298
|
+
constructor({ clientId, env = "dev", logger }) {
|
|
299
|
+
if (_ApitallyClient.instance) {
|
|
300
|
+
throw new Error("Apitally client is already initialized");
|
|
301
|
+
}
|
|
302
|
+
if (!isValidClientId(clientId)) {
|
|
303
|
+
throw new Error(`Invalid client ID '${clientId}' (expecting hexadeciaml UUID format)`);
|
|
304
|
+
}
|
|
305
|
+
if (!isValidEnv(env)) {
|
|
306
|
+
throw new Error(`Invalid env '${env}' (expecting 1-32 alphanumeric lowercase characters and hyphens only)`);
|
|
307
|
+
}
|
|
308
|
+
_ApitallyClient.instance = this;
|
|
309
|
+
this.clientId = clientId;
|
|
310
|
+
this.env = env;
|
|
311
|
+
this.instanceUuid = randomUUID();
|
|
312
|
+
this.requestsDataQueue = [];
|
|
313
|
+
this.requestCounter = new RequestCounter();
|
|
314
|
+
this.validationErrorCounter = new ValidationErrorCounter();
|
|
315
|
+
this.serverErrorCounter = new ServerErrorCounter();
|
|
316
|
+
this.logger = logger || getLogger();
|
|
317
|
+
this.startSync();
|
|
318
|
+
this.handleShutdown = this.handleShutdown.bind(this);
|
|
319
|
+
}
|
|
320
|
+
static getInstance() {
|
|
321
|
+
if (!_ApitallyClient.instance) {
|
|
322
|
+
throw new Error("Apitally client is not initialized");
|
|
323
|
+
}
|
|
324
|
+
return _ApitallyClient.instance;
|
|
325
|
+
}
|
|
326
|
+
static async shutdown() {
|
|
327
|
+
if (_ApitallyClient.instance) {
|
|
328
|
+
await _ApitallyClient.instance.handleShutdown();
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
async handleShutdown() {
|
|
332
|
+
this.stopSync();
|
|
333
|
+
await this.sendRequestsData();
|
|
334
|
+
_ApitallyClient.instance = void 0;
|
|
335
|
+
}
|
|
336
|
+
getHubUrlPrefix() {
|
|
337
|
+
const baseURL = process.env.APITALLY_HUB_BASE_URL || "https://hub.apitally.io";
|
|
338
|
+
const version = "v1";
|
|
339
|
+
return `${baseURL}/${version}/${this.clientId}/${this.env}/`;
|
|
340
|
+
}
|
|
341
|
+
async makeHubRequest(url, payload) {
|
|
342
|
+
const fetchWithRetry = fetchRetry(fetch, {
|
|
343
|
+
retries: 3,
|
|
344
|
+
retryDelay: 1e3,
|
|
345
|
+
retryOn: [
|
|
346
|
+
408,
|
|
347
|
+
429,
|
|
348
|
+
500,
|
|
349
|
+
502,
|
|
350
|
+
503,
|
|
351
|
+
504
|
|
352
|
+
]
|
|
353
|
+
});
|
|
354
|
+
const response = await fetchWithRetry(this.getHubUrlPrefix() + url, {
|
|
355
|
+
method: "POST",
|
|
356
|
+
body: JSON.stringify(payload),
|
|
357
|
+
headers: {
|
|
358
|
+
"Content-Type": "application/json"
|
|
359
|
+
}
|
|
360
|
+
});
|
|
361
|
+
if (!response.ok) {
|
|
362
|
+
throw new HTTPError(response);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
startSync() {
|
|
366
|
+
this.sync();
|
|
367
|
+
this.syncIntervalId = setInterval(() => {
|
|
368
|
+
this.sync();
|
|
369
|
+
}, INITIAL_SYNC_INTERVAL);
|
|
370
|
+
setTimeout(() => {
|
|
371
|
+
clearInterval(this.syncIntervalId);
|
|
372
|
+
this.syncIntervalId = setInterval(() => {
|
|
373
|
+
this.sync();
|
|
374
|
+
}, SYNC_INTERVAL);
|
|
375
|
+
}, INITIAL_SYNC_INTERVAL_DURATION);
|
|
376
|
+
}
|
|
377
|
+
async sync() {
|
|
378
|
+
try {
|
|
379
|
+
const promises = [
|
|
380
|
+
this.sendRequestsData()
|
|
381
|
+
];
|
|
382
|
+
if (!this.appInfoSent) {
|
|
383
|
+
promises.push(this.sendAppInfo());
|
|
384
|
+
}
|
|
385
|
+
await Promise.all(promises);
|
|
386
|
+
} catch (error) {
|
|
387
|
+
this.logger.error("Error while syncing with Apitally Hub", {
|
|
388
|
+
error
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
stopSync() {
|
|
393
|
+
if (this.syncIntervalId) {
|
|
394
|
+
clearInterval(this.syncIntervalId);
|
|
395
|
+
this.syncIntervalId = void 0;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
setAppInfo(appInfo) {
|
|
399
|
+
this.appInfo = appInfo;
|
|
400
|
+
this.appInfoSent = false;
|
|
401
|
+
this.sendAppInfo();
|
|
402
|
+
}
|
|
403
|
+
async sendAppInfo() {
|
|
404
|
+
if (this.appInfo) {
|
|
405
|
+
this.logger.debug("Sending app info to Apitally Hub");
|
|
406
|
+
const payload = {
|
|
407
|
+
instance_uuid: this.instanceUuid,
|
|
408
|
+
message_uuid: randomUUID(),
|
|
409
|
+
...this.appInfo
|
|
410
|
+
};
|
|
411
|
+
try {
|
|
412
|
+
await this.makeHubRequest("info", payload);
|
|
413
|
+
this.appInfoSent = true;
|
|
414
|
+
} catch (error) {
|
|
415
|
+
const handled = this.handleHubError(error);
|
|
416
|
+
if (!handled) {
|
|
417
|
+
this.logger.error(error.message);
|
|
418
|
+
this.logger.debug("Error while sending app info to Apitally Hub (will retry)", {
|
|
419
|
+
error
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
async sendRequestsData() {
|
|
426
|
+
this.logger.debug("Sending requests data to Apitally Hub");
|
|
427
|
+
const newPayload = {
|
|
428
|
+
time_offset: 0,
|
|
429
|
+
instance_uuid: this.instanceUuid,
|
|
430
|
+
message_uuid: randomUUID(),
|
|
431
|
+
requests: this.requestCounter.getAndResetRequests(),
|
|
432
|
+
validation_errors: this.validationErrorCounter.getAndResetValidationErrors(),
|
|
433
|
+
server_errors: this.serverErrorCounter.getAndResetServerErrors()
|
|
434
|
+
};
|
|
435
|
+
this.requestsDataQueue.push([
|
|
436
|
+
Date.now(),
|
|
437
|
+
newPayload
|
|
438
|
+
]);
|
|
439
|
+
const failedItems = [];
|
|
440
|
+
while (this.requestsDataQueue.length > 0) {
|
|
441
|
+
const queueItem = this.requestsDataQueue.shift();
|
|
442
|
+
if (queueItem) {
|
|
443
|
+
const [time, payload] = queueItem;
|
|
444
|
+
try {
|
|
445
|
+
const timeOffset = Date.now() - time;
|
|
446
|
+
if (timeOffset <= MAX_QUEUE_TIME) {
|
|
447
|
+
payload.time_offset = timeOffset / 1e3;
|
|
448
|
+
await this.makeHubRequest("requests", payload);
|
|
449
|
+
}
|
|
450
|
+
} catch (error) {
|
|
451
|
+
const handled = this.handleHubError(error);
|
|
452
|
+
if (!handled) {
|
|
453
|
+
this.logger.debug("Error while sending requests data to Apitally Hub (will retry)", {
|
|
454
|
+
error
|
|
455
|
+
});
|
|
456
|
+
failedItems.push(queueItem);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
this.requestsDataQueue = failedItems;
|
|
462
|
+
}
|
|
463
|
+
handleHubError(error) {
|
|
464
|
+
if (error instanceof HTTPError) {
|
|
465
|
+
if (error.response.status === 404) {
|
|
466
|
+
this.logger.error(`Invalid Apitally client ID: '${this.clientId}'`);
|
|
467
|
+
this.stopSync();
|
|
468
|
+
return true;
|
|
469
|
+
}
|
|
470
|
+
if (error.response.status === 422) {
|
|
471
|
+
this.logger.error("Received validation error from Apitally Hub");
|
|
472
|
+
return true;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return false;
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
__name(_ApitallyClient, "ApitallyClient");
|
|
479
|
+
__publicField(_ApitallyClient, "instance");
|
|
480
|
+
var ApitallyClient = _ApitallyClient;
|
|
481
|
+
|
|
482
|
+
// src/common/packageVersions.ts
|
|
483
|
+
import { createRequire } from "module";
|
|
484
|
+
function getPackageVersion(name) {
|
|
485
|
+
try {
|
|
486
|
+
const _require = createRequire(import.meta.url);
|
|
487
|
+
return _require(`${name}/package.json`).version || null;
|
|
488
|
+
} catch (error) {
|
|
489
|
+
return null;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
__name(getPackageVersion, "getPackageVersion");
|
|
493
|
+
|
|
494
|
+
// src/express/listEndpoints.js
|
|
495
|
+
var regExpToParseExpressPathRegExp = /^\/\^\\\/(?:(:?[\w\\.-]*(?:\\\/:?[\w\\.-]*)*)|(\(\?:\(\[\^\\\/]\+\?\)\)))\\\/.*/;
|
|
496
|
+
var regExpToReplaceExpressPathRegExpParams = /\(\?:\(\[\^\\\/]\+\?\)\)/;
|
|
497
|
+
var regexpExpressParamRegexp = /\(\?:\(\[\^\\\/]\+\?\)\)/g;
|
|
498
|
+
var EXPRESS_ROOT_PATH_REGEXP_VALUE = "/^\\/?(?=\\/|$)/i";
|
|
499
|
+
var STACK_ITEM_VALID_NAMES = [
|
|
500
|
+
"router",
|
|
501
|
+
"bound dispatch",
|
|
502
|
+
"mounted_app"
|
|
503
|
+
];
|
|
504
|
+
var getRouteMethods = /* @__PURE__ */ __name(function(route) {
|
|
505
|
+
let methods = Object.keys(route.methods);
|
|
506
|
+
methods = methods.filter((method) => method !== "_all");
|
|
507
|
+
methods = methods.map((method) => method.toUpperCase());
|
|
508
|
+
return methods;
|
|
509
|
+
}, "getRouteMethods");
|
|
510
|
+
var getRouteMiddlewares = /* @__PURE__ */ __name(function(route) {
|
|
511
|
+
return route.stack.map((item) => {
|
|
512
|
+
return item.handle.name || "anonymous";
|
|
513
|
+
});
|
|
514
|
+
}, "getRouteMiddlewares");
|
|
515
|
+
var hasParams = /* @__PURE__ */ __name(function(expressPathRegExp) {
|
|
516
|
+
return regexpExpressParamRegexp.test(expressPathRegExp);
|
|
517
|
+
}, "hasParams");
|
|
518
|
+
var parseExpressRoute = /* @__PURE__ */ __name(function(route, basePath) {
|
|
519
|
+
const paths = [];
|
|
520
|
+
if (Array.isArray(route.path)) {
|
|
521
|
+
paths.push(...route.path);
|
|
522
|
+
} else {
|
|
523
|
+
paths.push(route.path);
|
|
524
|
+
}
|
|
525
|
+
const endpoints = paths.map((path) => {
|
|
526
|
+
const completePath = basePath && path === "/" ? basePath : `${basePath}${path}`;
|
|
527
|
+
const endpoint = {
|
|
528
|
+
path: completePath,
|
|
529
|
+
methods: getRouteMethods(route),
|
|
530
|
+
middlewares: getRouteMiddlewares(route)
|
|
531
|
+
};
|
|
532
|
+
return endpoint;
|
|
533
|
+
});
|
|
534
|
+
return endpoints;
|
|
535
|
+
}, "parseExpressRoute");
|
|
536
|
+
var parseExpressPath = /* @__PURE__ */ __name(function(expressPathRegExp, params) {
|
|
537
|
+
let expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(expressPathRegExp);
|
|
538
|
+
let parsedRegExp = expressPathRegExp.toString();
|
|
539
|
+
let paramIndex = 0;
|
|
540
|
+
while (hasParams(parsedRegExp)) {
|
|
541
|
+
const paramName = params[paramIndex].name;
|
|
542
|
+
const paramId = `:${paramName}`;
|
|
543
|
+
parsedRegExp = parsedRegExp.replace(regExpToReplaceExpressPathRegExpParams, paramId);
|
|
544
|
+
paramIndex++;
|
|
545
|
+
}
|
|
546
|
+
if (parsedRegExp !== expressPathRegExp.toString()) {
|
|
547
|
+
expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(parsedRegExp);
|
|
548
|
+
}
|
|
549
|
+
const parsedPath = expressPathRegExpExec[1].replace(/\\\//g, "/");
|
|
550
|
+
return parsedPath;
|
|
551
|
+
}, "parseExpressPath");
|
|
552
|
+
var parseEndpoints = /* @__PURE__ */ __name(function(app, basePath, endpoints) {
|
|
553
|
+
const stack = app.stack || app._router && app._router.stack;
|
|
554
|
+
endpoints = endpoints || [];
|
|
555
|
+
basePath = basePath || "";
|
|
556
|
+
if (!stack) {
|
|
557
|
+
endpoints = addEndpoints(endpoints, [
|
|
558
|
+
{
|
|
559
|
+
path: basePath,
|
|
560
|
+
methods: [],
|
|
561
|
+
middlewares: []
|
|
562
|
+
}
|
|
563
|
+
]);
|
|
564
|
+
} else {
|
|
565
|
+
endpoints = parseStack(stack, basePath, endpoints);
|
|
566
|
+
}
|
|
567
|
+
return endpoints;
|
|
568
|
+
}, "parseEndpoints");
|
|
569
|
+
var addEndpoints = /* @__PURE__ */ __name(function(currentEndpoints, endpointsToAdd) {
|
|
570
|
+
endpointsToAdd.forEach((newEndpoint) => {
|
|
571
|
+
const existingEndpoint = currentEndpoints.find((item) => item.path === newEndpoint.path);
|
|
572
|
+
if (existingEndpoint !== void 0) {
|
|
573
|
+
const newMethods = newEndpoint.methods.filter((method) => !existingEndpoint.methods.includes(method));
|
|
574
|
+
existingEndpoint.methods = existingEndpoint.methods.concat(newMethods);
|
|
575
|
+
} else {
|
|
576
|
+
currentEndpoints.push(newEndpoint);
|
|
577
|
+
}
|
|
578
|
+
});
|
|
579
|
+
return currentEndpoints;
|
|
580
|
+
}, "addEndpoints");
|
|
581
|
+
var parseStack = /* @__PURE__ */ __name(function(stack, basePath, endpoints) {
|
|
582
|
+
stack.forEach((stackItem) => {
|
|
583
|
+
if (stackItem.route) {
|
|
584
|
+
const newEndpoints = parseExpressRoute(stackItem.route, basePath);
|
|
585
|
+
endpoints = addEndpoints(endpoints, newEndpoints);
|
|
586
|
+
} else if (STACK_ITEM_VALID_NAMES.includes(stackItem.name)) {
|
|
587
|
+
const isExpressPathRegexp = regExpToParseExpressPathRegExp.test(stackItem.regexp);
|
|
588
|
+
let newBasePath = basePath;
|
|
589
|
+
if (isExpressPathRegexp) {
|
|
590
|
+
const parsedPath = parseExpressPath(stackItem.regexp, stackItem.keys);
|
|
591
|
+
newBasePath += `/${parsedPath}`;
|
|
592
|
+
} else if (!stackItem.path && stackItem.regexp && stackItem.regexp.toString() !== EXPRESS_ROOT_PATH_REGEXP_VALUE) {
|
|
593
|
+
const regExpPath = ` RegExp(${stackItem.regexp}) `;
|
|
594
|
+
newBasePath += `/${regExpPath}`;
|
|
595
|
+
}
|
|
596
|
+
endpoints = parseEndpoints(stackItem.handle, newBasePath, endpoints);
|
|
597
|
+
}
|
|
598
|
+
});
|
|
599
|
+
return endpoints;
|
|
600
|
+
}, "parseStack");
|
|
601
|
+
var getEndpoints = /* @__PURE__ */ __name(function(app) {
|
|
602
|
+
const endpoints = parseEndpoints(app);
|
|
603
|
+
return endpoints.flatMap((route) => route.methods.filter((method) => ![
|
|
604
|
+
"HEAD",
|
|
605
|
+
"OPTIONS"
|
|
606
|
+
].includes(method.toUpperCase())).map((method) => ({
|
|
607
|
+
method,
|
|
608
|
+
path: route.path
|
|
609
|
+
})));
|
|
610
|
+
}, "getEndpoints");
|
|
611
|
+
var listEndpoints_default = getEndpoints;
|
|
612
|
+
|
|
613
|
+
// src/express/middleware.ts
|
|
614
|
+
var useApitally = /* @__PURE__ */ __name((app, config) => {
|
|
615
|
+
const client = new ApitallyClient(config);
|
|
616
|
+
const middleware = getMiddleware(app, client);
|
|
617
|
+
app.use(middleware);
|
|
618
|
+
setTimeout(() => {
|
|
619
|
+
client.setAppInfo(getAppInfo(app, config.appVersion));
|
|
620
|
+
}, 1e3);
|
|
621
|
+
}, "useApitally");
|
|
622
|
+
var getMiddleware = /* @__PURE__ */ __name((app, client) => {
|
|
623
|
+
const validatorInstalled = getPackageVersion("express-validator") !== null;
|
|
624
|
+
const celebrateInstalled = getPackageVersion("celebrate") !== null;
|
|
625
|
+
const nestInstalled = getPackageVersion("@nestjs/core") !== null;
|
|
626
|
+
const classValidatorInstalled = getPackageVersion("class-validator") !== null;
|
|
627
|
+
let errorHandlerConfigured = false;
|
|
628
|
+
return (req, res, next) => {
|
|
629
|
+
if (!errorHandlerConfigured) {
|
|
630
|
+
app.use((err, req2, res2, next2) => {
|
|
631
|
+
res2.locals.serverError = err;
|
|
632
|
+
next2(err);
|
|
633
|
+
});
|
|
634
|
+
errorHandlerConfigured = true;
|
|
635
|
+
}
|
|
636
|
+
try {
|
|
637
|
+
const startTime = performance.now();
|
|
638
|
+
const originalJson = res.json;
|
|
639
|
+
res.json = (body) => {
|
|
640
|
+
res.locals.body = body;
|
|
641
|
+
return originalJson.call(res, body);
|
|
642
|
+
};
|
|
643
|
+
res.on("finish", () => {
|
|
644
|
+
try {
|
|
645
|
+
if (req.route) {
|
|
646
|
+
const responseTime = performance.now() - startTime;
|
|
647
|
+
const consumer = getConsumer(req);
|
|
648
|
+
client.requestCounter.addRequest({
|
|
649
|
+
consumer,
|
|
650
|
+
method: req.method,
|
|
651
|
+
path: req.route.path,
|
|
652
|
+
statusCode: res.statusCode,
|
|
653
|
+
responseTime,
|
|
654
|
+
requestSize: req.get("content-length"),
|
|
655
|
+
responseSize: res.get("content-length")
|
|
656
|
+
});
|
|
657
|
+
if ((res.statusCode === 400 || res.statusCode === 422) && res.locals.body) {
|
|
658
|
+
const validationErrors = [];
|
|
659
|
+
if (validatorInstalled) {
|
|
660
|
+
validationErrors.push(...extractExpressValidatorErrors(res.locals.body));
|
|
661
|
+
}
|
|
662
|
+
if (celebrateInstalled) {
|
|
663
|
+
validationErrors.push(...extractCelebrateErrors(res.locals.body));
|
|
664
|
+
}
|
|
665
|
+
if (nestInstalled && classValidatorInstalled) {
|
|
666
|
+
validationErrors.push(...extractNestValidationErrors(res.locals.body));
|
|
667
|
+
}
|
|
668
|
+
validationErrors.forEach((error) => {
|
|
669
|
+
client.validationErrorCounter.addValidationError({
|
|
670
|
+
consumer,
|
|
671
|
+
method: req.method,
|
|
672
|
+
path: req.route.path,
|
|
673
|
+
...error
|
|
674
|
+
});
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
if (res.statusCode === 500 && res.locals.serverError) {
|
|
678
|
+
const serverError = res.locals.serverError;
|
|
679
|
+
client.serverErrorCounter.addServerError({
|
|
680
|
+
consumer,
|
|
681
|
+
method: req.method,
|
|
682
|
+
path: req.route.path,
|
|
683
|
+
type: serverError.name,
|
|
684
|
+
msg: serverError.message,
|
|
685
|
+
traceback: serverError.stack || ""
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
} catch (error) {
|
|
690
|
+
client.logger.error("Error while logging request in Apitally middleware.", {
|
|
691
|
+
request: req,
|
|
692
|
+
response: res,
|
|
693
|
+
error
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
});
|
|
697
|
+
} catch (error) {
|
|
698
|
+
client.logger.error("Error in Apitally middleware.", {
|
|
699
|
+
request: req,
|
|
700
|
+
response: res,
|
|
701
|
+
error
|
|
702
|
+
});
|
|
703
|
+
} finally {
|
|
704
|
+
next();
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
}, "getMiddleware");
|
|
708
|
+
var getConsumer = /* @__PURE__ */ __name((req) => {
|
|
709
|
+
if (req.apitallyConsumer) {
|
|
710
|
+
return String(req.apitallyConsumer);
|
|
711
|
+
} else if (req.consumerIdentifier) {
|
|
712
|
+
return String(req.consumerIdentifier);
|
|
713
|
+
}
|
|
714
|
+
return null;
|
|
715
|
+
}, "getConsumer");
|
|
716
|
+
var extractExpressValidatorErrors = /* @__PURE__ */ __name((responseBody) => {
|
|
717
|
+
const errors = [];
|
|
718
|
+
if (responseBody && responseBody.errors && Array.isArray(responseBody.errors)) {
|
|
719
|
+
responseBody.errors.forEach((error) => {
|
|
720
|
+
if (error.location && error.path && error.msg && error.type) {
|
|
721
|
+
errors.push({
|
|
722
|
+
loc: `${error.location}.${error.path}`,
|
|
723
|
+
msg: error.msg,
|
|
724
|
+
type: error.type
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
return errors;
|
|
730
|
+
}, "extractExpressValidatorErrors");
|
|
731
|
+
var extractCelebrateErrors = /* @__PURE__ */ __name((responseBody) => {
|
|
732
|
+
const errors = [];
|
|
733
|
+
if (responseBody && responseBody.validation) {
|
|
734
|
+
Object.values(responseBody.validation).forEach((error) => {
|
|
735
|
+
if (error.source && error.keys && Array.isArray(error.keys) && error.message) {
|
|
736
|
+
error.keys.forEach((key) => {
|
|
737
|
+
errors.push({
|
|
738
|
+
loc: `${error.source}.${key}`,
|
|
739
|
+
msg: subsetJoiMessage(error.message, key),
|
|
740
|
+
type: ""
|
|
741
|
+
});
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
return errors;
|
|
747
|
+
}, "extractCelebrateErrors");
|
|
748
|
+
var extractNestValidationErrors = /* @__PURE__ */ __name((responseBody) => {
|
|
749
|
+
const errors = [];
|
|
750
|
+
if (responseBody && Array.isArray(responseBody.message)) {
|
|
751
|
+
responseBody.message.forEach((message) => {
|
|
752
|
+
errors.push({
|
|
753
|
+
loc: "",
|
|
754
|
+
msg: message,
|
|
755
|
+
type: ""
|
|
756
|
+
});
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
return errors;
|
|
760
|
+
}, "extractNestValidationErrors");
|
|
761
|
+
var subsetJoiMessage = /* @__PURE__ */ __name((message, key) => {
|
|
762
|
+
const messageWithKey = message.split(". ").find((message2) => message2.includes(`"${key}"`));
|
|
763
|
+
return messageWithKey ? messageWithKey : message;
|
|
764
|
+
}, "subsetJoiMessage");
|
|
765
|
+
var getAppInfo = /* @__PURE__ */ __name((app, appVersion) => {
|
|
766
|
+
const versions = [
|
|
767
|
+
[
|
|
768
|
+
"nodejs",
|
|
769
|
+
process.version.replace(/^v/, "")
|
|
770
|
+
]
|
|
771
|
+
];
|
|
772
|
+
const expressVersion = getPackageVersion("express");
|
|
773
|
+
const apitallyVersion = getPackageVersion("../..");
|
|
774
|
+
if (expressVersion) {
|
|
775
|
+
versions.push([
|
|
776
|
+
"express",
|
|
777
|
+
expressVersion
|
|
778
|
+
]);
|
|
779
|
+
}
|
|
780
|
+
if (apitallyVersion) {
|
|
781
|
+
versions.push([
|
|
782
|
+
"apitally",
|
|
783
|
+
apitallyVersion
|
|
784
|
+
]);
|
|
785
|
+
}
|
|
786
|
+
if (appVersion) {
|
|
787
|
+
versions.push([
|
|
788
|
+
"app",
|
|
789
|
+
appVersion
|
|
790
|
+
]);
|
|
791
|
+
}
|
|
792
|
+
return {
|
|
793
|
+
paths: listEndpoints_default(app),
|
|
794
|
+
versions: Object.fromEntries(versions),
|
|
795
|
+
client: "js:express"
|
|
796
|
+
};
|
|
797
|
+
}, "getAppInfo");
|
|
798
|
+
export {
|
|
799
|
+
useApitally
|
|
800
|
+
};
|
|
801
|
+
//# sourceMappingURL=middleware.js.map
|