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