apitally 0.8.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,781 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
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
+ 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/hono/middleware.ts
34
+ var middleware_exports = {};
35
+ __export(middleware_exports, {
36
+ useApitally: () => useApitally
37
+ });
38
+ module.exports = __toCommonJS(middleware_exports);
39
+ var import_handler = require("hono/utils/handler");
40
+ var import_perf_hooks = require("perf_hooks");
41
+
42
+ // src/common/client.ts
43
+ var import_crypto3 = require("crypto");
44
+ var import_fetch_retry = __toESM(require("fetch-retry"), 1);
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
+ var getLogger = /* @__PURE__ */ __name(() => {
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
+ }, "getLogger");
113
+
114
+ // src/common/paramValidation.ts
115
+ function isValidClientId(clientId) {
116
+ 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;
117
+ return regexExp.test(clientId);
118
+ }
119
+ __name(isValidClientId, "isValidClientId");
120
+ function isValidEnv(env) {
121
+ const regexExp = /^[\w-]{1,32}$/;
122
+ return regexExp.test(env);
123
+ }
124
+ __name(isValidEnv, "isValidEnv");
125
+
126
+ // src/common/requestCounter.ts
127
+ var _RequestCounter = class _RequestCounter {
128
+ requestCounts;
129
+ requestSizeSums;
130
+ responseSizeSums;
131
+ responseTimes;
132
+ requestSizes;
133
+ responseSizes;
134
+ constructor() {
135
+ this.requestCounts = /* @__PURE__ */ new Map();
136
+ this.requestSizeSums = /* @__PURE__ */ new Map();
137
+ this.responseSizeSums = /* @__PURE__ */ new Map();
138
+ this.responseTimes = /* @__PURE__ */ new Map();
139
+ this.requestSizes = /* @__PURE__ */ new Map();
140
+ this.responseSizes = /* @__PURE__ */ new Map();
141
+ }
142
+ getKey(requestInfo) {
143
+ return [
144
+ requestInfo.consumer || "",
145
+ requestInfo.method.toUpperCase(),
146
+ requestInfo.path,
147
+ requestInfo.statusCode
148
+ ].join("|");
149
+ }
150
+ addRequest(requestInfo) {
151
+ const key = this.getKey(requestInfo);
152
+ this.requestCounts.set(key, (this.requestCounts.get(key) || 0) + 1);
153
+ if (!this.responseTimes.has(key)) {
154
+ this.responseTimes.set(key, /* @__PURE__ */ new Map());
155
+ }
156
+ const responseTimeMap = this.responseTimes.get(key);
157
+ const responseTimeMsBin = Math.floor(requestInfo.responseTime / 10) * 10;
158
+ responseTimeMap.set(responseTimeMsBin, (responseTimeMap.get(responseTimeMsBin) || 0) + 1);
159
+ if (requestInfo.requestSize !== void 0) {
160
+ requestInfo.requestSize = Number(requestInfo.requestSize);
161
+ this.requestSizeSums.set(key, (this.requestSizeSums.get(key) || 0) + requestInfo.requestSize);
162
+ if (!this.requestSizes.has(key)) {
163
+ this.requestSizes.set(key, /* @__PURE__ */ new Map());
164
+ }
165
+ const requestSizeMap = this.requestSizes.get(key);
166
+ const requestSizeKbBin = Math.floor(requestInfo.requestSize / 1e3);
167
+ requestSizeMap.set(requestSizeKbBin, (requestSizeMap.get(requestSizeKbBin) || 0) + 1);
168
+ }
169
+ if (requestInfo.responseSize !== void 0) {
170
+ requestInfo.responseSize = Number(requestInfo.responseSize);
171
+ this.responseSizeSums.set(key, (this.responseSizeSums.get(key) || 0) + requestInfo.responseSize);
172
+ if (!this.responseSizes.has(key)) {
173
+ this.responseSizes.set(key, /* @__PURE__ */ new Map());
174
+ }
175
+ const responseSizeMap = this.responseSizes.get(key);
176
+ const responseSizeKbBin = Math.floor(requestInfo.responseSize / 1e3);
177
+ responseSizeMap.set(responseSizeKbBin, (responseSizeMap.get(responseSizeKbBin) || 0) + 1);
178
+ }
179
+ }
180
+ getAndResetRequests() {
181
+ const data = [];
182
+ this.requestCounts.forEach((count, key) => {
183
+ const [consumer, method, path, statusCodeStr] = key.split("|");
184
+ const responseTimes = this.responseTimes.get(key) || /* @__PURE__ */ new Map();
185
+ const requestSizes = this.requestSizes.get(key) || /* @__PURE__ */ new Map();
186
+ const responseSizes = this.responseSizes.get(key) || /* @__PURE__ */ new Map();
187
+ data.push({
188
+ consumer: consumer || null,
189
+ method,
190
+ path,
191
+ status_code: parseInt(statusCodeStr),
192
+ request_count: count,
193
+ request_size_sum: this.requestSizeSums.get(key) || 0,
194
+ response_size_sum: this.responseSizeSums.get(key) || 0,
195
+ response_times: Object.fromEntries(responseTimes),
196
+ request_sizes: Object.fromEntries(requestSizes),
197
+ response_sizes: Object.fromEntries(responseSizes)
198
+ });
199
+ });
200
+ this.requestCounts.clear();
201
+ this.requestSizeSums.clear();
202
+ this.responseSizeSums.clear();
203
+ this.responseTimes.clear();
204
+ this.requestSizes.clear();
205
+ this.responseSizes.clear();
206
+ return data;
207
+ }
208
+ };
209
+ __name(_RequestCounter, "RequestCounter");
210
+ var RequestCounter = _RequestCounter;
211
+
212
+ // src/common/serverErrorCounter.ts
213
+ var import_crypto = require("crypto");
214
+ var MAX_MSG_LENGTH = 2048;
215
+ var MAX_STACKTRACE_LENGTH = 65536;
216
+ var _ServerErrorCounter = class _ServerErrorCounter {
217
+ errorCounts;
218
+ errorDetails;
219
+ sentryEventIds;
220
+ sentry;
221
+ constructor() {
222
+ this.errorCounts = /* @__PURE__ */ new Map();
223
+ this.errorDetails = /* @__PURE__ */ new Map();
224
+ this.sentryEventIds = /* @__PURE__ */ new Map();
225
+ this.tryImportSentry();
226
+ }
227
+ addServerError(serverError) {
228
+ const key = this.getKey(serverError);
229
+ if (!this.errorDetails.has(key)) {
230
+ this.errorDetails.set(key, serverError);
231
+ }
232
+ this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
233
+ this.captureSentryEventId(key);
234
+ }
235
+ getAndResetServerErrors() {
236
+ const data = [];
237
+ this.errorCounts.forEach((count, key) => {
238
+ const serverError = this.errorDetails.get(key);
239
+ if (serverError) {
240
+ data.push({
241
+ consumer: serverError.consumer || null,
242
+ method: serverError.method,
243
+ path: serverError.path,
244
+ type: serverError.type,
245
+ msg: this.getTruncatedMessage(serverError.msg),
246
+ traceback: this.getTruncatedStack(serverError.traceback),
247
+ sentry_event_id: this.sentryEventIds.get(key) || null,
248
+ error_count: count
249
+ });
250
+ }
251
+ });
252
+ this.errorCounts.clear();
253
+ this.errorDetails.clear();
254
+ return data;
255
+ }
256
+ getKey(serverError) {
257
+ const hashInput = [
258
+ serverError.consumer || "",
259
+ serverError.method.toUpperCase(),
260
+ serverError.path,
261
+ serverError.type,
262
+ serverError.msg.trim(),
263
+ serverError.traceback.trim()
264
+ ].join("|");
265
+ return (0, import_crypto.createHash)("md5").update(hashInput).digest("hex");
266
+ }
267
+ getTruncatedMessage(msg) {
268
+ msg = msg.trim();
269
+ if (msg.length <= MAX_MSG_LENGTH) {
270
+ return msg;
271
+ }
272
+ const suffix = "... (truncated)";
273
+ const cutoff = MAX_MSG_LENGTH - suffix.length;
274
+ return msg.substring(0, cutoff) + suffix;
275
+ }
276
+ getTruncatedStack(stack) {
277
+ const suffix = "... (truncated) ...";
278
+ const cutoff = MAX_STACKTRACE_LENGTH - suffix.length;
279
+ const lines = stack.trim().split("\n");
280
+ const truncatedLines = [];
281
+ let length = 0;
282
+ for (const line of lines) {
283
+ if (length + line.length + 1 > cutoff) {
284
+ truncatedLines.push(suffix);
285
+ break;
286
+ }
287
+ truncatedLines.push(line);
288
+ length += line.length + 1;
289
+ }
290
+ return truncatedLines.join("\n");
291
+ }
292
+ captureSentryEventId(serverErrorKey) {
293
+ if (this.sentry && this.sentry.lastEventId) {
294
+ const eventId = this.sentry.lastEventId();
295
+ if (eventId) {
296
+ this.sentryEventIds.set(serverErrorKey, eventId);
297
+ }
298
+ }
299
+ }
300
+ async tryImportSentry() {
301
+ try {
302
+ this.sentry = await import("@sentry/node");
303
+ } catch (e) {
304
+ }
305
+ }
306
+ };
307
+ __name(_ServerErrorCounter, "ServerErrorCounter");
308
+ var ServerErrorCounter = _ServerErrorCounter;
309
+
310
+ // src/common/validationErrorCounter.ts
311
+ var import_crypto2 = require("crypto");
312
+ var _ValidationErrorCounter = class _ValidationErrorCounter {
313
+ errorCounts;
314
+ errorDetails;
315
+ constructor() {
316
+ this.errorCounts = /* @__PURE__ */ new Map();
317
+ this.errorDetails = /* @__PURE__ */ new Map();
318
+ }
319
+ addValidationError(validationError) {
320
+ const key = this.getKey(validationError);
321
+ if (!this.errorDetails.has(key)) {
322
+ this.errorDetails.set(key, validationError);
323
+ }
324
+ this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
325
+ }
326
+ getAndResetValidationErrors() {
327
+ const data = [];
328
+ this.errorCounts.forEach((count, key) => {
329
+ const validationError = this.errorDetails.get(key);
330
+ if (validationError) {
331
+ data.push({
332
+ consumer: validationError.consumer || null,
333
+ method: validationError.method,
334
+ path: validationError.path,
335
+ loc: validationError.loc.split("."),
336
+ msg: validationError.msg,
337
+ type: validationError.type,
338
+ error_count: count
339
+ });
340
+ }
341
+ });
342
+ this.errorCounts.clear();
343
+ this.errorDetails.clear();
344
+ return data;
345
+ }
346
+ getKey(validationError) {
347
+ const hashInput = [
348
+ validationError.consumer || "",
349
+ validationError.method.toUpperCase(),
350
+ validationError.path,
351
+ validationError.loc,
352
+ validationError.msg.trim(),
353
+ validationError.type
354
+ ].join("|");
355
+ return (0, import_crypto2.createHash)("md5").update(hashInput).digest("hex");
356
+ }
357
+ };
358
+ __name(_ValidationErrorCounter, "ValidationErrorCounter");
359
+ var ValidationErrorCounter = _ValidationErrorCounter;
360
+
361
+ // src/common/client.ts
362
+ var SYNC_INTERVAL = 6e4;
363
+ var INITIAL_SYNC_INTERVAL = 1e4;
364
+ var INITIAL_SYNC_INTERVAL_DURATION = 36e5;
365
+ var MAX_QUEUE_TIME = 36e5;
366
+ var _a;
367
+ var HTTPError = (_a = class extends Error {
368
+ response;
369
+ constructor(response) {
370
+ const reason = response.status ? `status code ${response.status}` : "an unknown error";
371
+ super(`Request failed with ${reason}`);
372
+ this.response = response;
373
+ }
374
+ }, __name(_a, "HTTPError"), _a);
375
+ var _ApitallyClient = class _ApitallyClient {
376
+ clientId;
377
+ env;
378
+ instanceUuid;
379
+ syncDataQueue;
380
+ syncIntervalId;
381
+ startupData;
382
+ startupDataSent = false;
383
+ requestCounter;
384
+ validationErrorCounter;
385
+ serverErrorCounter;
386
+ consumerRegistry;
387
+ logger;
388
+ constructor({ clientId, env = "dev", logger }) {
389
+ if (_ApitallyClient.instance) {
390
+ throw new Error("Apitally client is already initialized");
391
+ }
392
+ if (!isValidClientId(clientId)) {
393
+ throw new Error(`Invalid client ID '${clientId}' (expecting hexadeciaml UUID format)`);
394
+ }
395
+ if (!isValidEnv(env)) {
396
+ throw new Error(`Invalid env '${env}' (expecting 1-32 alphanumeric lowercase characters and hyphens only)`);
397
+ }
398
+ _ApitallyClient.instance = this;
399
+ this.clientId = clientId;
400
+ this.env = env;
401
+ this.instanceUuid = (0, import_crypto3.randomUUID)();
402
+ this.syncDataQueue = [];
403
+ this.requestCounter = new RequestCounter();
404
+ this.validationErrorCounter = new ValidationErrorCounter();
405
+ this.serverErrorCounter = new ServerErrorCounter();
406
+ this.consumerRegistry = new ConsumerRegistry();
407
+ this.logger = logger || getLogger();
408
+ this.startSync();
409
+ this.handleShutdown = this.handleShutdown.bind(this);
410
+ }
411
+ static getInstance() {
412
+ if (!_ApitallyClient.instance) {
413
+ throw new Error("Apitally client is not initialized");
414
+ }
415
+ return _ApitallyClient.instance;
416
+ }
417
+ static async shutdown() {
418
+ if (_ApitallyClient.instance) {
419
+ await _ApitallyClient.instance.handleShutdown();
420
+ }
421
+ }
422
+ async handleShutdown() {
423
+ this.stopSync();
424
+ await this.sendSyncData();
425
+ _ApitallyClient.instance = void 0;
426
+ }
427
+ getHubUrlPrefix() {
428
+ const baseURL = process.env.APITALLY_HUB_BASE_URL || "https://hub.apitally.io";
429
+ const version = "v2";
430
+ return `${baseURL}/${version}/${this.clientId}/${this.env}/`;
431
+ }
432
+ async sendData(url, payload) {
433
+ const fetchWithRetry = (0, import_fetch_retry.default)(fetch, {
434
+ retries: 3,
435
+ retryDelay: 1e3,
436
+ retryOn: [
437
+ 408,
438
+ 429,
439
+ 500,
440
+ 502,
441
+ 503,
442
+ 504
443
+ ]
444
+ });
445
+ const response = await fetchWithRetry(this.getHubUrlPrefix() + url, {
446
+ method: "POST",
447
+ body: JSON.stringify(payload),
448
+ headers: {
449
+ "Content-Type": "application/json"
450
+ }
451
+ });
452
+ if (!response.ok) {
453
+ throw new HTTPError(response);
454
+ }
455
+ }
456
+ startSync() {
457
+ this.sync();
458
+ this.syncIntervalId = setInterval(() => {
459
+ this.sync();
460
+ }, INITIAL_SYNC_INTERVAL);
461
+ setTimeout(() => {
462
+ clearInterval(this.syncIntervalId);
463
+ this.syncIntervalId = setInterval(() => {
464
+ this.sync();
465
+ }, SYNC_INTERVAL);
466
+ }, INITIAL_SYNC_INTERVAL_DURATION);
467
+ }
468
+ async sync() {
469
+ try {
470
+ const promises = [
471
+ this.sendSyncData()
472
+ ];
473
+ if (!this.startupDataSent) {
474
+ promises.push(this.sendStartupData());
475
+ }
476
+ await Promise.all(promises);
477
+ } catch (error) {
478
+ this.logger.error("Error while syncing with Apitally Hub", {
479
+ error
480
+ });
481
+ }
482
+ }
483
+ stopSync() {
484
+ if (this.syncIntervalId) {
485
+ clearInterval(this.syncIntervalId);
486
+ this.syncIntervalId = void 0;
487
+ }
488
+ }
489
+ setStartupData(data) {
490
+ this.startupData = data;
491
+ this.startupDataSent = false;
492
+ this.sendStartupData();
493
+ }
494
+ async sendStartupData() {
495
+ if (this.startupData) {
496
+ this.logger.debug("Sending startup data to Apitally Hub");
497
+ const payload = {
498
+ instance_uuid: this.instanceUuid,
499
+ message_uuid: (0, import_crypto3.randomUUID)(),
500
+ ...this.startupData
501
+ };
502
+ try {
503
+ await this.sendData("startup", payload);
504
+ this.startupDataSent = true;
505
+ } catch (error) {
506
+ const handled = this.handleHubError(error);
507
+ if (!handled) {
508
+ this.logger.error(error.message);
509
+ this.logger.debug("Error while sending startup data to Apitally Hub (will retry)", {
510
+ error
511
+ });
512
+ }
513
+ }
514
+ }
515
+ }
516
+ async sendSyncData() {
517
+ this.logger.debug("Synchronizing data with Apitally Hub");
518
+ const newPayload = {
519
+ time_offset: 0,
520
+ instance_uuid: this.instanceUuid,
521
+ message_uuid: (0, import_crypto3.randomUUID)(),
522
+ requests: this.requestCounter.getAndResetRequests(),
523
+ validation_errors: this.validationErrorCounter.getAndResetValidationErrors(),
524
+ server_errors: this.serverErrorCounter.getAndResetServerErrors(),
525
+ consumers: this.consumerRegistry.getAndResetUpdatedConsumers()
526
+ };
527
+ this.syncDataQueue.push([
528
+ Date.now(),
529
+ newPayload
530
+ ]);
531
+ let i = 0;
532
+ while (this.syncDataQueue.length > 0) {
533
+ const queueItem = this.syncDataQueue.shift();
534
+ if (queueItem) {
535
+ const [time, payload] = queueItem;
536
+ try {
537
+ const timeOffset = Date.now() - time;
538
+ if (timeOffset <= MAX_QUEUE_TIME) {
539
+ if (i > 0) {
540
+ const waitMs = 100 + Math.random() * 200;
541
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
542
+ }
543
+ payload.time_offset = timeOffset / 1e3;
544
+ await this.sendData("sync", payload);
545
+ i += 1;
546
+ }
547
+ } catch (error) {
548
+ const handled = this.handleHubError(error);
549
+ if (!handled) {
550
+ this.logger.debug("Error while synchronizing data with Apitally Hub (will retry)", {
551
+ error
552
+ });
553
+ this.syncDataQueue.push(queueItem);
554
+ break;
555
+ }
556
+ }
557
+ }
558
+ }
559
+ }
560
+ handleHubError(error) {
561
+ if (error instanceof HTTPError) {
562
+ if (error.response.status === 404) {
563
+ this.logger.error(`Invalid Apitally client ID: '${this.clientId}'`);
564
+ this.stopSync();
565
+ return true;
566
+ }
567
+ if (error.response.status === 422) {
568
+ this.logger.error("Received validation error from Apitally Hub");
569
+ return true;
570
+ }
571
+ }
572
+ return false;
573
+ }
574
+ };
575
+ __name(_ApitallyClient, "ApitallyClient");
576
+ __publicField(_ApitallyClient, "instance");
577
+ var ApitallyClient = _ApitallyClient;
578
+
579
+ // src/common/packageVersions.ts
580
+ var import_module = require("module");
581
+ var import_meta = {};
582
+ function getPackageVersion(name) {
583
+ try {
584
+ const _require = (0, import_module.createRequire)(import_meta.url);
585
+ return _require(`${name}/package.json`).version || null;
586
+ } catch (error) {
587
+ return null;
588
+ }
589
+ }
590
+ __name(getPackageVersion, "getPackageVersion");
591
+
592
+ // src/hono/middleware.ts
593
+ var useApitally = /* @__PURE__ */ __name((app, config) => {
594
+ const client = new ApitallyClient(config);
595
+ const middleware = getMiddleware(client);
596
+ app.use(middleware);
597
+ setTimeout(() => {
598
+ client.setStartupData(getAppInfo(app, config.appVersion));
599
+ }, 1e3);
600
+ }, "useApitally");
601
+ var getMiddleware = /* @__PURE__ */ __name((client) => {
602
+ const zodInstalled = getPackageVersion("zod") !== null;
603
+ return async (c, next) => {
604
+ const startTime = import_perf_hooks.performance.now();
605
+ await next();
606
+ let response;
607
+ const responseTime = import_perf_hooks.performance.now() - startTime;
608
+ const [responseSize, newResponse] = await measureResponseSize(c.res);
609
+ const consumer = getConsumer(c);
610
+ client.consumerRegistry.addOrUpdateConsumer(consumer);
611
+ client.requestCounter.addRequest({
612
+ consumer: consumer == null ? void 0 : consumer.identifier,
613
+ method: c.req.method,
614
+ path: c.req.routePath,
615
+ statusCode: c.res.status,
616
+ responseTime,
617
+ requestSize: c.req.header("Content-Length"),
618
+ responseSize
619
+ });
620
+ response = newResponse;
621
+ if (c.res.status === 400 && zodInstalled) {
622
+ const [responseJson, newResponse2] = await getResponseJson(response);
623
+ const validationErrors = extractZodErrors(responseJson);
624
+ validationErrors.forEach((error) => {
625
+ client.validationErrorCounter.addValidationError({
626
+ consumer: consumer == null ? void 0 : consumer.identifier,
627
+ method: c.req.method,
628
+ path: c.req.routePath,
629
+ ...error
630
+ });
631
+ });
632
+ response = newResponse2;
633
+ }
634
+ if (c.error) {
635
+ client.serverErrorCounter.addServerError({
636
+ consumer: consumer == null ? void 0 : consumer.identifier,
637
+ method: c.req.method,
638
+ path: c.req.routePath,
639
+ type: c.error.name,
640
+ msg: c.error.message,
641
+ traceback: c.error.stack || ""
642
+ });
643
+ }
644
+ c.res = response;
645
+ };
646
+ }, "getMiddleware");
647
+ var getConsumer = /* @__PURE__ */ __name((c) => {
648
+ const consumer = c.get("apitallyConsumer");
649
+ if (consumer) {
650
+ return consumerFromStringOrObject(consumer);
651
+ }
652
+ return null;
653
+ }, "getConsumer");
654
+ var measureResponseSize = /* @__PURE__ */ __name(async (response) => {
655
+ const [newResponse1, newResponse2] = await teeResponse(response);
656
+ let size = 0;
657
+ if (newResponse2.body) {
658
+ let done = false;
659
+ const reader = newResponse2.body.getReader();
660
+ while (!done) {
661
+ const result = await reader.read();
662
+ done = result.done;
663
+ if (!done && result.value) {
664
+ size += result.value.byteLength;
665
+ }
666
+ }
667
+ }
668
+ return [
669
+ size,
670
+ newResponse1
671
+ ];
672
+ }, "measureResponseSize");
673
+ var getResponseJson = /* @__PURE__ */ __name(async (response) => {
674
+ const contentType = response.headers.get("content-type");
675
+ if (contentType && contentType.includes("application/json")) {
676
+ const [newResponse1, newResponse2] = await teeResponse(response);
677
+ const responseJson = await newResponse2.json();
678
+ return [
679
+ responseJson,
680
+ newResponse1
681
+ ];
682
+ }
683
+ return [
684
+ null,
685
+ response
686
+ ];
687
+ }, "getResponseJson");
688
+ var teeResponse = /* @__PURE__ */ __name(async (response) => {
689
+ if (!response.body) {
690
+ return [
691
+ response,
692
+ response
693
+ ];
694
+ }
695
+ const [stream1, stream2] = response.body.tee();
696
+ const newResponse1 = new Response(stream1, {
697
+ status: response.status,
698
+ statusText: response.statusText,
699
+ headers: response.headers
700
+ });
701
+ const newResponse2 = new Response(stream2, {
702
+ status: response.status,
703
+ statusText: response.statusText,
704
+ headers: response.headers
705
+ });
706
+ return [
707
+ newResponse1,
708
+ newResponse2
709
+ ];
710
+ }, "teeResponse");
711
+ var extractZodErrors = /* @__PURE__ */ __name((responseJson) => {
712
+ const errors = [];
713
+ if (responseJson && responseJson.success === false && responseJson.error && responseJson.error.name === "ZodError") {
714
+ const zodError = responseJson.error;
715
+ zodError.issues.forEach((zodIssue) => {
716
+ errors.push({
717
+ loc: zodIssue.path.join("."),
718
+ msg: zodIssue.message,
719
+ type: zodIssue.code
720
+ });
721
+ });
722
+ }
723
+ return errors;
724
+ }, "extractZodErrors");
725
+ var getAppInfo = /* @__PURE__ */ __name((app, appVersion) => {
726
+ const versions = [];
727
+ if (process.versions.node) {
728
+ versions.push([
729
+ "nodejs",
730
+ process.versions.node
731
+ ]);
732
+ }
733
+ if (process.versions.bun) {
734
+ versions.push([
735
+ "bun",
736
+ process.versions.bun
737
+ ]);
738
+ }
739
+ const honoVersion = getPackageVersion("hono");
740
+ const apitallyVersion = getPackageVersion("../..");
741
+ if (honoVersion) {
742
+ versions.push([
743
+ "hono",
744
+ honoVersion
745
+ ]);
746
+ }
747
+ if (apitallyVersion) {
748
+ versions.push([
749
+ "apitally",
750
+ apitallyVersion
751
+ ]);
752
+ }
753
+ if (appVersion) {
754
+ versions.push([
755
+ "app",
756
+ appVersion
757
+ ]);
758
+ }
759
+ return {
760
+ paths: listEndpoints(app),
761
+ versions: Object.fromEntries(versions),
762
+ client: "js:hono"
763
+ };
764
+ }, "getAppInfo");
765
+ var listEndpoints = /* @__PURE__ */ __name((app) => {
766
+ const endpoints = [];
767
+ app.routes.forEach((route) => {
768
+ if (route.method !== "ALL" && !(0, import_handler.isMiddleware)(route.handler)) {
769
+ endpoints.push({
770
+ method: route.method.toUpperCase(),
771
+ path: route.path
772
+ });
773
+ }
774
+ });
775
+ return endpoints;
776
+ }, "listEndpoints");
777
+ // Annotate the CommonJS export names for ESM import in node:
778
+ 0 && (module.exports = {
779
+ useApitally
780
+ });
781
+ //# sourceMappingURL=middleware.cjs.map