@xenterprises/fastify-xconfig 1.0.2 → 1.1.1

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 (55) hide show
  1. package/README.md +171 -18
  2. package/dist/utils/randomUUID.d.ts +1 -1
  3. package/dist/xConfig.d.ts +1 -2
  4. package/dist/xConfig.js +2 -7
  5. package/dist/xConfig.js.map +1 -1
  6. package/package.json +24 -43
  7. package/server/app.js +78 -0
  8. package/src/auth/admin.js +181 -0
  9. package/src/auth/portal.js +177 -0
  10. package/src/integrations/cloudinary.js +98 -0
  11. package/src/integrations/geocode.js +43 -0
  12. package/src/integrations/prisma.js +30 -0
  13. package/src/integrations/sendgrid.js +58 -0
  14. package/src/integrations/twilio.js +146 -0
  15. package/src/lifecycle/xFastifyAfter.js +27 -0
  16. package/src/middleware/bugsnag.js +10 -0
  17. package/src/middleware/cors.js +10 -0
  18. package/src/middleware/fancyErrors.js +26 -0
  19. package/src/middleware/multipart.js +6 -0
  20. package/src/middleware/rateLimit.js +6 -0
  21. package/src/middleware/underPressure.js +6 -0
  22. package/src/utils/colorize.js +37 -0
  23. package/src/utils/cookie.js +5 -0
  24. package/src/utils/formatBytes.js +16 -0
  25. package/src/utils/health.js +126 -0
  26. package/src/utils/xEcho.js +12 -0
  27. package/src/utils/xSlugify.js +20 -0
  28. package/src/utils/xUUID.js +14 -0
  29. package/src/xConfig.js +117 -0
  30. package/test/index.js +17 -0
  31. package/tsconfig.json +9 -11
  32. package/xConfigReference.js +1526 -0
  33. package/xConfigWorkingList.js +720 -0
  34. package/.github/workflows/ci.yml +0 -19
  35. package/.taprc +0 -3
  36. package/example.ts +0 -13
  37. package/src/xConfig.ts +0 -20
  38. package/test/index.test-d.ts +0 -13
  39. package/test/index.test.js +0 -14
  40. package/test/xConfig.js +0 -115
  41. /package/{src → ts-reference}/integrations/cloudinary.ts +0 -0
  42. /package/{src → ts-reference}/integrations/prisma.ts +0 -0
  43. /package/{src → ts-reference}/integrations/sendgrid.ts +0 -0
  44. /package/{src → ts-reference}/integrations/stripe.ts +0 -0
  45. /package/{src → ts-reference}/integrations/twilio.ts +0 -0
  46. /package/{src → ts-reference}/middleware/bugsnag.ts +0 -0
  47. /package/{src → ts-reference}/middleware/cors.ts +0 -0
  48. /package/{src → ts-reference}/middleware/errorHandler.ts +0 -0
  49. /package/{src → ts-reference}/middleware/multipart.ts +0 -0
  50. /package/{src → ts-reference}/middleware/rateLimit.ts +0 -0
  51. /package/{src → ts-reference}/middleware/underPressure.ts +0 -0
  52. /package/{src → ts-reference}/utils/colorize.ts +0 -0
  53. /package/{src → ts-reference}/utils/formatBytes.ts +0 -0
  54. /package/{src → ts-reference}/utils/randomUUID.ts +0 -0
  55. /package/{src → ts-reference}/utils/statAsync.ts +0 -0
@@ -0,0 +1,177 @@
1
+ import * as jose from "jose";
2
+ import fetch from "node-fetch";
3
+
4
+ export async function setupAuth(fastify, options) {
5
+ if (options.user?.active !== false) {
6
+ // Get configuration
7
+ const projectId = options.user.portalStackProjectId || process.env.STACK_PROJECT_ID;
8
+ const publishableKey = options.user.publishableKey || process.env.STACK_PUBLISHABLE_CLIENT_KEY;
9
+ const secretKey = options.user.secretKey || process.env.STACK_SECRET_SERVER_KEY;
10
+
11
+ if (!projectId) {
12
+ throw new Error("Stack Auth project ID is required");
13
+ }
14
+
15
+ if (!publishableKey || !secretKey) {
16
+ throw new Error("Stack Auth publishable and secret keys are required");
17
+ }
18
+
19
+ const userExcludedPaths = options.user.excludedPaths || [
20
+ "/portal/auth/login",
21
+ "/portal/auth/logout",
22
+ "/portal/auth/register",
23
+ "/portal/auth/forgot-password",
24
+ "/portal/auth/reset-password"
25
+ ];
26
+
27
+ // Base URL for Stack Auth API
28
+ const stackAuthBaseUrl = `https://api.stack-auth.com/api/v1`;
29
+ const jwksUrl = `${stackAuthBaseUrl}/projects/${projectId}/.well-known/jwks.json`;
30
+
31
+ // Create JWKS for token verification
32
+ const jwks = jose.createRemoteJWKSet(new URL(jwksUrl));
33
+
34
+ // Helper for Stack Auth API headers
35
+ fastify.decorate('getStackAuthHeaders', function (accessType = "server") {
36
+ const headers = {
37
+ 'Content-Type': 'application/json',
38
+ 'Accept': 'application/json',
39
+ 'X-Stack-Access-Type': accessType,
40
+ 'X-Stack-Project-Id': projectId,
41
+ };
42
+
43
+ if (accessType === "client") {
44
+ headers['X-Stack-Publishable-Client-Key'] = publishableKey;
45
+ } else if (accessType === "server") {
46
+ headers['X-Stack-Secret-Server-Key'] = secretKey;
47
+ }
48
+
49
+ return headers;
50
+ });
51
+
52
+ // JWT verification helper
53
+ fastify.decorate('verifyStackJWT', async function (accessToken) {
54
+ try {
55
+ const { payload } = await jose.jwtVerify(accessToken, jwks);
56
+ return payload;
57
+ } catch (error) {
58
+ fastify.log.error(error);
59
+ return null;
60
+ }
61
+ });
62
+
63
+ // API URL helper
64
+ fastify.decorate('getStackAuthApiUrl', function () {
65
+ return stackAuthBaseUrl;
66
+ });
67
+
68
+ // Authentication middleware
69
+ fastify.addHook("onRequest", async (request, reply) => {
70
+ const url = request.url;
71
+
72
+ // Skip excluded paths
73
+ if (userExcludedPaths.some(path => url.startsWith(path))) {
74
+ return;
75
+ }
76
+
77
+ if (url.startsWith("/portal")) {
78
+ try {
79
+ // Get token from header
80
+ const authHeader = request.headers.authorization;
81
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
82
+ return reply.code(401).send({ error: "Access token required" });
83
+ }
84
+
85
+ // Verify token
86
+ const token = authHeader.slice(7);
87
+ const payload = await fastify.verifyStackJWT(token);
88
+
89
+ if (!payload) {
90
+ return reply.code(401).send({ error: "Invalid token" });
91
+ }
92
+
93
+ // Set user info on request
94
+ request.user = payload;
95
+ request.userAuth = { id: payload.sub };
96
+ } catch (err) {
97
+ return reply.code(401).send({ error: "Authentication failed" });
98
+ }
99
+ }
100
+ });
101
+
102
+ // Login endpoint
103
+ fastify.post("/portal/auth/login", async (req, reply) => {
104
+ try {
105
+ const { email, password } = req.body;
106
+
107
+ if (!email || !password) {
108
+ return reply.code(400).send({ error: "Email and password required" });
109
+ }
110
+
111
+ // Call Stack Auth API for password sign-in
112
+ const response = await fetch(
113
+ `${stackAuthBaseUrl}/auth/password/sign-in`,
114
+ {
115
+ method: 'POST',
116
+ headers: fastify.getStackAuthHeaders("server"),
117
+ body: JSON.stringify({ email, password })
118
+ }
119
+ );
120
+
121
+ const data = await response.json().catch(() => ({}));
122
+
123
+ if (!response.ok) {
124
+ return reply.code(response.status || 400).send({
125
+ error: data.message || "Authentication failed"
126
+ });
127
+ }
128
+
129
+ // Check if we have the expected response properties
130
+ if (!data.access_token || !data.refresh_token || !data.user_id) {
131
+ return reply.code(500).send({ error: "Invalid response from authentication service" });
132
+ }
133
+
134
+ // Verify token
135
+ const payload = await fastify.verifyStackJWT(data.access_token);
136
+ if (!payload) {
137
+ return reply.code(401).send({ error: "Invalid token received" });
138
+ }
139
+
140
+ reply.send({
141
+ accessToken: data.access_token,
142
+ refreshToken: data.refresh_token,
143
+ user: payload,
144
+ userId: data.user_id
145
+ });
146
+ } catch (err) {
147
+ fastify.log.error(err);
148
+ reply.code(500).send({ error: "Internal server error" });
149
+ }
150
+ });
151
+
152
+
153
+ // User info endpoint
154
+ fastify.get("/portal/auth/me", async (req, reply) => {
155
+ reply.send(req.user || { authenticated: false });
156
+ });
157
+
158
+ // Token verification endpoint
159
+ fastify.post("/portal/auth/verify", async (req, reply) => {
160
+ const { token } = req.body;
161
+
162
+ if (!token) {
163
+ return reply.code(400).send({ error: "Token required" });
164
+ }
165
+
166
+ const payload = await fastify.verifyStackJWT(token);
167
+
168
+ if (!payload) {
169
+ return reply.code(401).send({ valid: false });
170
+ }
171
+
172
+ reply.send({ valid: true, user: payload });
173
+ });
174
+
175
+ console.info(" ✅ Auth User Enabled");
176
+ }
177
+ }
@@ -0,0 +1,98 @@
1
+ import { v2 as Cloudinary } from "cloudinary";
2
+
3
+ export async function setupCloudinary(fastify, options) {
4
+
5
+ if (options.active !== false) {
6
+ if (
7
+ !options.cloudName ||
8
+ !options.apiKey ||
9
+ !options.apiSecret
10
+ ) {
11
+ throw new Error(
12
+ "Cloudinary cloudName, apiKey, and apiSecret must be provided."
13
+ );
14
+ }
15
+
16
+ Cloudinary.config({
17
+ cloud_name: options.cloudName,
18
+ api_key: options.apiKey,
19
+ api_secret: options.apiSecret,
20
+ },
21
+ );
22
+
23
+ fastify.decorate('cloudinary', {
24
+ upload: async (fileStream, options = {}) => {
25
+ return new Promise((resolve, reject) => {
26
+ if (options.folder) {
27
+ options.folder = options.folder || options.folder;
28
+ }
29
+ options.resource_type = options.resource_type || 'auto';
30
+ options.timestamp = Math.floor(Date.now() / 1000); // Add timestamp to options
31
+ options.use_filename = options.use_filename !== undefined ? options.use_filename : true;
32
+ options.unique_filename = options.unique_filename !== undefined ? options.unique_filename : true;
33
+
34
+ const uploadStream = Cloudinary.uploader.upload_stream(options, (error, result) => {
35
+ if (error) {
36
+ fastify.log.error("Cloudinary upload failed:", error);
37
+ reject(new Error(`Failed to upload to Cloudinary: ${JSON.stringify(error)}`));
38
+ } else {
39
+ resolve(result); // Resolve with the result from Cloudinary
40
+ }
41
+ });
42
+
43
+ fileStream.pipe(uploadStream)
44
+ .on('error', (streamError) => {
45
+ fastify.log.error("Stream error:", streamError);
46
+ reject(new Error(`Stream error during Cloudinary upload: ${streamError.message}`));
47
+ })
48
+ .on('end', () => {
49
+ fastify.log.info("Stream ended successfully.");
50
+ });
51
+ });
52
+ },
53
+
54
+ uploadLarge: async (fileStream, options = {}) => {
55
+ return new Promise((resolve, reject) => {
56
+ if (options.folder) {
57
+ options.folder = options.folder || options.folder;
58
+ }
59
+ options.resource_type = options.resource_type || 'auto';
60
+ options.timestamp = Math.floor(Date.now() / 1000);
61
+ options.use_filename = options.use_filename !== undefined ? options.use_filename : true;
62
+ options.unique_filename = options.unique_filename !== undefined ? options.unique_filename : true;
63
+ options.overwrite = options.overwrite !== undefined ? options.overwrite : false;
64
+
65
+ const uploadStream = Cloudinary.uploader.upload_stream(options, (error, result) => {
66
+ if (error) {
67
+ fastify.log.error("Cloudinary upload failed:", error);
68
+ reject(new Error(`Failed to upload to Cloudinary: ${JSON.stringify(error)}`));
69
+ } else {
70
+ resolve(result);
71
+ }
72
+ });
73
+
74
+ fileStream.pipe(uploadStream)
75
+ .on('error', (streamError) => {
76
+ fastify.log.error("Stream error:", streamError);
77
+ reject(new Error(`Stream error during Cloudinary upload: ${streamError.message}`));
78
+ })
79
+ .on('end', () => {
80
+ fastify.log.info("Stream ended successfully.");
81
+ });
82
+ });
83
+ },
84
+
85
+ delete: async (publicId) => {
86
+ try {
87
+ const response = await Cloudinary.uploader.destroy(publicId);
88
+ return response;
89
+ } catch (error) {
90
+ fastify.log.error("Cloudinary delete failed:", error);
91
+ throw new Error("Failed to delete from Cloudinary.");
92
+ }
93
+ }
94
+ });
95
+
96
+ console.info(" ✅ Cloudinary Enabled");
97
+ }
98
+ }
@@ -0,0 +1,43 @@
1
+ export async function setupGeocode(fastify, options) {
2
+ if (options.active !== false) {
3
+ if (!options.apiKey) {
4
+ throw new Error("Geocode API key must be provided.");
5
+ }
6
+ const geocodioEndpoint = 'https://api.geocod.io/v1.7/geocode';
7
+ const geocodioApiKey = options.apiKey;
8
+
9
+ fastify.decorate('geocode', {
10
+ // Method to get lat/long and county from a zip code
11
+ async getLatLongByZip(zipCode) {
12
+ try {
13
+ const url = `${geocodioEndpoint}?q=${zipCode}&fields=cd,stateleg&api_key=${geocodioApiKey}`;
14
+ const response = await fetch(url);
15
+ const result = await response.json();
16
+
17
+ if (result.results && result.results.length > 0) {
18
+ const location = result.results[0].location;
19
+ const addressComponents = result.results[0].address_components;
20
+
21
+ return {
22
+ zip: zipCode,
23
+ lat: location.lat,
24
+ lng: location.lng,
25
+ city: addressComponents.city,
26
+ county: addressComponents.county,
27
+ country: addressComponents.country,
28
+ state: addressComponents.state,
29
+ addressComponents: addressComponents
30
+ };
31
+ } else {
32
+ throw new Error('No results found for the provided zip code.');
33
+ }
34
+ } catch (error) {
35
+ fastify.log.error('Failed to fetch geolocation data:', error);
36
+ throw new Error('Failed to fetch geolocation data.');
37
+ }
38
+ }
39
+ });
40
+
41
+ console.info(' ✅ Geocodio Enabled');
42
+ }
43
+ }
@@ -0,0 +1,30 @@
1
+
2
+ import { PrismaClient } from "@prisma/client";
3
+ export async function setupPrisma(fastify, options) {
4
+ if (options.active !== false) {
5
+ delete options.active;
6
+ const prisma = new PrismaClient(options);
7
+
8
+ // Connect to the database
9
+ await prisma.$connect();
10
+
11
+ // Decorate Fastify instance with Prisma Client
12
+ fastify.decorate("prisma", prisma);
13
+
14
+ // Disconnect Prisma Client when Fastify closes
15
+ fastify.addHook("onClose", async () => {
16
+ await fastify.prisma.$disconnect();
17
+ });
18
+
19
+ console.info(" ✅ Prisma Enabled");
20
+ }
21
+ /*
22
+ ===== Ensure Proper Cleanup on Server Shutdown =====
23
+ */
24
+ fastify.addHook("onClose", async () => {
25
+ if (fastify.prisma) {
26
+ await fastify.prisma.$disconnect();
27
+ }
28
+ // Add additional cleanup for other services if necessary
29
+ });
30
+ }
@@ -0,0 +1,58 @@
1
+ import Sendgrid from '@sendgrid/mail';
2
+ import sgClient from '@sendgrid/client';
3
+ export async function setupSendgrid(fastify, options) {
4
+ if (options.active !== false) {
5
+ if (!options.apiKey)
6
+ throw new Error("SendGrid API key must be provided.");
7
+
8
+ Sendgrid.setApiKey(options.apiKey);
9
+ sgClient.setApiKey(options.apiKeyEmailValidation);
10
+ // Decorator to group SendGrid-related methods under fastify.sendGrid
11
+ fastify.decorate('sendgrid', {
12
+ sendEmail: async (to, subject, templateId, dynamicTemplateData) => {
13
+ try {
14
+
15
+ const msg = {
16
+ to: to,
17
+ from: options.fromEmail,
18
+ subject: subject,
19
+ templateId: templateId,
20
+ dynamicTemplateData: { ...dynamicTemplateData, subject: subject },
21
+ };
22
+ await Sendgrid.send(msg);
23
+ return true;
24
+ } catch (error) {
25
+ fastify.log.error("SendGrid send email failed:", error);
26
+ throw new Error("Failed to send email.");
27
+ }
28
+ },
29
+ validateEmail: async (email) => {
30
+ const data = {
31
+ email: email,
32
+ // source: 'signup',
33
+ };
34
+
35
+ const request = {
36
+ url: `/v3/validations/email`,
37
+ method: 'POST',
38
+ body: data,
39
+ };
40
+
41
+ try {
42
+ const [response, body] = await sgClient.request(request);
43
+ console.log(body)
44
+ if (response.statusCode === 200) {
45
+ return body?.result; // Return the validation result
46
+ } else {
47
+ throw new Error(body.errors ? body.errors.map(err => err.message).join(', ') : 'Failed to validate email.');
48
+ }
49
+ } catch (error) {
50
+ fastify.log.error('SendGrid email validation failed:', error);
51
+ throw new Error('Failed to validate email.');
52
+ }
53
+ }
54
+ });
55
+
56
+ console.info(" ✅ SendGrid Enabled");
57
+ }
58
+ }
@@ -0,0 +1,146 @@
1
+ import Twilio from "twilio";
2
+ export async function setupTwilio(fastify, options) {
3
+ if (options.active !== false) {
4
+ // Return if missing Twilio credentials
5
+ if (
6
+ !options.accountSid ||
7
+ !options.authToken ||
8
+ !options.phoneNumber
9
+ )
10
+ throw new Error(
11
+ "Twilio accountSid, authToken, and phoneNumber must be provided."
12
+ );
13
+
14
+ const twilioClient = Twilio(
15
+ options.accountSid,
16
+ options.authToken
17
+ );
18
+
19
+ // Decorator to group Twilio-related methods under fastify.twilio
20
+ fastify.decorate('twilio', {
21
+ sendSMS: async (to, body) => {
22
+ try {
23
+ const message = await twilioClient.messages.create({
24
+ body,
25
+ to,
26
+ from: options.phoneNumber, // Use the Twilio phone number from options
27
+ });
28
+ return message;
29
+ } catch (error) {
30
+ fastify.log.error("Twilio send SMS failed:", error);
31
+ throw new Error("Failed to send SMS.");
32
+ }
33
+ },
34
+ sendMMS: async (to, body, mediaUrl) => {
35
+ try {
36
+ const message = await twilioClient.messages.create({
37
+ body,
38
+ to,
39
+ from: options.phoneNumber,
40
+ mediaUrl: [mediaUrl], // Array of media URLs
41
+ });
42
+ return message;
43
+ } catch (error) {
44
+ fastify.log.error("Twilio send MMS failed:", error);
45
+ throw new Error("Failed to send MMS.");
46
+ }
47
+ },
48
+ makeVoiceCall: async (to, twimlUrl) => {
49
+ try {
50
+ const call = await twilioClient.calls.create({
51
+ to,
52
+ from: options.phoneNumber,
53
+ url: twimlUrl, // URL that provides TwiML instructions
54
+ });
55
+ return call;
56
+ } catch (error) {
57
+ fastify.log.error("Twilio make voice call failed:", error);
58
+ throw new Error("Failed to make voice call.");
59
+ }
60
+ },
61
+ sendVerificationCode: async (to, channel = 'sms') => {
62
+ try {
63
+ const verification = await twilioClient.verify.services(options.verifyServiceSid)
64
+ .verifications
65
+ .create({ to, channel }); // channel can be 'sms' or 'call'
66
+ return verification;
67
+ } catch (error) {
68
+ fastify.log.error("Twilio send verification code failed:", error);
69
+ throw new Error("Failed to send verification code.");
70
+ }
71
+ },
72
+ verifyCode: async (to, code) => {
73
+ try {
74
+ const verificationCheck = await twilioClient.verify.services(options.verifyServiceSid)
75
+ .verificationChecks
76
+ .create({ to, code });
77
+ return verificationCheck;
78
+ } catch (error) {
79
+ fastify.log.error("Twilio verify code failed:", error);
80
+ throw new Error("Failed to verify code.");
81
+ }
82
+ },
83
+ fetchSMSHistory: async (fromDate, toDate) => {
84
+ try {
85
+ const messages = await twilioClient.messages.list({
86
+ dateSentAfter: fromDate,
87
+ dateSentBefore: toDate,
88
+ limit: 100,
89
+ });
90
+ return messages;
91
+ } catch (error) {
92
+ fastify.log.error("Twilio fetch SMS history failed:", error);
93
+ throw new Error("Failed to fetch SMS history.");
94
+ }
95
+ },
96
+ handleIncomingSMS: (req, reply) => {
97
+ const { Body, From } = req.body;
98
+
99
+ // Process incoming message
100
+ console.log(`Message received from ${From}: ${Body}`);
101
+
102
+ reply.type('text/xml');
103
+ reply.send('<Response><Message>Thanks for your message!</Message></Response>');
104
+ },
105
+ checkCallStatus: async (callSid) => {
106
+ try {
107
+ const call = await twilioClient.calls(callSid).fetch();
108
+ return call;
109
+ } catch (error) {
110
+ fastify.log.error("Twilio check call status failed:", error);
111
+ throw new Error("Failed to check call status.");
112
+ }
113
+ },
114
+ validatePhoneNumber: async (phoneNumber) => {
115
+ try {
116
+ // Perform phone number validation with Twilio
117
+ const validation = await twilioClient.lookups.v2
118
+ .phoneNumbers(phoneNumber)
119
+ .fetch();
120
+
121
+ // Check if the phone number is valid (Twilio may return "valid": true/false)
122
+ const isValid = validation.valid !== undefined ? validation.valid : true;
123
+
124
+ // Return the required structure
125
+ return {
126
+ sms: phoneNumber, // The phone number
127
+ smsValidate: validation, // The full validation payload from Twilio
128
+ isSmsValidated: isValid // Set true/false based on the validation
129
+ };
130
+ } catch (error) {
131
+ fastify.log.error("Twilio phone number validation failed:", error);
132
+
133
+ // Return the structure with failed validation
134
+ return {
135
+ sms: phoneNumber, // The phone number
136
+ smsValidate: {}, // Empty object as validation failed
137
+ isSmsValidated: false // Validation failed
138
+ };
139
+ }
140
+ }
141
+ });
142
+
143
+ console.info(" ✅ Twilio Enabled");
144
+ }
145
+
146
+ }
@@ -0,0 +1,27 @@
1
+ // src/lifecycle/xFastifyAfter.js
2
+ import { printRoutes } from "../utils/colorize.js";
3
+ export async function xFastifyAfter(fastify, options) {
4
+
5
+ /*
6
+ ===== LIST ROUTES AFTER ALL PLUGINS =====
7
+ Use the after() method to ensure this runs after all plugins are registered.
8
+ */
9
+ fastify.after(() => {
10
+ if (options.professional !== true) {
11
+ console.info(" ✅ Listing Routes:");
12
+ fastify.ready(() => {
13
+ printRoutes(options.routes, options.colors !== false);
14
+ // Add rocket emoji
15
+ console.info(
16
+ `🚀 Server is ready on port ${process.env.PORT || 3000}\n\n`
17
+ );
18
+ // Add goodbye emoji for server shutting down
19
+ fastify.addHook("onClose", () =>
20
+ console.info("Server shutting down... Goodbye 👋")
21
+ );
22
+ });
23
+ }
24
+ });
25
+
26
+
27
+ }
@@ -0,0 +1,10 @@
1
+ export async function setupBugsnag(fastify, options) {
2
+ if (options.active !== false) {
3
+ if (!options.apiKey)
4
+ throw new Error("Bugsnag API key must be provided.");
5
+ fastify.register(import("fastify-bugsnag"), {
6
+ apiKey: options.apiKey,
7
+ });
8
+ console.info(" ✅ BugSnag Enabled");
9
+ }
10
+ }
@@ -0,0 +1,10 @@
1
+ export async function setupCors(fastify, options) {
2
+ if (options.active !== false) {
3
+ await fastify.register(await import("@fastify/cors"), {
4
+ origin: options.origin || ["https://getx.io", "http://localhost:3000"],
5
+ credentials: options.credentials !== undefined ? options.credentials : true,
6
+ methods: options.methods || ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
7
+ });
8
+ console.info(" ✅ CORS Enabled");
9
+ }
10
+ }
@@ -0,0 +1,26 @@
1
+ export async function setupFancyErrors(fastify, options) {
2
+
3
+ /*
4
+ ===== EXTEND ERRORS =====
5
+ */
6
+ if (options.fancyErrors !== false) {
7
+ fastify.setErrorHandler((error, request, reply) => {
8
+ const statusCode = error.statusCode || 500;
9
+ const response = {
10
+ status: statusCode,
11
+ message: error.message || "Internal Server Error",
12
+ // Only show stack in development mode
13
+ stack: process.env.NODE_ENV === "development" ? error.stack : undefined,
14
+ };
15
+
16
+ // Optional Bugsnag error reporting
17
+ if (fastify.bugsnag) {
18
+ fastify.bugsnag.notify(error);
19
+ }
20
+
21
+ fastify.log.error(response);
22
+ reply.status(statusCode).send(response);
23
+ });
24
+ console.info(" ✅ Fancy Errors Enabled");
25
+ }
26
+ }
@@ -0,0 +1,6 @@
1
+ export async function setupMultipart(fastify, options) {
2
+ if (options.active !== false) {
3
+ fastify.register(import("@fastify/multipart"), options);
4
+ console.info(" ✅ Multipart Enabled");
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ export async function setupRateLimit(fastify, options) {
2
+ if (options.active !== false) {
3
+ fastify.register(import("@fastify/rate-limit"), options);
4
+ console.info(" ✅ Rate Limiting Enabled");
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ export async function setupUnderPressure(fastify, options) {
2
+ if (options.active !== false) {
3
+ fastify.register(import("@fastify/under-pressure"), options);
4
+ console.info(" ✅ Under Pressure Enabled");
5
+ }
6
+ }