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