apitally
Version:
Simple API monitoring & analytics for REST APIs built with Express, Fastify, NestJS, AdonisJS, Hono, H3, Elysia, Hapi, and Koa.
307 lines • 11.2 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var plugin_exports = {};
__export(plugin_exports, {
apitallyPlugin: () => apitallyPlugin,
default: () => plugin_default,
setConsumer: () => setConsumer
});
module.exports = __toCommonJS(plugin_exports);
var import_fastify_plugin = __toESM(require("fastify-plugin"), 1);
var import_node_async_hooks = require("node:async_hooks");
var import_client = require("../common/client.js");
var import_consumerRegistry = require("../common/consumerRegistry.js");
var import_headers = require("../common/headers.js");
var import_packageVersions = require("../common/packageVersions.js");
var import_requestLogger = require("../common/requestLogger.js");
var import_loggers = require("../loggers/index.js");
const LOGS_SYMBOL = Symbol("apitally.logs");
const ASYNC_RESOURCE_SYMBOL = Symbol("apitally.logsContextAsyncResource");
const apitallyPlugin = /* @__PURE__ */ __name(async (fastify, config) => {
const client = new import_client.ApitallyClient(config);
const routes = [];
const logsContext = new import_node_async_hooks.AsyncLocalStorage();
if (client.requestLogger.config.captureLogs) {
(0, import_loggers.patchConsole)(logsContext);
(0, import_loggers.patchWinston)(logsContext);
(0, import_loggers.patchPinoLogger)(fastify.log, logsContext);
(0, import_loggers.patchNestLogger)(logsContext);
}
fastify.decorateRequest("apitallyConsumer", null);
fastify.decorateRequest("consumerIdentifier", null);
fastify.decorateReply("payload", null);
fastify.addHook("onRoute", (routeOptions) => {
const methods = Array.isArray(routeOptions.method) ? routeOptions.method : [
routeOptions.method
];
methods.forEach((method) => {
if (![
"HEAD",
"OPTIONS"
].includes(method.toUpperCase())) {
routes.push({
method: method.toUpperCase(),
path: routeOptions.url
});
}
});
});
fastify.addHook("onReady", () => {
client.setStartupData(getAppInfo(routes, config.appVersion));
client.startSync();
});
fastify.addHook("onClose", async () => {
await client.handleShutdown();
});
fastify.addHook("onRequest", (request, reply, done) => {
if (client.isEnabled()) {
const logs = [];
request[LOGS_SYMBOL] = logs;
logsContext.run(logs, () => {
const asyncResource = new import_node_async_hooks.AsyncResource("ApitallyLogsContext");
request[ASYNC_RESOURCE_SYMBOL] = asyncResource;
asyncResource.runInAsyncScope(done, request.raw);
});
} else {
done();
}
});
fastify.addHook("preValidation", (request, reply, done) => {
if (client.isEnabled() && request[ASYNC_RESOURCE_SYMBOL]) {
const asyncResource = request[ASYNC_RESOURCE_SYMBOL];
asyncResource.runInAsyncScope(done, request.raw);
} else {
done();
}
});
fastify.addHook("onSend", (request, reply, payload, done) => {
const contentType = reply.getHeader("content-type");
if (client.requestLogger.isSupportedContentType(contentType)) {
reply.payload = payload;
}
done();
});
fastify.addHook("onError", (request, reply, error, done) => {
if (!error.statusCode || error.statusCode === 500) {
reply.serverError = error;
}
done();
});
fastify.addHook("onResponse", (request, reply, done) => {
var _a;
if (client.isEnabled() && request.method.toUpperCase() !== "OPTIONS") {
const consumer = getConsumer(request);
const path = "routeOptions" in request ? request.routeOptions.url : request.routerPath;
const requestSize = (0, import_headers.parseContentLength)(request.headers["content-length"]);
const responseSize = (0, import_headers.parseContentLength)(reply.getHeader("content-length"));
const responseTime = getResponseTime(reply);
client.consumerRegistry.addOrUpdateConsumer(consumer);
client.requestCounter.addRequest({
consumer: consumer == null ? void 0 : consumer.identifier,
method: request.method,
path,
statusCode: reply.statusCode,
responseTime,
requestSize,
responseSize
});
if ((reply.statusCode === 400 || reply.statusCode === 422) && reply.payload) {
try {
const parsedPayload = JSON.parse(reply.payload);
const validationErrors = [];
if ((!parsedPayload.code || parsedPayload.code === "FST_ERR_VALIDATION") && typeof parsedPayload.message === "string") {
validationErrors.push(...extractAjvErrors(parsedPayload.message));
} else if (Array.isArray(parsedPayload.message)) {
validationErrors.push(...extractNestValidationErrors(parsedPayload.message));
}
validationErrors.forEach((error) => {
client.validationErrorCounter.addValidationError({
consumer: consumer == null ? void 0 : consumer.identifier,
method: request.method,
path,
...error
});
});
} catch (error) {
}
}
if (reply.statusCode === 500 && reply.serverError) {
client.serverErrorCounter.addServerError({
consumer: consumer == null ? void 0 : consumer.identifier,
method: request.method,
path,
type: reply.serverError.name,
msg: reply.serverError.message,
traceback: reply.serverError.stack || ""
});
}
if (client.requestLogger.enabled) {
const logs = request[LOGS_SYMBOL];
client.requestLogger.logRequest({
timestamp: Date.now() / 1e3,
method: request.method,
path,
url: `${request.protocol}://${request.host ?? request.hostname}${request.originalUrl ?? request.url}`,
headers: (0, import_requestLogger.convertHeaders)(request.headers),
size: requestSize,
consumer: consumer == null ? void 0 : consumer.identifier,
body: (0, import_requestLogger.convertBody)(request.body, request.headers["content-type"])
}, {
statusCode: reply.statusCode,
responseTime: responseTime / 1e3,
headers: (0, import_requestLogger.convertHeaders)(reply.getHeaders()),
size: responseSize,
body: (0, import_requestLogger.convertBody)(reply.payload, (_a = reply.getHeader("content-type")) == null ? void 0 : _a.toString())
}, reply.serverError, logs);
}
}
done();
});
}, "apitallyPlugin");
function getAppInfo(routes, appVersion) {
const versions = [
[
"nodejs",
process.version.replace(/^v/, "")
]
];
const fastifyVersion = (0, import_packageVersions.getPackageVersion)("fastify");
const pinoVersion = (0, import_packageVersions.getPackageVersion)("pino");
const nestjsVersion = (0, import_packageVersions.getPackageVersion)("@nestjs/core");
const apitallyVersion = (0, import_packageVersions.getPackageVersion)("../..");
if (fastifyVersion) {
versions.push([
"fastify",
fastifyVersion
]);
}
if (pinoVersion) {
versions.push([
"pino",
pinoVersion
]);
}
if (nestjsVersion) {
versions.push([
"nestjs",
nestjsVersion
]);
}
if (apitallyVersion) {
versions.push([
"apitally",
apitallyVersion
]);
}
if (appVersion) {
versions.push([
"app",
appVersion
]);
}
return {
paths: routes,
versions: Object.fromEntries(versions),
client: "js:fastify"
};
}
__name(getAppInfo, "getAppInfo");
function setConsumer(request, consumer) {
request.apitallyConsumer = consumer || void 0;
}
__name(setConsumer, "setConsumer");
function getConsumer(request) {
if (request.apitallyConsumer) {
return (0, import_consumerRegistry.consumerFromStringOrObject)(request.apitallyConsumer);
} else if (request.consumerIdentifier) {
process.emitWarning("The consumerIdentifier property on the request object is deprecated. Use apitallyConsumer instead.", "DeprecationWarning");
return (0, import_consumerRegistry.consumerFromStringOrObject)(request.consumerIdentifier);
}
return null;
}
__name(getConsumer, "getConsumer");
function getResponseTime(reply) {
if (reply.elapsedTime !== void 0) {
return reply.elapsedTime;
} else if (reply.getResponseTime !== void 0) {
return reply.getResponseTime();
}
return 0;
}
__name(getResponseTime, "getResponseTime");
function extractAjvErrors(message) {
try {
const regex = /(?<=^|, )((?:headers|params|query|querystring|body)[/.][^ ]+)(?= )/g;
const matches = [];
let match;
while ((match = regex.exec(message)) !== null) {
matches.push({
match: match[0],
index: match.index
});
}
return matches.map((m, i) => {
const endIndex = i + 1 < matches.length ? matches[i + 1].index - 2 : message.length;
const matchSplit = m.match.split(/[/.]/);
if (matchSplit[0] === "querystring") {
matchSplit[0] = "query";
}
return {
loc: matchSplit.join("."),
msg: message.substring(m.index, endIndex),
type: ""
};
});
} catch (error) {
return [];
}
}
__name(extractAjvErrors, "extractAjvErrors");
function extractNestValidationErrors(message) {
try {
return message.filter((msg) => typeof msg === "string").map((msg) => ({
loc: "",
msg,
type: ""
}));
} catch (error) {
return [];
}
}
__name(extractNestValidationErrors, "extractNestValidationErrors");
var plugin_default = (0, import_fastify_plugin.default)(apitallyPlugin, {
name: "apitally"
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
apitallyPlugin,
setConsumer
});
//# sourceMappingURL=plugin.cjs.map