apitally 0.21.3 → 0.21.4

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 (179) hide show
  1. package/dist/adonisjs/configure.cjs +6 -21
  2. package/dist/adonisjs/configure.cjs.map +1 -1
  3. package/dist/adonisjs/configure.js +3 -18
  4. package/dist/adonisjs/configure.js.map +1 -1
  5. package/dist/adonisjs/index.cjs +2 -70
  6. package/dist/adonisjs/index.cjs.map +1 -1
  7. package/dist/adonisjs/index.js +1 -66
  8. package/dist/adonisjs/index.js.map +1 -1
  9. package/dist/adonisjs/middleware.cjs +11 -116
  10. package/dist/adonisjs/middleware.cjs.map +1 -1
  11. package/dist/adonisjs/middleware.js +6 -101
  12. package/dist/adonisjs/middleware.js.map +1 -1
  13. package/dist/adonisjs/provider.cjs +14 -5668
  14. package/dist/adonisjs/provider.cjs.map +1 -1
  15. package/dist/adonisjs/provider.js +6 -5676
  16. package/dist/adonisjs/provider.js.map +1 -1
  17. package/dist/common/client.cjs +26 -792
  18. package/dist/common/client.cjs.map +1 -1
  19. package/dist/common/client.js +19 -785
  20. package/dist/common/client.js.map +1 -1
  21. package/dist/common/consumerRegistry.cjs +3 -5
  22. package/dist/common/consumerRegistry.cjs.map +1 -1
  23. package/dist/common/consumerRegistry.js +3 -5
  24. package/dist/common/consumerRegistry.js.map +1 -1
  25. package/dist/common/headers.cjs +0 -2
  26. package/dist/common/headers.cjs.map +1 -1
  27. package/dist/common/headers.js +0 -2
  28. package/dist/common/headers.js.map +1 -1
  29. package/dist/common/logging.cjs +0 -2
  30. package/dist/common/logging.cjs.map +1 -1
  31. package/dist/common/logging.js +0 -2
  32. package/dist/common/logging.js.map +1 -1
  33. package/dist/common/packageVersions.cjs +2 -4
  34. package/dist/common/packageVersions.cjs.map +1 -1
  35. package/dist/common/packageVersions.js +2 -10
  36. package/dist/common/packageVersions.js.map +1 -1
  37. package/dist/common/paramValidation.cjs +0 -2
  38. package/dist/common/paramValidation.cjs.map +1 -1
  39. package/dist/common/paramValidation.js +0 -2
  40. package/dist/common/paramValidation.js.map +1 -1
  41. package/dist/common/requestCounter.cjs +2 -4
  42. package/dist/common/requestCounter.cjs.map +1 -1
  43. package/dist/common/requestCounter.js +2 -4
  44. package/dist/common/requestCounter.js.map +1 -1
  45. package/dist/common/requestLogger.cjs +39 -162
  46. package/dist/common/requestLogger.cjs.map +1 -1
  47. package/dist/common/requestLogger.js +33 -156
  48. package/dist/common/requestLogger.js.map +1 -1
  49. package/dist/common/response.cjs +0 -2
  50. package/dist/common/response.cjs.map +1 -1
  51. package/dist/common/response.js +0 -2
  52. package/dist/common/response.js.map +1 -1
  53. package/dist/common/sentry.cjs +1 -3
  54. package/dist/common/sentry.cjs.map +1 -1
  55. package/dist/common/sentry.js +1 -3
  56. package/dist/common/sentry.js.map +1 -1
  57. package/dist/common/serverErrorCounter.cjs +7 -36
  58. package/dist/common/serverErrorCounter.cjs.map +1 -1
  59. package/dist/common/serverErrorCounter.js +6 -25
  60. package/dist/common/serverErrorCounter.js.map +1 -1
  61. package/dist/common/tempGzipFile.cjs +9 -11
  62. package/dist/common/tempGzipFile.cjs.map +1 -1
  63. package/dist/common/tempGzipFile.js +9 -11
  64. package/dist/common/tempGzipFile.js.map +1 -1
  65. package/dist/common/types.cjs +0 -2
  66. package/dist/common/types.cjs.map +1 -1
  67. package/dist/common/validationErrorCounter.cjs +3 -5
  68. package/dist/common/validationErrorCounter.cjs.map +1 -1
  69. package/dist/common/validationErrorCounter.js +3 -5
  70. package/dist/common/validationErrorCounter.js.map +1 -1
  71. package/dist/elysia/index.cjs +2 -1573
  72. package/dist/elysia/index.cjs.map +1 -1
  73. package/dist/elysia/index.js +2 -1577
  74. package/dist/elysia/index.js.map +1 -1
  75. package/dist/elysia/plugin.cjs +26 -1432
  76. package/dist/elysia/plugin.cjs.map +1 -1
  77. package/dist/elysia/plugin.js +15 -1416
  78. package/dist/elysia/plugin.js.map +1 -1
  79. package/dist/elysia/utils.cjs +3 -24
  80. package/dist/elysia/utils.cjs.map +1 -1
  81. package/dist/elysia/utils.js +1 -25
  82. package/dist/elysia/utils.js.map +1 -1
  83. package/dist/express/index.cjs +3 -6354
  84. package/dist/express/index.cjs.map +1 -1
  85. package/dist/express/index.js +1 -6367
  86. package/dist/express/index.js.map +1 -1
  87. package/dist/express/middleware.cjs +38 -6070
  88. package/dist/express/middleware.cjs.map +1 -1
  89. package/dist/express/middleware.js +13 -6061
  90. package/dist/express/middleware.js.map +1 -1
  91. package/dist/express/utils.cjs +17 -19
  92. package/dist/express/utils.cjs.map +1 -1
  93. package/dist/express/utils.js +17 -19
  94. package/dist/express/utils.js.map +1 -1
  95. package/dist/fastify/index.cjs +3 -6124
  96. package/dist/fastify/index.cjs.map +1 -1
  97. package/dist/fastify/index.js +2 -6148
  98. package/dist/fastify/index.js.map +1 -1
  99. package/dist/fastify/plugin.cjs +35 -5889
  100. package/dist/fastify/plugin.cjs.map +1 -1
  101. package/dist/fastify/plugin.js +13 -5893
  102. package/dist/fastify/plugin.js.map +1 -1
  103. package/dist/h3/index.cjs +3 -1545
  104. package/dist/h3/index.cjs.map +1 -1
  105. package/dist/h3/index.js +1 -1537
  106. package/dist/h3/index.js.map +1 -1
  107. package/dist/h3/plugin.cjs +27 -1423
  108. package/dist/h3/plugin.cjs.map +1 -1
  109. package/dist/h3/plugin.js +15 -1406
  110. package/dist/h3/plugin.js.map +1 -1
  111. package/dist/h3/utils.cjs +3 -24
  112. package/dist/h3/utils.cjs.map +1 -1
  113. package/dist/h3/utils.js +1 -25
  114. package/dist/h3/utils.js.map +1 -1
  115. package/dist/hapi/index.cjs +3 -5988
  116. package/dist/hapi/index.cjs.map +1 -1
  117. package/dist/hapi/index.js +2 -6012
  118. package/dist/hapi/index.js.map +1 -1
  119. package/dist/hapi/plugin.cjs +27 -5847
  120. package/dist/hapi/plugin.cjs.map +1 -1
  121. package/dist/hapi/plugin.js +15 -5851
  122. package/dist/hapi/plugin.js.map +1 -1
  123. package/dist/hapi/utils.cjs +3 -24
  124. package/dist/hapi/utils.cjs.map +1 -1
  125. package/dist/hapi/utils.js +1 -25
  126. package/dist/hapi/utils.js.map +1 -1
  127. package/dist/hono/index.cjs +3 -1571
  128. package/dist/hono/index.cjs.map +1 -1
  129. package/dist/hono/index.js +1 -1563
  130. package/dist/hono/index.js.map +1 -1
  131. package/dist/hono/middleware.cjs +21 -1460
  132. package/dist/hono/middleware.cjs.map +1 -1
  133. package/dist/hono/middleware.js +9 -1443
  134. package/dist/hono/middleware.js.map +1 -1
  135. package/dist/hono/utils.cjs +3 -24
  136. package/dist/hono/utils.cjs.map +1 -1
  137. package/dist/hono/utils.js +1 -27
  138. package/dist/hono/utils.js.map +1 -1
  139. package/dist/koa/index.cjs +3 -1484
  140. package/dist/koa/index.cjs.map +1 -1
  141. package/dist/koa/index.js +1 -1476
  142. package/dist/koa/index.js.map +1 -1
  143. package/dist/koa/middleware.cjs +19 -1313
  144. package/dist/koa/middleware.cjs.map +1 -1
  145. package/dist/koa/middleware.js +8 -1297
  146. package/dist/koa/middleware.js.map +1 -1
  147. package/dist/loggers/console.cjs +4 -6
  148. package/dist/loggers/console.cjs.map +1 -1
  149. package/dist/loggers/console.js +4 -6
  150. package/dist/loggers/console.js.map +1 -1
  151. package/dist/loggers/hapi.cjs +3 -5
  152. package/dist/loggers/hapi.cjs.map +1 -1
  153. package/dist/loggers/hapi.js +3 -5
  154. package/dist/loggers/hapi.js.map +1 -1
  155. package/dist/loggers/index.cjs +10 -4732
  156. package/dist/loggers/index.cjs.map +1 -1
  157. package/dist/loggers/index.js +5 -4743
  158. package/dist/loggers/index.js.map +1 -1
  159. package/dist/loggers/nestjs.cjs +5 -39
  160. package/dist/loggers/nestjs.cjs.map +1 -1
  161. package/dist/loggers/nestjs.js +4 -36
  162. package/dist/loggers/nestjs.js.map +1 -1
  163. package/dist/loggers/pino.cjs +29 -4448
  164. package/dist/loggers/pino.cjs.map +1 -1
  165. package/dist/loggers/pino.js +7 -4451
  166. package/dist/loggers/pino.js.map +1 -1
  167. package/dist/loggers/utils.cjs +1 -3
  168. package/dist/loggers/utils.cjs.map +1 -1
  169. package/dist/loggers/utils.js +1 -3
  170. package/dist/loggers/utils.js.map +1 -1
  171. package/dist/loggers/winston.cjs +6 -44
  172. package/dist/loggers/winston.cjs.map +1 -1
  173. package/dist/loggers/winston.js +4 -40
  174. package/dist/loggers/winston.js.map +1 -1
  175. package/dist/nestjs/index.cjs +17 -17786
  176. package/dist/nestjs/index.cjs.map +1 -1
  177. package/dist/nestjs/index.js +20 -17814
  178. package/dist/nestjs/index.js.map +1 -1
  179. package/package.json +1 -1
@@ -5,8 +5,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
8
  var __export = (target, all) => {
11
9
  for (var name in all)
12
10
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -28,1581 +26,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
26
  mod
29
27
  ));
30
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
32
-
33
- // src/elysia/index.ts
34
29
  var elysia_exports = {};
35
30
  __export(elysia_exports, {
36
- apitallyPlugin: () => apitallyPlugin
31
+ apitallyPlugin: () => import_plugin.default
37
32
  });
38
33
  module.exports = __toCommonJS(elysia_exports);
39
-
40
- // src/elysia/plugin.ts
41
- var import_elysia = require("elysia");
42
- var import_node_async_hooks = require("async_hooks");
43
- var import_node_perf_hooks = require("perf_hooks");
44
-
45
- // src/common/client.ts
46
- var import_fetch_retry = __toESM(require("fetch-retry"), 1);
47
- var import_node_crypto5 = require("crypto");
48
-
49
- // src/common/consumerRegistry.ts
50
- var consumerFromStringOrObject = /* @__PURE__ */ __name((consumer) => {
51
- var _a2, _b;
52
- if (typeof consumer === "string") {
53
- consumer = String(consumer).trim().substring(0, 128);
54
- return consumer ? {
55
- identifier: consumer
56
- } : null;
57
- } else {
58
- consumer.identifier = String(consumer.identifier).trim().substring(0, 128);
59
- consumer.name = (_a2 = consumer.name) == null ? void 0 : _a2.trim().substring(0, 64);
60
- consumer.group = (_b = consumer.group) == null ? void 0 : _b.trim().substring(0, 64);
61
- return consumer.identifier ? consumer : null;
62
- }
63
- }, "consumerFromStringOrObject");
64
- var _ConsumerRegistry = class _ConsumerRegistry {
65
- consumers;
66
- updated;
67
- constructor() {
68
- this.consumers = /* @__PURE__ */ new Map();
69
- this.updated = /* @__PURE__ */ new Set();
70
- }
71
- addOrUpdateConsumer(consumer) {
72
- if (!consumer || !consumer.name && !consumer.group) {
73
- return;
74
- }
75
- const existing = this.consumers.get(consumer.identifier);
76
- if (!existing) {
77
- this.consumers.set(consumer.identifier, consumer);
78
- this.updated.add(consumer.identifier);
79
- } else {
80
- if (consumer.name && consumer.name !== existing.name) {
81
- existing.name = consumer.name;
82
- this.updated.add(consumer.identifier);
83
- }
84
- if (consumer.group && consumer.group !== existing.group) {
85
- existing.group = consumer.group;
86
- this.updated.add(consumer.identifier);
87
- }
88
- }
89
- }
90
- getAndResetUpdatedConsumers() {
91
- const data = [];
92
- this.updated.forEach((identifier) => {
93
- const consumer = this.consumers.get(identifier);
94
- if (consumer) {
95
- data.push(consumer);
96
- }
97
- });
98
- this.updated.clear();
99
- return data;
100
- }
101
- };
102
- __name(_ConsumerRegistry, "ConsumerRegistry");
103
- var ConsumerRegistry = _ConsumerRegistry;
104
-
105
- // src/common/logging.ts
106
- var import_winston = require("winston");
107
- function getLogger() {
108
- return (0, import_winston.createLogger)({
109
- level: process.env.APITALLY_DEBUG ? "debug" : "warn",
110
- format: import_winston.format.combine(import_winston.format.colorize(), import_winston.format.timestamp(), import_winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`)),
111
- transports: [
112
- new import_winston.transports.Console()
113
- ]
114
- });
115
- }
116
- __name(getLogger, "getLogger");
117
-
118
- // src/common/paramValidation.ts
119
- function isValidClientId(clientId) {
120
- 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;
121
- return regexExp.test(clientId);
122
- }
123
- __name(isValidClientId, "isValidClientId");
124
- function isValidEnv(env) {
125
- const regexExp = /^[\w-]{1,32}$/;
126
- return regexExp.test(env);
127
- }
128
- __name(isValidEnv, "isValidEnv");
129
-
130
- // src/common/requestCounter.ts
131
- var _RequestCounter = class _RequestCounter {
132
- requestCounts;
133
- requestSizeSums;
134
- responseSizeSums;
135
- responseTimes;
136
- requestSizes;
137
- responseSizes;
138
- constructor() {
139
- this.requestCounts = /* @__PURE__ */ new Map();
140
- this.requestSizeSums = /* @__PURE__ */ new Map();
141
- this.responseSizeSums = /* @__PURE__ */ new Map();
142
- this.responseTimes = /* @__PURE__ */ new Map();
143
- this.requestSizes = /* @__PURE__ */ new Map();
144
- this.responseSizes = /* @__PURE__ */ new Map();
145
- }
146
- getKey(requestInfo) {
147
- return [
148
- requestInfo.consumer || "",
149
- requestInfo.method.toUpperCase(),
150
- requestInfo.path,
151
- requestInfo.statusCode
152
- ].join("|");
153
- }
154
- addRequest(requestInfo) {
155
- const key = this.getKey(requestInfo);
156
- this.requestCounts.set(key, (this.requestCounts.get(key) || 0) + 1);
157
- if (!this.responseTimes.has(key)) {
158
- this.responseTimes.set(key, /* @__PURE__ */ new Map());
159
- }
160
- const responseTimeMap = this.responseTimes.get(key);
161
- const responseTimeMsBin = Math.floor(requestInfo.responseTime / 10) * 10;
162
- responseTimeMap.set(responseTimeMsBin, (responseTimeMap.get(responseTimeMsBin) || 0) + 1);
163
- if (requestInfo.requestSize !== void 0) {
164
- requestInfo.requestSize = Number(requestInfo.requestSize);
165
- this.requestSizeSums.set(key, (this.requestSizeSums.get(key) || 0) + requestInfo.requestSize);
166
- if (!this.requestSizes.has(key)) {
167
- this.requestSizes.set(key, /* @__PURE__ */ new Map());
168
- }
169
- const requestSizeMap = this.requestSizes.get(key);
170
- const requestSizeKbBin = Math.floor(requestInfo.requestSize / 1e3);
171
- requestSizeMap.set(requestSizeKbBin, (requestSizeMap.get(requestSizeKbBin) || 0) + 1);
172
- }
173
- if (requestInfo.responseSize !== void 0) {
174
- requestInfo.responseSize = Number(requestInfo.responseSize);
175
- this.responseSizeSums.set(key, (this.responseSizeSums.get(key) || 0) + requestInfo.responseSize);
176
- if (!this.responseSizes.has(key)) {
177
- this.responseSizes.set(key, /* @__PURE__ */ new Map());
178
- }
179
- const responseSizeMap = this.responseSizes.get(key);
180
- const responseSizeKbBin = Math.floor(requestInfo.responseSize / 1e3);
181
- responseSizeMap.set(responseSizeKbBin, (responseSizeMap.get(responseSizeKbBin) || 0) + 1);
182
- }
183
- }
184
- getAndResetRequests() {
185
- const data = [];
186
- this.requestCounts.forEach((count, key) => {
187
- const [consumer, method, path, statusCodeStr] = key.split("|");
188
- const responseTimes = this.responseTimes.get(key) || /* @__PURE__ */ new Map();
189
- const requestSizes = this.requestSizes.get(key) || /* @__PURE__ */ new Map();
190
- const responseSizes = this.responseSizes.get(key) || /* @__PURE__ */ new Map();
191
- data.push({
192
- consumer: consumer || null,
193
- method,
194
- path,
195
- status_code: parseInt(statusCodeStr),
196
- request_count: count,
197
- request_size_sum: this.requestSizeSums.get(key) || 0,
198
- response_size_sum: this.responseSizeSums.get(key) || 0,
199
- response_times: Object.fromEntries(responseTimes),
200
- request_sizes: Object.fromEntries(requestSizes),
201
- response_sizes: Object.fromEntries(responseSizes)
202
- });
203
- });
204
- this.requestCounts.clear();
205
- this.requestSizeSums.clear();
206
- this.responseSizeSums.clear();
207
- this.responseTimes.clear();
208
- this.requestSizes.clear();
209
- this.responseSizes.clear();
210
- return data;
211
- }
212
- };
213
- __name(_RequestCounter, "RequestCounter");
214
- var RequestCounter = _RequestCounter;
215
-
216
- // src/common/requestLogger.ts
217
- var import_async_lock = __toESM(require("async-lock"), 1);
218
- var import_node_buffer2 = require("buffer");
219
- var import_node_crypto3 = require("crypto");
220
- var import_node_fs2 = require("fs");
221
- var import_node_os2 = require("os");
222
- var import_node_path2 = require("path");
223
-
224
- // src/common/sentry.ts
225
- var sentry;
226
- (async () => {
227
- try {
228
- sentry = await import("@sentry/node");
229
- } catch (e) {
230
- }
231
- })();
232
- function getSentryEventId() {
233
- if (sentry && sentry.lastEventId) {
234
- return sentry.lastEventId();
235
- }
236
- return void 0;
237
- }
238
- __name(getSentryEventId, "getSentryEventId");
239
-
240
- // src/common/serverErrorCounter.ts
241
- var import_node_crypto = require("crypto");
242
- var MAX_MSG_LENGTH = 2048;
243
- var MAX_STACKTRACE_LENGTH = 65536;
244
- var _ServerErrorCounter = class _ServerErrorCounter {
245
- errorCounts;
246
- errorDetails;
247
- sentryEventIds;
248
- constructor() {
249
- this.errorCounts = /* @__PURE__ */ new Map();
250
- this.errorDetails = /* @__PURE__ */ new Map();
251
- this.sentryEventIds = /* @__PURE__ */ new Map();
252
- }
253
- addServerError(serverError) {
254
- const key = this.getKey(serverError);
255
- if (!this.errorDetails.has(key)) {
256
- this.errorDetails.set(key, serverError);
257
- }
258
- this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
259
- const sentryEventId = getSentryEventId();
260
- if (sentryEventId) {
261
- this.sentryEventIds.set(key, sentryEventId);
262
- }
263
- }
264
- getAndResetServerErrors() {
265
- const data = [];
266
- this.errorCounts.forEach((count, key) => {
267
- const serverError = this.errorDetails.get(key);
268
- if (serverError) {
269
- data.push({
270
- consumer: serverError.consumer || null,
271
- method: serverError.method,
272
- path: serverError.path,
273
- type: serverError.type,
274
- msg: truncateExceptionMessage(serverError.msg),
275
- traceback: truncateExceptionStackTrace(serverError.traceback),
276
- sentry_event_id: this.sentryEventIds.get(key) || null,
277
- error_count: count
278
- });
279
- }
280
- });
281
- this.errorCounts.clear();
282
- this.errorDetails.clear();
283
- this.sentryEventIds.clear();
284
- return data;
285
- }
286
- getKey(serverError) {
287
- const hashInput = [
288
- serverError.consumer || "",
289
- serverError.method.toUpperCase(),
290
- serverError.path,
291
- serverError.type,
292
- serverError.msg.trim(),
293
- serverError.traceback.trim()
294
- ].join("|");
295
- return (0, import_node_crypto.createHash)("md5").update(hashInput).digest("hex");
296
- }
297
- };
298
- __name(_ServerErrorCounter, "ServerErrorCounter");
299
- var ServerErrorCounter = _ServerErrorCounter;
300
- function truncateExceptionMessage(msg) {
301
- if (msg.length <= MAX_MSG_LENGTH) {
302
- return msg;
303
- }
304
- const suffix = "... (truncated)";
305
- const cutoff = MAX_MSG_LENGTH - suffix.length;
306
- return msg.substring(0, cutoff) + suffix;
307
- }
308
- __name(truncateExceptionMessage, "truncateExceptionMessage");
309
- function truncateExceptionStackTrace(stack) {
310
- const suffix = "... (truncated) ...";
311
- const cutoff = MAX_STACKTRACE_LENGTH - suffix.length;
312
- const lines = stack.trim().split("\n");
313
- const truncatedLines = [];
314
- let length = 0;
315
- for (const line of lines) {
316
- if (length + line.length + 1 > cutoff) {
317
- truncatedLines.push(suffix);
318
- break;
319
- }
320
- truncatedLines.push(line);
321
- length += line.length + 1;
322
- }
323
- return truncatedLines.join("\n");
324
- }
325
- __name(truncateExceptionStackTrace, "truncateExceptionStackTrace");
326
-
327
- // src/common/tempGzipFile.ts
328
- var import_node_buffer = require("buffer");
329
- var import_node_crypto2 = require("crypto");
330
- var import_node_fs = require("fs");
331
- var import_promises = require("fs/promises");
332
- var import_node_os = require("os");
333
- var import_node_path = require("path");
334
- var import_node_zlib = require("zlib");
335
- var _TempGzipFile = class _TempGzipFile {
336
- uuid;
337
- filePath;
338
- gzip;
339
- writeStream;
340
- readyPromise;
341
- closedPromise;
342
- constructor() {
343
- this.uuid = (0, import_node_crypto2.randomUUID)();
344
- this.filePath = (0, import_node_path.join)((0, import_node_os.tmpdir)(), `apitally-${this.uuid}.gz`);
345
- this.writeStream = (0, import_node_fs.createWriteStream)(this.filePath);
346
- this.readyPromise = new Promise((resolve, reject) => {
347
- this.writeStream.once("ready", resolve);
348
- this.writeStream.once("error", reject);
349
- });
350
- this.closedPromise = new Promise((resolve, reject) => {
351
- this.writeStream.once("close", resolve);
352
- this.writeStream.once("error", reject);
353
- });
354
- this.gzip = (0, import_node_zlib.createGzip)();
355
- this.gzip.pipe(this.writeStream);
356
- }
357
- get size() {
358
- return this.writeStream.bytesWritten;
359
- }
360
- async writeLine(data) {
361
- await this.readyPromise;
362
- return new Promise((resolve, reject) => {
363
- this.gzip.write(import_node_buffer.Buffer.concat([
364
- data,
365
- import_node_buffer.Buffer.from("\n")
366
- ]), (error) => {
367
- if (error) {
368
- reject(error);
369
- } else {
370
- resolve();
371
- }
372
- });
373
- });
374
- }
375
- async getContent() {
376
- return new Promise((resolve, reject) => {
377
- (0, import_node_fs.readFile)(this.filePath, (error, data) => {
378
- if (error) {
379
- reject(error);
380
- } else {
381
- resolve(data);
382
- }
383
- });
384
- });
385
- }
386
- async close() {
387
- await new Promise((resolve) => {
388
- this.gzip.end(() => {
389
- resolve();
390
- });
391
- });
392
- await this.closedPromise;
393
- }
394
- async delete() {
395
- await this.close();
396
- await (0, import_promises.unlink)(this.filePath);
397
- }
398
- };
399
- __name(_TempGzipFile, "TempGzipFile");
400
- var TempGzipFile = _TempGzipFile;
401
-
402
- // src/common/requestLogger.ts
403
- var MAX_BODY_SIZE = 5e4;
404
- var MAX_FILE_SIZE = 1e6;
405
- var MAX_FILES = 50;
406
- var MAX_PENDING_WRITES = 100;
407
- var MAX_LOG_MSG_LENGTH = 2048;
408
- var BODY_TOO_LARGE = import_node_buffer2.Buffer.from("<body too large>");
409
- var BODY_MASKED = import_node_buffer2.Buffer.from("<masked>");
410
- var MASKED = "******";
411
- var ALLOWED_CONTENT_TYPES = [
412
- "application/json",
413
- "application/problem+json",
414
- "application/vnd.api+json",
415
- "text/plain",
416
- "text/html"
417
- ];
418
- var EXCLUDE_PATH_PATTERNS = [
419
- /\/_?healthz?$/i,
420
- /\/_?health[_-]?checks?$/i,
421
- /\/_?heart[_-]?beats?$/i,
422
- /\/ping$/i,
423
- /\/ready$/i,
424
- /\/live$/i
425
- ];
426
- var EXCLUDE_USER_AGENT_PATTERNS = [
427
- /health[-_ ]?check/i,
428
- /microsoft-azure-application-lb/i,
429
- /googlehc/i,
430
- /kube-probe/i
431
- ];
432
- var MASK_QUERY_PARAM_PATTERNS = [
433
- /auth/i,
434
- /api-?key/i,
435
- /secret/i,
436
- /token/i,
437
- /password/i,
438
- /pwd/i
439
- ];
440
- var MASK_HEADER_PATTERNS = [
441
- /auth/i,
442
- /api-?key/i,
443
- /secret/i,
444
- /token/i,
445
- /cookie/i
446
- ];
447
- var MASK_BODY_FIELD_PATTERNS = [
448
- /password/i,
449
- /pwd/i,
450
- /token/i,
451
- /secret/i,
452
- /auth/i,
453
- /card[-_ ]?number/i,
454
- /ccv/i,
455
- /ssn/i
456
- ];
457
- var DEFAULT_CONFIG = {
458
- enabled: false,
459
- logQueryParams: true,
460
- logRequestHeaders: false,
461
- logRequestBody: false,
462
- logResponseHeaders: true,
463
- logResponseBody: false,
464
- logException: true,
465
- captureLogs: false,
466
- maskQueryParams: [],
467
- maskHeaders: [],
468
- maskBodyFields: [],
469
- excludePaths: []
470
- };
471
- var _RequestLogger = class _RequestLogger {
472
- config;
473
- enabled;
474
- suspendUntil = null;
475
- pendingWrites = [];
476
- currentFile = null;
477
- files = [];
478
- maintainIntervalId;
479
- lock = new import_async_lock.default();
480
- constructor(config) {
481
- this.config = {
482
- ...DEFAULT_CONFIG,
483
- ...config
484
- };
485
- this.enabled = this.config.enabled && checkWritableFs();
486
- if (this.enabled) {
487
- this.maintainIntervalId = setInterval(() => {
488
- this.maintain();
489
- }, 1e3);
490
- }
491
- }
492
- get maxBodySize() {
493
- return MAX_BODY_SIZE;
494
- }
495
- shouldExcludePath(urlPath) {
496
- const patterns = [
497
- ...this.config.excludePaths,
498
- ...EXCLUDE_PATH_PATTERNS
499
- ];
500
- return matchPatterns(urlPath, patterns);
501
- }
502
- shouldExcludeUserAgent(userAgent) {
503
- return userAgent ? matchPatterns(userAgent, EXCLUDE_USER_AGENT_PATTERNS) : false;
504
- }
505
- shouldMaskQueryParam(name) {
506
- const patterns = [
507
- ...this.config.maskQueryParams,
508
- ...MASK_QUERY_PARAM_PATTERNS
509
- ];
510
- return matchPatterns(name, patterns);
511
- }
512
- shouldMaskHeader(name) {
513
- const patterns = [
514
- ...this.config.maskHeaders,
515
- ...MASK_HEADER_PATTERNS
516
- ];
517
- return matchPatterns(name, patterns);
518
- }
519
- shouldMaskBodyField(name) {
520
- const patterns = [
521
- ...this.config.maskBodyFields,
522
- ...MASK_BODY_FIELD_PATTERNS
523
- ];
524
- return matchPatterns(name, patterns);
525
- }
526
- hasSupportedContentType(headers) {
527
- var _a2;
528
- const contentType = (_a2 = headers.find(([k]) => k.toLowerCase() === "content-type")) == null ? void 0 : _a2[1];
529
- return this.isSupportedContentType(contentType);
530
- }
531
- hasJsonContentType(headers) {
532
- var _a2;
533
- const contentType = (_a2 = headers.find(([k]) => k.toLowerCase() === "content-type")) == null ? void 0 : _a2[1];
534
- return contentType ? /\bjson\b/i.test(contentType) : null;
535
- }
536
- isSupportedContentType(contentType) {
537
- return typeof contentType === "string" && ALLOWED_CONTENT_TYPES.some((t) => contentType.startsWith(t));
538
- }
539
- maskQueryParams(search) {
540
- const params = new URLSearchParams(search);
541
- for (const [key] of params) {
542
- if (this.shouldMaskQueryParam(key)) {
543
- params.set(key, MASKED);
544
- }
545
- }
546
- return params.toString();
547
- }
548
- maskHeaders(headers) {
549
- return headers.map(([k, v]) => [
550
- k,
551
- this.shouldMaskHeader(k) ? MASKED : v
552
- ]);
553
- }
554
- maskBody(data) {
555
- if (typeof data === "object" && data !== null && !Array.isArray(data)) {
556
- const result = {};
557
- for (const [key, value] of Object.entries(data)) {
558
- if (typeof value === "string" && this.shouldMaskBodyField(key)) {
559
- result[key] = MASKED;
560
- } else {
561
- result[key] = this.maskBody(value);
562
- }
563
- }
564
- return result;
565
- }
566
- if (Array.isArray(data)) {
567
- return data.map((item) => this.maskBody(item));
568
- }
569
- return data;
570
- }
571
- applyMasking(item) {
572
- if (this.config.maskRequestBodyCallback && item.request.body && item.request.body !== BODY_TOO_LARGE) {
573
- try {
574
- const maskedBody = this.config.maskRequestBodyCallback(item.request);
575
- item.request.body = maskedBody ?? BODY_MASKED;
576
- } catch {
577
- item.request.body = void 0;
578
- }
579
- }
580
- if (this.config.maskResponseBodyCallback && item.response.body && item.response.body !== BODY_TOO_LARGE) {
581
- try {
582
- const maskedBody = this.config.maskResponseBodyCallback(item.request, item.response);
583
- item.response.body = maskedBody ?? BODY_MASKED;
584
- } catch {
585
- item.response.body = void 0;
586
- }
587
- }
588
- if (item.request.body && item.request.body.length > MAX_BODY_SIZE) {
589
- item.request.body = BODY_TOO_LARGE;
590
- }
591
- if (item.response.body && item.response.body.length > MAX_BODY_SIZE) {
592
- item.response.body = BODY_TOO_LARGE;
593
- }
594
- for (const key of [
595
- "request",
596
- "response"
597
- ]) {
598
- const bodyData = item[key].body;
599
- if (!bodyData || bodyData === BODY_TOO_LARGE || bodyData === BODY_MASKED) {
600
- continue;
601
- }
602
- const headers = item[key].headers;
603
- const hasJsonContent = this.hasJsonContentType(headers);
604
- if (hasJsonContent === null || hasJsonContent) {
605
- try {
606
- const parsedBody = JSON.parse(bodyData.toString());
607
- const maskedBody = this.maskBody(parsedBody);
608
- item[key].body = import_node_buffer2.Buffer.from(JSON.stringify(maskedBody));
609
- } catch {
610
- }
611
- }
612
- }
613
- item.request.headers = this.config.logRequestHeaders ? this.maskHeaders(item.request.headers) : [];
614
- item.response.headers = this.config.logResponseHeaders ? this.maskHeaders(item.response.headers) : [];
615
- const url = new URL(item.request.url);
616
- url.search = this.config.logQueryParams ? this.maskQueryParams(url.search) : "";
617
- item.request.url = url.toString();
618
- return item;
619
- }
620
- logRequest(request, response, error, logs) {
621
- var _a2, _b, _c;
622
- if (!this.enabled || this.suspendUntil !== null) return;
623
- const url = new URL(request.url);
624
- const path = request.path ?? url.pathname;
625
- const userAgent = (_a2 = request.headers.find(([k]) => k.toLowerCase() === "user-agent")) == null ? void 0 : _a2[1];
626
- if (this.shouldExcludePath(path) || this.shouldExcludeUserAgent(userAgent) || (((_c = (_b = this.config).excludeCallback) == null ? void 0 : _c.call(_b, request, response)) ?? false)) {
627
- return;
628
- }
629
- if (!this.config.logRequestBody || !this.hasSupportedContentType(request.headers)) {
630
- request.body = void 0;
631
- }
632
- if (!this.config.logResponseBody || !this.hasSupportedContentType(response.headers)) {
633
- response.body = void 0;
634
- }
635
- if (request.size !== void 0 && request.size < 0) {
636
- request.size = void 0;
637
- }
638
- if (response.size !== void 0 && response.size < 0) {
639
- response.size = void 0;
640
- }
641
- const item = {
642
- uuid: (0, import_node_crypto3.randomUUID)(),
643
- request,
644
- response,
645
- exception: error && this.config.logException ? {
646
- type: error.name,
647
- message: truncateExceptionMessage(error.message),
648
- stacktrace: truncateExceptionStackTrace(error.stack || ""),
649
- sentryEventId: getSentryEventId()
650
- } : void 0
651
- };
652
- if (logs && logs.length > 0) {
653
- item.logs = logs.map((log) => ({
654
- timestamp: log.timestamp,
655
- logger: log.logger,
656
- level: log.level,
657
- message: truncateLogMessage(log.message)
658
- }));
659
- }
660
- this.pendingWrites.push(item);
661
- if (this.pendingWrites.length > MAX_PENDING_WRITES) {
662
- this.pendingWrites.shift();
663
- }
664
- }
665
- async writeToFile() {
666
- if (!this.enabled || this.pendingWrites.length === 0) {
667
- return;
668
- }
669
- return this.lock.acquire("file", async () => {
670
- if (!this.currentFile) {
671
- this.currentFile = new TempGzipFile();
672
- }
673
- while (this.pendingWrites.length > 0) {
674
- let item = this.pendingWrites.shift();
675
- if (item) {
676
- item = this.applyMasking(item);
677
- const finalItem = {
678
- uuid: item.uuid,
679
- request: skipEmptyValues(item.request),
680
- response: skipEmptyValues(item.response),
681
- exception: item.exception,
682
- logs: item.logs
683
- };
684
- [
685
- finalItem.request.body,
686
- finalItem.response.body
687
- ].forEach((body) => {
688
- if (body) {
689
- body.toJSON = function() {
690
- return this.toString("base64");
691
- };
692
- }
693
- });
694
- await this.currentFile.writeLine(import_node_buffer2.Buffer.from(JSON.stringify(finalItem)));
695
- }
696
- }
697
- });
698
- }
699
- getFile() {
700
- return this.files.shift();
701
- }
702
- retryFileLater(file) {
703
- this.files.unshift(file);
704
- }
705
- async rotateFile() {
706
- return this.lock.acquire("file", async () => {
707
- if (this.currentFile) {
708
- await this.currentFile.close();
709
- this.files.push(this.currentFile);
710
- this.currentFile = null;
711
- }
712
- });
713
- }
714
- async maintain() {
715
- await this.writeToFile();
716
- if (this.currentFile && this.currentFile.size > MAX_FILE_SIZE) {
717
- await this.rotateFile();
718
- }
719
- while (this.files.length > MAX_FILES) {
720
- const file = this.files.shift();
721
- file == null ? void 0 : file.delete();
722
- }
723
- if (this.suspendUntil !== null && this.suspendUntil < Date.now()) {
724
- this.suspendUntil = null;
725
- }
726
- }
727
- async clear() {
728
- this.pendingWrites = [];
729
- await this.rotateFile();
730
- this.files.forEach((file) => {
731
- file.delete();
732
- });
733
- this.files = [];
734
- }
735
- async close() {
736
- this.enabled = false;
737
- await this.clear();
738
- if (this.maintainIntervalId) {
739
- clearInterval(this.maintainIntervalId);
740
- }
741
- }
742
- };
743
- __name(_RequestLogger, "RequestLogger");
744
- var RequestLogger = _RequestLogger;
745
- function convertHeaders(headers) {
746
- if (!headers) {
747
- return [];
748
- }
749
- if (headers instanceof Headers) {
750
- return Array.from(headers.entries());
751
- }
752
- return Object.entries(headers).flatMap(([key, value]) => {
753
- if (value === void 0) {
754
- return [];
755
- }
756
- if (Array.isArray(value)) {
757
- return value.map((v) => [
758
- key,
759
- v
760
- ]);
761
- }
762
- return [
763
- [
764
- key,
765
- value.toString()
766
- ]
767
- ];
768
- });
769
- }
770
- __name(convertHeaders, "convertHeaders");
771
- function matchPatterns(value, patterns) {
772
- return patterns.some((pattern) => {
773
- return pattern.test(value);
774
- });
775
- }
776
- __name(matchPatterns, "matchPatterns");
777
- function skipEmptyValues(data) {
778
- return Object.fromEntries(Object.entries(data).filter(([_, v]) => {
779
- if (v == null || Number.isNaN(v)) return false;
780
- if (Array.isArray(v) || import_node_buffer2.Buffer.isBuffer(v) || typeof v === "string") {
781
- return v.length > 0;
782
- }
783
- return true;
784
- }));
785
- }
786
- __name(skipEmptyValues, "skipEmptyValues");
787
- function truncateLogMessage(msg) {
788
- if (msg.length > MAX_LOG_MSG_LENGTH) {
789
- const suffix = "... (truncated)";
790
- return msg.slice(0, MAX_LOG_MSG_LENGTH - suffix.length) + suffix;
791
- }
792
- return msg;
793
- }
794
- __name(truncateLogMessage, "truncateLogMessage");
795
- function checkWritableFs() {
796
- try {
797
- const testPath = (0, import_node_path2.join)((0, import_node_os2.tmpdir)(), `apitally-${(0, import_node_crypto3.randomUUID)()}`);
798
- (0, import_node_fs2.writeFileSync)(testPath, "test");
799
- (0, import_node_fs2.unlinkSync)(testPath);
800
- return true;
801
- } catch (error) {
802
- return false;
803
- }
804
- }
805
- __name(checkWritableFs, "checkWritableFs");
806
-
807
- // src/common/validationErrorCounter.ts
808
- var import_node_crypto4 = require("crypto");
809
- var _ValidationErrorCounter = class _ValidationErrorCounter {
810
- errorCounts;
811
- errorDetails;
812
- constructor() {
813
- this.errorCounts = /* @__PURE__ */ new Map();
814
- this.errorDetails = /* @__PURE__ */ new Map();
815
- }
816
- addValidationError(validationError) {
817
- const key = this.getKey(validationError);
818
- if (!this.errorDetails.has(key)) {
819
- this.errorDetails.set(key, validationError);
820
- }
821
- this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
822
- }
823
- getAndResetValidationErrors() {
824
- const data = [];
825
- this.errorCounts.forEach((count, key) => {
826
- const validationError = this.errorDetails.get(key);
827
- if (validationError) {
828
- data.push({
829
- consumer: validationError.consumer || null,
830
- method: validationError.method,
831
- path: validationError.path,
832
- loc: validationError.loc.split(".").filter(Boolean),
833
- msg: validationError.msg,
834
- type: validationError.type,
835
- error_count: count
836
- });
837
- }
838
- });
839
- this.errorCounts.clear();
840
- this.errorDetails.clear();
841
- return data;
842
- }
843
- getKey(validationError) {
844
- const hashInput = [
845
- validationError.consumer || "",
846
- validationError.method.toUpperCase(),
847
- validationError.path,
848
- validationError.loc.split(".").filter(Boolean),
849
- validationError.msg.trim(),
850
- validationError.type
851
- ].join("|");
852
- return (0, import_node_crypto4.createHash)("md5").update(hashInput).digest("hex");
853
- }
854
- };
855
- __name(_ValidationErrorCounter, "ValidationErrorCounter");
856
- var ValidationErrorCounter = _ValidationErrorCounter;
857
-
858
- // src/common/client.ts
859
- var SYNC_INTERVAL = 6e4;
860
- var INITIAL_SYNC_INTERVAL = 1e4;
861
- var INITIAL_SYNC_INTERVAL_DURATION = 36e5;
862
- var MAX_QUEUE_TIME = 36e5;
863
- var _a;
864
- var HTTPError = (_a = class extends Error {
865
- response;
866
- constructor(response) {
867
- const reason = response.status ? `status code ${response.status}` : "an unknown error";
868
- super(`Request failed with ${reason}`);
869
- this.response = response;
870
- }
871
- }, __name(_a, "HTTPError"), _a);
872
- var _ApitallyClient = class _ApitallyClient {
873
- clientId;
874
- env;
875
- instanceUuid;
876
- syncDataQueue;
877
- syncIntervalId;
878
- startupData;
879
- startupDataSent = false;
880
- enabled = true;
881
- requestCounter;
882
- requestLogger;
883
- validationErrorCounter;
884
- serverErrorCounter;
885
- consumerRegistry;
886
- logger;
887
- constructor({ clientId, env = "dev", requestLogging, requestLoggingConfig, logger }) {
888
- if (_ApitallyClient.instance) {
889
- throw new Error("Apitally client is already initialized");
890
- }
891
- this.logger = logger ?? getLogger();
892
- if (!isValidClientId(clientId)) {
893
- this.logger.error(`Invalid Apitally client ID '${clientId}' (expecting hexadecimal UUID format)`);
894
- this.enabled = false;
895
- }
896
- if (!isValidEnv(env)) {
897
- this.logger.error(`Invalid Apitally env '${env}' (expecting 1-32 alphanumeric characters and hyphens only)`);
898
- this.enabled = false;
899
- }
900
- if (requestLoggingConfig && !requestLogging) {
901
- console.warn("requestLoggingConfig is deprecated, use requestLogging instead.");
902
- }
903
- _ApitallyClient.instance = this;
904
- this.clientId = clientId;
905
- this.env = env;
906
- this.instanceUuid = (0, import_node_crypto5.randomUUID)();
907
- this.syncDataQueue = [];
908
- this.requestCounter = new RequestCounter();
909
- this.requestLogger = new RequestLogger(requestLogging ?? requestLoggingConfig);
910
- this.validationErrorCounter = new ValidationErrorCounter();
911
- this.serverErrorCounter = new ServerErrorCounter();
912
- this.consumerRegistry = new ConsumerRegistry();
913
- this.handleShutdown = this.handleShutdown.bind(this);
914
- }
915
- static getInstance() {
916
- if (!_ApitallyClient.instance) {
917
- throw new Error("Apitally client is not initialized");
918
- }
919
- return _ApitallyClient.instance;
920
- }
921
- isEnabled() {
922
- return this.enabled;
923
- }
924
- static async shutdown() {
925
- if (_ApitallyClient.instance) {
926
- await _ApitallyClient.instance.handleShutdown();
927
- }
928
- }
929
- async handleShutdown() {
930
- this.enabled = false;
931
- this.stopSync();
932
- await this.sendSyncData();
933
- await this.sendLogData();
934
- await this.requestLogger.close();
935
- _ApitallyClient.instance = void 0;
936
- }
937
- getHubUrlPrefix() {
938
- const baseURL = process.env.APITALLY_HUB_BASE_URL || "https://hub.apitally.io";
939
- const version = "v2";
940
- return `${baseURL}/${version}/${this.clientId}/${this.env}/`;
941
- }
942
- async sendData(url, payload) {
943
- const fetchWithRetry = (0, import_fetch_retry.default)(fetch, {
944
- retries: 3,
945
- retryDelay: 1e3,
946
- retryOn: [
947
- 408,
948
- 429,
949
- 500,
950
- 502,
951
- 503,
952
- 504
953
- ]
954
- });
955
- const response = await fetchWithRetry(this.getHubUrlPrefix() + url, {
956
- method: "POST",
957
- body: JSON.stringify(payload),
958
- headers: {
959
- "Content-Type": "application/json"
960
- }
961
- });
962
- if (!response.ok) {
963
- throw new HTTPError(response);
964
- }
965
- }
966
- startSync() {
967
- if (!this.enabled) {
968
- return;
969
- }
970
- this.sync();
971
- this.syncIntervalId = setInterval(() => {
972
- this.sync();
973
- }, INITIAL_SYNC_INTERVAL);
974
- setTimeout(() => {
975
- if (this.syncIntervalId) {
976
- clearInterval(this.syncIntervalId);
977
- this.syncIntervalId = setInterval(() => {
978
- this.sync();
979
- }, SYNC_INTERVAL);
980
- }
981
- }, INITIAL_SYNC_INTERVAL_DURATION);
982
- }
983
- async sync() {
984
- try {
985
- const promises = [
986
- this.sendSyncData(),
987
- this.sendLogData()
988
- ];
989
- if (!this.startupDataSent) {
990
- promises.push(this.sendStartupData());
991
- }
992
- await Promise.all(promises);
993
- } catch (error) {
994
- this.logger.error("Error while syncing with Apitally Hub", {
995
- error
996
- });
997
- }
998
- }
999
- stopSync() {
1000
- if (this.syncIntervalId) {
1001
- clearInterval(this.syncIntervalId);
1002
- this.syncIntervalId = void 0;
1003
- }
1004
- }
1005
- setStartupData(data) {
1006
- this.startupData = data;
1007
- this.startupDataSent = false;
1008
- }
1009
- async sendStartupData() {
1010
- if (this.startupData) {
1011
- this.logger.debug("Sending startup data to Apitally Hub");
1012
- const payload = {
1013
- instance_uuid: this.instanceUuid,
1014
- message_uuid: (0, import_node_crypto5.randomUUID)(),
1015
- ...this.startupData
1016
- };
1017
- try {
1018
- await this.sendData("startup", payload);
1019
- this.startupDataSent = true;
1020
- } catch (error) {
1021
- const handled = this.handleHubError(error);
1022
- if (!handled) {
1023
- this.logger.error(error.message);
1024
- this.logger.debug("Error while sending startup data to Apitally Hub (will retry)", {
1025
- error
1026
- });
1027
- }
1028
- }
1029
- }
1030
- }
1031
- async sendSyncData() {
1032
- this.logger.debug("Synchronizing data with Apitally Hub");
1033
- const newPayload = {
1034
- timestamp: Date.now() / 1e3,
1035
- instance_uuid: this.instanceUuid,
1036
- message_uuid: (0, import_node_crypto5.randomUUID)(),
1037
- requests: this.requestCounter.getAndResetRequests(),
1038
- validation_errors: this.validationErrorCounter.getAndResetValidationErrors(),
1039
- server_errors: this.serverErrorCounter.getAndResetServerErrors(),
1040
- consumers: this.consumerRegistry.getAndResetUpdatedConsumers()
1041
- };
1042
- this.syncDataQueue.push(newPayload);
1043
- let i = 0;
1044
- while (this.syncDataQueue.length > 0) {
1045
- const payload = this.syncDataQueue.shift();
1046
- if (payload) {
1047
- try {
1048
- if (Date.now() - payload.timestamp * 1e3 <= MAX_QUEUE_TIME) {
1049
- if (i > 0) {
1050
- await this.randomDelay();
1051
- }
1052
- await this.sendData("sync", payload);
1053
- i += 1;
1054
- }
1055
- } catch (error) {
1056
- const handled = this.handleHubError(error);
1057
- if (!handled) {
1058
- this.logger.debug("Error while synchronizing data with Apitally Hub (will retry)", {
1059
- error
1060
- });
1061
- this.syncDataQueue.push(payload);
1062
- break;
1063
- }
1064
- }
1065
- }
1066
- }
1067
- }
1068
- async sendLogData() {
1069
- this.logger.debug("Sending request log data to Apitally Hub");
1070
- await this.requestLogger.rotateFile();
1071
- const fetchWithRetry = (0, import_fetch_retry.default)(fetch, {
1072
- retries: 3,
1073
- retryDelay: 1e3,
1074
- retryOn: [
1075
- 408,
1076
- 429,
1077
- 500,
1078
- 502,
1079
- 503,
1080
- 504
1081
- ]
1082
- });
1083
- let i = 0;
1084
- let logFile;
1085
- while (logFile = this.requestLogger.getFile()) {
1086
- if (i > 0) {
1087
- await this.randomDelay();
1088
- }
1089
- try {
1090
- const response = await fetchWithRetry(`${this.getHubUrlPrefix()}log?uuid=${logFile.uuid}`, {
1091
- method: "POST",
1092
- body: await logFile.getContent()
1093
- });
1094
- if (response.status === 402 && response.headers.has("Retry-After")) {
1095
- const retryAfter = parseInt(response.headers.get("Retry-After") ?? "0");
1096
- if (retryAfter > 0) {
1097
- this.requestLogger.suspendUntil = Date.now() + retryAfter * 1e3;
1098
- this.requestLogger.clear();
1099
- return;
1100
- }
1101
- }
1102
- if (!response.ok) {
1103
- throw new HTTPError(response);
1104
- }
1105
- logFile.delete();
1106
- } catch (error) {
1107
- this.requestLogger.retryFileLater(logFile);
1108
- break;
1109
- }
1110
- i++;
1111
- if (i >= 10) break;
1112
- }
1113
- }
1114
- handleHubError(error) {
1115
- if (error instanceof HTTPError) {
1116
- if (error.response.status === 404) {
1117
- this.logger.error(`Invalid Apitally client ID: '${this.clientId}'`);
1118
- this.enabled = false;
1119
- this.stopSync();
1120
- return true;
1121
- }
1122
- if (error.response.status === 422) {
1123
- this.logger.error("Received validation error from Apitally Hub");
1124
- return true;
1125
- }
1126
- }
1127
- return false;
1128
- }
1129
- async randomDelay() {
1130
- const delay = 100 + Math.random() * 400;
1131
- await new Promise((resolve) => setTimeout(resolve, delay));
1132
- }
1133
- };
1134
- __name(_ApitallyClient, "ApitallyClient");
1135
- __publicField(_ApitallyClient, "instance");
1136
- var ApitallyClient = _ApitallyClient;
1137
-
1138
- // src/common/headers.ts
1139
- function parseContentLength(contentLength) {
1140
- if (contentLength === void 0 || contentLength === null) {
1141
- return void 0;
1142
- }
1143
- if (typeof contentLength === "number") {
1144
- return contentLength;
1145
- }
1146
- if (typeof contentLength === "string") {
1147
- const parsed = parseInt(contentLength);
1148
- return isNaN(parsed) ? void 0 : parsed;
1149
- }
1150
- if (Array.isArray(contentLength)) {
1151
- return parseContentLength(contentLength[0]);
1152
- }
1153
- return void 0;
1154
- }
1155
- __name(parseContentLength, "parseContentLength");
1156
-
1157
- // src/common/response.ts
1158
- async function measureResponseSize(response, tee = true) {
1159
- const [newResponse1, newResponse2] = tee ? teeResponse(response) : [
1160
- response,
1161
- response
1162
- ];
1163
- let size = 0;
1164
- if (newResponse2.body) {
1165
- let done = false;
1166
- const reader = newResponse2.body.getReader();
1167
- while (!done) {
1168
- const result = await reader.read();
1169
- done = result.done;
1170
- if (!done && result.value) {
1171
- size += result.value.byteLength;
1172
- }
1173
- }
1174
- }
1175
- return [
1176
- size,
1177
- newResponse1
1178
- ];
1179
- }
1180
- __name(measureResponseSize, "measureResponseSize");
1181
- async function getResponseBody(response, tee = true) {
1182
- const [newResponse1, newResponse2] = tee ? teeResponse(response) : [
1183
- response,
1184
- response
1185
- ];
1186
- const responseBuffer = Buffer.from(await newResponse2.arrayBuffer());
1187
- return [
1188
- responseBuffer,
1189
- newResponse1
1190
- ];
1191
- }
1192
- __name(getResponseBody, "getResponseBody");
1193
- function teeResponse(response) {
1194
- if (!response.body) {
1195
- return [
1196
- response,
1197
- response
1198
- ];
1199
- }
1200
- const [stream1, stream2] = response.body.tee();
1201
- const newResponse1 = new Response(stream1, {
1202
- status: response.status,
1203
- statusText: response.statusText,
1204
- headers: response.headers
1205
- });
1206
- const newResponse2 = new Response(stream2, {
1207
- status: response.status,
1208
- statusText: response.statusText,
1209
- headers: response.headers
1210
- });
1211
- return [
1212
- newResponse1,
1213
- newResponse2
1214
- ];
1215
- }
1216
- __name(teeResponse, "teeResponse");
1217
- function teeResponseBlob(response, blob) {
1218
- const newResponse1 = new Response(blob, {
1219
- status: response.status,
1220
- statusText: response.statusText,
1221
- headers: response.headers
1222
- });
1223
- const newResponse2 = new Response(blob, {
1224
- status: response.status,
1225
- statusText: response.statusText,
1226
- headers: response.headers
1227
- });
1228
- return [
1229
- newResponse1,
1230
- newResponse2
1231
- ];
1232
- }
1233
- __name(teeResponseBlob, "teeResponseBlob");
1234
-
1235
- // src/loggers/console.ts
1236
- var import_node_util = require("util");
1237
- var MAX_BUFFER_SIZE = 1e3;
1238
- var isPatched = false;
1239
- var globalLogsContext;
1240
- function patchConsole(logsContext) {
1241
- globalLogsContext = logsContext;
1242
- if (isPatched) {
1243
- return;
1244
- }
1245
- const logMethods = [
1246
- "log",
1247
- "warn",
1248
- "error",
1249
- "info",
1250
- "debug"
1251
- ];
1252
- logMethods.forEach((method) => {
1253
- const originalMethod = console[method];
1254
- console[method] = function(...args) {
1255
- captureLog(method, args);
1256
- return originalMethod.apply(console, args);
1257
- };
1258
- });
1259
- isPatched = true;
1260
- }
1261
- __name(patchConsole, "patchConsole");
1262
- function captureLog(level, args) {
1263
- const logs = globalLogsContext == null ? void 0 : globalLogsContext.getStore();
1264
- if (logs && logs.length < MAX_BUFFER_SIZE) {
1265
- logs.push({
1266
- timestamp: Date.now() / 1e3,
1267
- logger: "console",
1268
- level,
1269
- message: (0, import_node_util.format)(...args)
1270
- });
1271
- }
1272
- }
1273
- __name(captureLog, "captureLog");
1274
-
1275
- // src/loggers/hapi.ts
1276
- var import_node_util2 = require("util");
1277
-
1278
- // src/loggers/utils.ts
1279
- var import_node_util3 = require("util");
1280
- function formatMessage(message, ...args) {
1281
- return [
1282
- message,
1283
- ...args
1284
- ].map(formatArg).filter((arg) => arg !== "").join("\n");
1285
- }
1286
- __name(formatMessage, "formatMessage");
1287
- function removeKeys(obj, keys) {
1288
- return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key)));
1289
- }
1290
- __name(removeKeys, "removeKeys");
1291
- function formatArg(arg) {
1292
- if (typeof arg === "string") {
1293
- return arg.trim();
1294
- }
1295
- if (arg instanceof Error) {
1296
- return (0, import_node_util3.format)(arg).trim();
1297
- }
1298
- if (arg === void 0 || arg === null || isEmptyObject(arg)) {
1299
- return "";
1300
- }
1301
- try {
1302
- return JSON.stringify(arg);
1303
- } catch {
1304
- return (0, import_node_util3.format)(arg).trim();
1305
- }
1306
- }
1307
- __name(formatArg, "formatArg");
1308
- function isEmptyObject(obj) {
1309
- return obj !== null && typeof obj === "object" && Object.getPrototypeOf(obj) === Object.prototype && Object.keys(obj).length === 0;
1310
- }
1311
- __name(isEmptyObject, "isEmptyObject");
1312
-
1313
- // src/loggers/pino.ts
1314
- var originalStreamSym = Symbol.for("apitally.originalStream");
1315
-
1316
- // src/loggers/winston.ts
1317
- var MAX_BUFFER_SIZE2 = 1e3;
1318
- var isPatched2 = false;
1319
- var globalLogsContext2;
1320
- async function patchWinston(logsContext) {
1321
- var _a2, _b;
1322
- globalLogsContext2 = logsContext;
1323
- if (isPatched2) {
1324
- return;
1325
- }
1326
- try {
1327
- const loggerModule = await import("winston/lib/winston/logger.js");
1328
- if ((_b = (_a2 = loggerModule.default) == null ? void 0 : _a2.prototype) == null ? void 0 : _b.write) {
1329
- const originalWrite = loggerModule.default.prototype.write;
1330
- loggerModule.default.prototype.write = function(info) {
1331
- captureLog2(info);
1332
- return originalWrite.call(this, info);
1333
- };
1334
- }
1335
- } catch {
1336
- }
1337
- isPatched2 = true;
1338
- }
1339
- __name(patchWinston, "patchWinston");
1340
- function captureLog2(info) {
1341
- const logs = globalLogsContext2 == null ? void 0 : globalLogsContext2.getStore();
1342
- if (!logs || !info || logs.length >= MAX_BUFFER_SIZE2) {
1343
- return;
1344
- }
1345
- try {
1346
- const rest = removeKeys(info, [
1347
- "timestamp",
1348
- "level",
1349
- "message",
1350
- "splat"
1351
- ]);
1352
- const formattedMessage = formatMessage(info.message, rest);
1353
- if (formattedMessage) {
1354
- logs.push({
1355
- timestamp: parseTimestamp(info.timestamp),
1356
- level: info.level || "info",
1357
- message: formattedMessage.trim()
1358
- });
1359
- }
1360
- } catch (e) {
1361
- }
1362
- }
1363
- __name(captureLog2, "captureLog");
1364
- function parseTimestamp(timestamp) {
1365
- if (timestamp) {
1366
- const ts = new Date(timestamp).getTime();
1367
- if (!isNaN(ts)) {
1368
- return ts / 1e3;
1369
- }
1370
- }
1371
- return Date.now() / 1e3;
1372
- }
1373
- __name(parseTimestamp, "parseTimestamp");
1374
-
1375
- // src/common/packageVersions.ts
1376
- var import_node_module = require("module");
1377
- var import_meta = {};
1378
- function getPackageVersion(name) {
1379
- const packageJsonPath = `${name}/package.json`;
1380
- try {
1381
- return require(packageJsonPath).version || null;
1382
- } catch (error) {
1383
- try {
1384
- const _require = (0, import_node_module.createRequire)(import_meta.url);
1385
- return _require(packageJsonPath).version || null;
1386
- } catch (error2) {
1387
- return null;
1388
- }
1389
- }
1390
- }
1391
- __name(getPackageVersion, "getPackageVersion");
1392
-
1393
- // src/elysia/utils.ts
1394
- function getAppInfo(app, appVersion) {
1395
- const versions = [];
1396
- if (process.versions.node) {
1397
- versions.push([
1398
- "nodejs",
1399
- process.versions.node
1400
- ]);
1401
- }
1402
- if (process.versions.bun) {
1403
- versions.push([
1404
- "bun",
1405
- process.versions.bun
1406
- ]);
1407
- }
1408
- const elysiaVersion = getPackageVersion("elysia");
1409
- const apitallyVersion = getPackageVersion("../..");
1410
- if (elysiaVersion) {
1411
- versions.push([
1412
- "elysia",
1413
- elysiaVersion
1414
- ]);
1415
- }
1416
- if (apitallyVersion) {
1417
- versions.push([
1418
- "apitally",
1419
- apitallyVersion
1420
- ]);
1421
- }
1422
- if (appVersion) {
1423
- versions.push([
1424
- "app",
1425
- appVersion
1426
- ]);
1427
- }
1428
- return {
1429
- paths: app.routes.map((route) => ({
1430
- method: route.method.toUpperCase(),
1431
- path: route.path
1432
- })).filter((route) => route.method && route.path && ![
1433
- "HEAD",
1434
- "OPTIONS"
1435
- ].includes(route.method)),
1436
- versions: Object.fromEntries(versions),
1437
- client: "js:elysia"
1438
- };
1439
- }
1440
- __name(getAppInfo, "getAppInfo");
1441
-
1442
- // src/elysia/plugin.ts
1443
- var START_TIME_SYMBOL = Symbol("apitally.startTime");
1444
- var REQUEST_BODY_SYMBOL = Symbol("apitally.requestBody");
1445
- var RESPONSE_SYMBOL = Symbol("apitally.response");
1446
- var ERROR_SYMBOL = Symbol("apitally.error");
1447
- function apitallyPlugin(config) {
1448
- const client = new ApitallyClient(config);
1449
- const logsContext = new import_node_async_hooks.AsyncLocalStorage();
1450
- if (client.requestLogger.enabled && client.requestLogger.config.captureLogs) {
1451
- patchConsole(logsContext);
1452
- patchWinston(logsContext);
1453
- }
1454
- return (app) => {
1455
- const handler = app["~adapter"].handler;
1456
- const originalMapResponse = handler.mapResponse;
1457
- const originalMapCompactResponse = handler.mapCompactResponse;
1458
- const originalMapEarlyResponse = handler.mapEarlyResponse;
1459
- const captureResponse = /* @__PURE__ */ __name((originalResponse, mappedResponse, request) => {
1460
- var _a2;
1461
- if (request instanceof Request && mappedResponse instanceof Response && !(RESPONSE_SYMBOL in request)) {
1462
- const [newResponse1, newResponse2] = ((_a2 = originalResponse == null ? void 0 : originalResponse.constructor) == null ? void 0 : _a2.name) === "String" ? teeResponseBlob(mappedResponse, originalResponse) : teeResponse(mappedResponse);
1463
- request[RESPONSE_SYMBOL] = newResponse2;
1464
- return newResponse1;
1465
- } else {
1466
- return mappedResponse;
1467
- }
1468
- }, "captureResponse");
1469
- handler.mapResponse = /* @__PURE__ */ __name(function wrappedMapResponse(response, set, request) {
1470
- const mappedResponse = originalMapResponse(response, set, request);
1471
- const newResponse = captureResponse(response, mappedResponse, request);
1472
- return newResponse;
1473
- }, "wrappedMapResponse");
1474
- handler.mapCompactResponse = /* @__PURE__ */ __name(function wrappedMapCompactResponse(response, request) {
1475
- const mappedResponse = originalMapCompactResponse(response, request);
1476
- const newResponse = captureResponse(response, mappedResponse, request);
1477
- return newResponse;
1478
- }, "wrappedMapCompactResponse");
1479
- handler.mapEarlyResponse = /* @__PURE__ */ __name(function wrappedMapEarlyResponse(response, set, request) {
1480
- const mappedResponse = originalMapEarlyResponse(response, set, request);
1481
- const newResponse = captureResponse(response, mappedResponse, request);
1482
- return newResponse;
1483
- }, "wrappedMapEarlyResponse");
1484
- return app.decorate("apitally", {}).onStart(() => {
1485
- const appInfo = getAppInfo(app, config.appVersion);
1486
- client.setStartupData(appInfo);
1487
- client.startSync();
1488
- }).onStop(async () => {
1489
- await client.handleShutdown();
1490
- }).onRequest(async ({ request }) => {
1491
- if (!client.isEnabled() || request.method.toUpperCase() === "OPTIONS") {
1492
- return;
1493
- }
1494
- logsContext.enterWith([]);
1495
- request[START_TIME_SYMBOL] = import_node_perf_hooks.performance.now();
1496
- if (client.requestLogger.enabled && client.requestLogger.config.logRequestBody) {
1497
- const contentType = request.headers.get("content-type");
1498
- const requestSize = parseContentLength(request.headers.get("content-length")) ?? 0;
1499
- if (client.requestLogger.isSupportedContentType(contentType) && requestSize <= client.requestLogger.maxBodySize) {
1500
- try {
1501
- request[REQUEST_BODY_SYMBOL] = Buffer.from(await request.clone().arrayBuffer());
1502
- } catch (error) {
1503
- }
1504
- }
1505
- }
1506
- }).onAfterResponse(async ({ request, set, route, apitally }) => {
1507
- if (!client.isEnabled() || request.method.toUpperCase() === "OPTIONS") {
1508
- return;
1509
- }
1510
- const startTime = request[START_TIME_SYMBOL];
1511
- const responseTime = startTime ? import_node_perf_hooks.performance.now() - startTime : 0;
1512
- const requestBody = request[REQUEST_BODY_SYMBOL];
1513
- const requestSize = parseContentLength(request.headers.get("content-length")) ?? (requestBody == null ? void 0 : requestBody.length);
1514
- const error = request[ERROR_SYMBOL];
1515
- let response = request[RESPONSE_SYMBOL];
1516
- let responseBody;
1517
- let responseSize;
1518
- if (!response && error && "toResponse" in error && typeof error.toResponse === "function") {
1519
- try {
1520
- response = error.toResponse();
1521
- } catch (error2) {
1522
- }
1523
- }
1524
- if (response instanceof Response) {
1525
- if (client.requestLogger.enabled && client.requestLogger.config.logResponseBody && client.requestLogger.isSupportedContentType(response.headers.get("content-type"))) {
1526
- responseBody = (await getResponseBody(response, false))[0];
1527
- responseSize = responseBody.length;
1528
- } else {
1529
- responseSize = (await measureResponseSize(response, false))[0];
1530
- }
1531
- }
1532
- const statusCode = (response == null ? void 0 : response.status) ?? getStatusCode(set) ?? 200;
1533
- const responseHeaders = (response == null ? void 0 : response.headers) ?? set.headers;
1534
- const consumer = apitally.consumer ? consumerFromStringOrObject(apitally.consumer) : null;
1535
- client.consumerRegistry.addOrUpdateConsumer(consumer);
1536
- if (route) {
1537
- client.requestCounter.addRequest({
1538
- consumer: consumer == null ? void 0 : consumer.identifier,
1539
- method: request.method,
1540
- path: route,
1541
- statusCode,
1542
- responseTime,
1543
- requestSize,
1544
- responseSize
1545
- });
1546
- if (statusCode === 500 && error) {
1547
- client.serverErrorCounter.addServerError({
1548
- consumer: consumer == null ? void 0 : consumer.identifier,
1549
- method: request.method,
1550
- path: route,
1551
- type: error.name,
1552
- msg: error.message,
1553
- traceback: error.stack || ""
1554
- });
1555
- }
1556
- if ((statusCode === 400 || statusCode === 422) && error instanceof import_elysia.ValidationError) {
1557
- try {
1558
- const parsedMessage = JSON.parse(error.message);
1559
- client.validationErrorCounter.addValidationError({
1560
- consumer: consumer == null ? void 0 : consumer.identifier,
1561
- method: request.method,
1562
- path: route,
1563
- loc: (parsedMessage.on ?? "") + "." + (parsedMessage.property ?? ""),
1564
- msg: parsedMessage.message,
1565
- type: ""
1566
- });
1567
- } catch (error2) {
1568
- }
1569
- }
1570
- }
1571
- if (client.requestLogger.enabled) {
1572
- const logs = logsContext.getStore();
1573
- client.requestLogger.logRequest({
1574
- timestamp: (Date.now() - responseTime) / 1e3,
1575
- method: request.method,
1576
- path: route,
1577
- url: request.url,
1578
- headers: convertHeaders(Object.fromEntries(request.headers.entries())),
1579
- size: requestSize,
1580
- consumer: consumer == null ? void 0 : consumer.identifier,
1581
- body: requestBody
1582
- }, {
1583
- statusCode,
1584
- responseTime: responseTime / 1e3,
1585
- headers: convertHeaders(responseHeaders),
1586
- size: responseSize,
1587
- body: responseBody
1588
- }, error, logs);
1589
- }
1590
- }).onError(({ request, error }) => {
1591
- if (client.isEnabled() && error instanceof Error) {
1592
- request[ERROR_SYMBOL] = error;
1593
- }
1594
- });
1595
- };
1596
- }
1597
- __name(apitallyPlugin, "apitallyPlugin");
1598
- function getStatusCode(set) {
1599
- if (typeof set.status === "number") {
1600
- return set.status;
1601
- } else if (typeof set.status === "string") {
1602
- return import_elysia.StatusMap[set.status];
1603
- }
1604
- }
1605
- __name(getStatusCode, "getStatusCode");
34
+ var import_plugin = __toESM(require("./plugin.js"), 1);
1606
35
  // Annotate the CommonJS export names for ESM import in node:
1607
36
  0 && (module.exports = {
1608
37
  apitallyPlugin