Merge pull request #210 from C-h-a-r/release

Self Hosted Dashboard
This commit is contained in:
1tzEmerald authored and GitHub committed 2026-06-02 17:34:40 +01:00
commit 014f263bf1
88 files changed
+9561 -857

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
Configs/supportbot.yml filter=supportbot-token
Configs/api.yml filter=api-secrets
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
cd "$(git rev-parse --show-toplevel)" || exit 1
node scripts/verify-supportbot-token.js pre-commit
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
cd "$(git rev-parse --show-toplevel)" || exit 1
node scripts/verify-supportbot-token.js pre-push
+10
View File
@@ -0,0 +1,10 @@
node_modules
# Dashboard UI source at repo root only (do not ignore public/dashboard/)
/dashboard/
# Local git hooks + secret-stripping scripts (run npm run git:setup)
scripts/
# Local secrets — use *.example as templates
Configs/api.yml
+1209 -91
View File
File diff suppressed because it is too large. Load diff
+11
View File
@@ -0,0 +1,11 @@
# SupportBot | Emerald Services
# Discord Stats addon | Created by Xiled Emerald
Guild_ID: "GUILD_ID_HERE"
StatsCategory: "Server Statistics"
UserCount_Name: "Total Members:"
ChannelCount_Name: "Total Channels:"
RoleCount_Name: "Total Roles:"
+1 -1
View File
@@ -2,7 +2,7 @@ const Discord = require("discord.js");
const fs = require("fs");
const yaml = require("js-yaml");
const { Command } = require('../Structures/Addon.js'); // Adjust the path as needed
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const supportbot = require("../Structures/ConfigStore").supportbot;
module.exports = new Command({
name: "addon",
+139
View File
@@ -0,0 +1,139 @@
// SupportBot | Emerald Services
// Discord Stats addon | Created by Xiled Emerald
const fs = require("fs");
const Discord = require("discord.js");
const yaml = require("js-yaml");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
// If you need to read something from the main config!
const cmdconfig = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
// This is for your Addon Configuration
const config = yaml.load(fs.readFileSync('./Addons/Configs/discord-stats.yml', 'utf8'));
const { Command, Event } = require("../Structures/Addon");
module.exports.commands = [
new Command({
name: "stats",
description: "Create the discord statistic channels",
options: [],
permissions: ["SEND_MESSAGES"],
async run(interaction) {
const guild = interaction.guild;
const statsCategory = guild.channels.cache.find(
(category) =>
category.name === config.StatsCategory ||
category.id === config.StatsCategory
);
if (!statsCategory) {
const errorEmbed = new Discord.MessageEmbed()
.setTitle("Invalid Category")
.setDescription(
`${supportbot.InvalidChannel}\n\n**Category Required:** \`${config.StatsCategory}\``
)
.setColor(supportbot.ErrorColour);
interaction.reply({
embeds: [errorEmbed],
ephemeral: true,
});
return;
}
const guildName = guild.name;
const userCount = guild.memberCount;
const roleCount = guild.roles.cache.size;
const channelCount = guild.channels.cache.size;
try {
const guildNameChannel = await guild.channels.create(guildName, {
type: "GUILD_VOICE",
});
const userCountChannel = await guild.channels.create(
`${config.UserCount_Name} ${userCount}`,
{
type: "GUILD_VOICE",
}
);
const channelCountChannel = await guild.channels.create(
`${config.ChannelCount_Name} ${channelCount}`,
{
type: "GUILD_VOICE",
}
);
const roleCountChannel = await guild.channels.create(
`${config.RoleCount_Name} ${roleCount}`,
{
type: "GUILD_VOICE",
}
);
guildNameChannel.permissionOverwrites.edit(guild.id, {
VIEW_CHANNEL: true,
CONNECT: false,
});
userCountChannel.permissionOverwrites.edit(guild.id, {
VIEW_CHANNEL: true,
CONNECT: false,
});
channelCountChannel.permissionOverwrites.edit(guild.id, {
VIEW_CHANNEL: true,
CONNECT: false,
});
roleCountChannel.permissionOverwrites.edit(guild.id, {
VIEW_CHANNEL: true,
CONNECT: false,
});
userCountChannel.setParent(statsCategory.id);
roleCountChannel.setParent(statsCategory.id);
guildNameChannel.setParent(statsCategory.id);
channelCountChannel.setParent(statsCategory.id);
const successEmbed = new Discord.MessageEmbed()
.setDescription(":white_check_mark: **[DISCORD STATS]** Channels created successfully!")
.setColor(supportbot.EmbedColour);
interaction.reply({
embeds: [successEmbed],
ephemeral: true,
});
setInterval(() => {
userCountChannel.setName(
`${config.UserCount_Name} ${userCount}`
);
channelCountChannel.setName(
`${config.ChannelCount_Name} ${channelCount}`
);
roleCountChannel.setName(
`${config.RoleCount_Name} ${roleCount}`
);
}, 30000);
} catch (error) {
console.error(error);
const errorEmbed = new Discord.MessageEmbed()
.setTitle("Error")
.setDescription("An error occurred while creating the stats channels.")
.setColor(supportbot.ErrorColour);
interaction.reply({
embeds: [errorEmbed],
ephemeral: true,
});
}
},
}),
];
+3 -3
View File
@@ -5,9 +5,9 @@ const fs = require("fs");
const { ApplicationCommandOptionType, ApplicationCommandType, EmbedBuilder, MessageFlags } = require("discord.js");
const yaml = require("js-yaml");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const supportbotai = yaml.load(fs.readFileSync("./Configs/supportbot-ai.yml", "utf8"));
const supportbot = require("../../Structures/ConfigStore").supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const supportbotai = require("../../Structures/ConfigStore").supportbotAi;
const Command = require("../../Structures/Command.js");
const AIDatabase = require("../../Structures/AIDatabase.js");
+3 -3
View File
@@ -2,8 +2,8 @@ const fs = require("fs");
const Discord = require("discord.js");
const yaml = require("js-yaml");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const supportbot = require("../../Structures/ConfigStore").supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const Command = require("../../Structures/Command.js");
@@ -54,7 +54,7 @@ module.exports = new Command({
iconURL: interaction.user.displayAvatarURL(),
});
interaction.reply({
await interaction.reply({
flags: Discord.MessageFlags.Ephemeral,
embeds: [HelpEmbed1],
});
+3 -14
View File
@@ -1,22 +1,11 @@
// SupportBot | Emerald Services
// Info Command
const fs = require("fs");
const Discord = require("discord.js");
const yaml = require("js-yaml");
const supportbot = yaml.load(
fs.readFileSync("./Configs/supportbot.yml", "utf8")
);
const cmdconfig = yaml.load(
fs.readFileSync("./Configs/commands.yml", "utf8")
);
const msgconfig = yaml.load(
fs.readFileSync("./Configs/messages.yml", "utf8")
);
const supportbot = require("../../Structures/ConfigStore").supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const msgconfig = require("../../Structures/ConfigStore").messages;
const Command = require("../../Structures/Command.js");
+4 -8
View File
@@ -5,10 +5,8 @@ const fs = require("fs");
const Discord = require("discord.js");
const yaml = require("js-yaml");
const supportbot = yaml.load(
fs.readFileSync("./Configs/supportbot.yml", "utf8")
);
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const supportbot = require("../../Structures/ConfigStore").supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const Command = require("../../Structures/Command.js");
@@ -19,15 +17,13 @@ module.exports = new Command({
permissions: cmdconfig.Ping.Permission,
async run(interaction) {
let disableCommand = true;
const PingEmbed = new Discord.EmbedBuilder()
.setDescription(
`:ping_pong: **Ping:** \`${interaction.client.ws.ping} ms\``
`:ping_pong: **Ping:** \`${interaction.client.ws.ping} ms\``,
)
.setColor(supportbot.Embed.Colours.General);
interaction.reply({
await interaction.reply({
embeds: [PingEmbed],
});
},
+3 -3
View File
@@ -20,9 +20,9 @@ const yaml = require("js-yaml");
const db = require("../../Structures/Database.js");
const Command = require("../../Structures/Command.js");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const supportbot = require("../../Structures/ConfigStore").supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const msgconfig = require("../../Structures/ConfigStore").messages;
const clockedInUsers = new Set();
+3 -3
View File
@@ -7,9 +7,9 @@ const yaml = require("js-yaml");
const { translate } = require("@vitalets/google-translate-api");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const supportbot = require("../../Structures/ConfigStore").supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const msgconfig = require("../../Structures/ConfigStore").messages;
const Command = require("../../Structures/Command.js");
+3 -3
View File
@@ -3,9 +3,9 @@ const Discord = require("discord.js");
const yaml = require("js-yaml");
const path = require("path");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const supportbot = require("../../Structures/ConfigStore").supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const msgconfig = require("../../Structures/ConfigStore").messages;
const Command = require("../../Structures/Command.js");
const DB = require("../../Structures/Database.js");
+3 -3
View File
@@ -2,9 +2,9 @@ const Discord = require("discord.js");
const fs = require("fs");
const yaml = require("js-yaml");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const supportbot = require("../../Structures/ConfigStore").supportbot;
const msgconfig = require("../../Structures/ConfigStore").messages;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const SuggestionDB = require("../../Structures/Database.js");
const Command = require("../../Structures/Command.js");
+3 -3
View File
@@ -8,9 +8,9 @@ const db = require("../../Structures/Database.js");
const TicketManager = require("../../Structures/TicketManager.js");
const Command = require("../../Structures/Command.js");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const supportbot = require("../../Structures/ConfigStore").supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const msgconfig = require("../../Structures/ConfigStore").messages;
function getDepartmentConfig(departmentKey) {
return supportbot.Ticket?.DepartmentSystem?.Departments?.[departmentKey] || null;
+3 -3
View File
@@ -12,9 +12,9 @@ const {
TextInputStyle,
} = require("discord.js");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const supportbot = require("../../Structures/ConfigStore").supportbot;
const msgconfig = require("../../Structures/ConfigStore").messages;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const TicketManager = require("../../Structures/TicketManager.js");
const Command = require("../../Structures/Command.js");
+4 -8
View File
@@ -19,14 +19,10 @@ const yaml = require("js-yaml");
const db = require("../../Structures/Database.js");
const panelconfig = yaml.load(
fs.readFileSync("./Configs/ticket-panel.yml", "utf8"),
);
const supportbot = yaml.load(
fs.readFileSync("./Configs/supportbot.yml", "utf8"),
);
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const panelconfig = require("../../Structures/ConfigStore").ticketPanel;
const supportbot = require("../../Structures/ConfigStore").supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const msgconfig = require("../../Structures/ConfigStore").messages;
const Command = require("../../Structures/Command.js");
const TicketNumberID = require("../../Structures/TicketID.js");
+3 -3
View File
@@ -19,9 +19,9 @@ const {
} = require("discord.js");
const yaml = require("js-yaml");
const panelconfig = yaml.load(fs.readFileSync("./Configs/ticket-panel.yml", "utf8"));
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const panelconfig = require("../../Structures/ConfigStore").ticketPanel;
const supportbot = require("../../Structures/ConfigStore").supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const Command = require("../../Structures/Command.js");
const db = require("../../Structures/Database.js");
+3 -3
View File
@@ -16,9 +16,9 @@ const Command = require('../../Structures/Command.js');
const fs = require('fs');
const yaml = require('js-yaml');
const supportbot = yaml.load(fs.readFileSync('./Configs/supportbot.yml', 'utf8'));
const cmdconfig = yaml.load(fs.readFileSync('./Configs/commands.yml', 'utf8'));
const msgconfig = yaml.load(fs.readFileSync('./Configs/messages.yml', 'utf8'));
const supportbot = require('../../Structures/ConfigStore').supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const msgconfig = require("../../Structures/ConfigStore").messages;
function parseColor(color) {
if (!color) return 0x5865F2;
+3 -3
View File
@@ -1,9 +1,9 @@
const fs = require("fs");
const { ApplicationCommandOptionType, ApplicationCommandType, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ComponentType, MessageFlags } = require("discord.js");
const yaml = require("js-yaml");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const supportbot = require("../../Structures/ConfigStore").supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
const msgconfig = require("../../Structures/ConfigStore").messages;
const Command = require("../../Structures/Command.js");
+2 -2
View File
@@ -4,8 +4,8 @@ const fs = require("fs");
const yaml = require("js-yaml");
const db = require("../../Structures/Database.js");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const supportbot = require("../../Structures/ConfigStore").supportbot;
const cmdconfig = require("../../Structures/ConfigStore").commands;
async function loadSettings() {
return new Promise((resolve, reject) => {
+23 -2
View File
@@ -1,8 +1,29 @@
# -------------------------------
# API Server Configuration
# -------------------------------
# Copy to api.yml and fill in your values (api.yml is not committed with real secrets).
API:
Enabled: true
Port: 3000 # PORT NUMBER FOR YOUR BOT
SecretKey: "PUT_RANDOM_STRING_HERE" # DO NOT SHARE THIS KEY WITH ANYONE
Port: 3000
SecretKey: "CHANGE_ME"
# Set to 1 when the dashboard is behind nginx, Cloudflare, Pterodactyl proxy, etc.
# so http/https is detected from X-Forwarded-Proto.
TrustProxy: false
OAuth:
Enabled: true
ClientId: "DISCORD_CLIENT_ID"
ClientSecret: "DISCORD_CLIENT_SECRET"
# Canonical callback URL (host + path). Protocol (http/https) can follow the
# browser when UseRequestOrigin is true (default).
RedirectUri: "http://localhost:3000/api/auth/discord/callback"
# Optional: register extra callback URLs in Discord and list them here.
# RedirectUris:
# - "https://bot.example.com/api/auth/discord/callback"
# UseRequestOrigin: true
# CookieSecure: false
OwnerUserIds:
- "YOUR_DISCORD_USER_ID"
AllowedUserIds: []
+30
View File
@@ -0,0 +1,30 @@
# -------------------------------
# API Server Configuration
# -------------------------------
# Copy to api.yml and fill in your values (api.yml is not committed with real secrets).
API:
Enabled: true
Port: 3000
SecretKey: "CHANGE_ME"
# Set to 1 when the dashboard is behind nginx, Cloudflare, Pterodactyl proxy, etc.
# so http/https is detected from X-Forwarded-Proto.
TrustProxy: false
OAuth:
Enabled: true
ClientId: "DISCORD_CLIENT_ID"
ClientSecret: "DISCORD_CLIENT_SECRET"
# Canonical callback URL (host + path). Protocol (http/https) can follow the
# browser when UseRequestOrigin is true (default).
RedirectUri: "http://localhost:3000/api/auth/discord/callback"
# Optional: register extra callback URLs in Discord and list them here.
# RedirectUris:
# - "https://bot.example.com/api/auth/discord/callback"
# UseRequestOrigin: true
# CookieSecure: false
OwnerUserIds:
- "YOUR_DISCORD_USER_ID"
AllowedUserIds: []
+2 -2
View File
@@ -38,7 +38,7 @@ Welcome:
Embed:
Colour: "#45b463"
Title: "Welcome to ServerName"
Message: ":smile: %joined_user% has just landed!\n\n🔨 **Server Rules:** <#1202667199853232129>"
Message: ":smile: %joined_user% has just landed!\n\n🔨 **Server Rules:** <#CHANNEL_ID>"
Icon:
Mode: "USER" # USER | BOT | CUSTOM
CustomURL: "https://example.com/custom.png"
@@ -64,7 +64,7 @@ Welcome:
Modern:
Colour: "#45b463"
Title: "**Welcome to ServerName**"
Body: ":smile: %joined_user% has just landed!\n\n🔨 **Server Rules:** <#1202667199853232129>"
Body: ":smile: %joined_user% has just landed!\n\n🔨 **Server Rules:** <#CHANNEL_ID>"
Icon:
Mode: "BOT" # USER | BOT | CUSTOM
CustomURL: "https://example.com/custom-icon.png"
+1 -1
View File
@@ -35,7 +35,7 @@ Features:
SuggestTickets: true # Should SupportBot AI suggest creating a ticket if the user needs more help?
Channels:
AIChannel: "1469028791312715902"
AIChannel: "CHANNEL_ID"
Embed:
Color: "#45b463"
+45 -48
View File
@@ -12,28 +12,27 @@
#
# SupportBot Configuration (supportbot.yml)
SupportBot_Version: "v26.1.1"
SupportBot_Version: "v26.3.0"
# -------------------------
# General
# -------------------------
General:
Name: "SupportBot"
Name: "SupportBo"
Token: "BOT_TOKEN"
Addons:
Enabled: true
GuildId: ""
# -------------------------
# Activity
# -------------------------
Activity:
Status: "SupportBot v8"
Type: "Competing"
Status: "Char"
Type: "Watching"
StreamingURL: "https://www.twitch.tv/YOUR_TWITCH_NAME"
# Available Types:
# Playing
# Watching
@@ -43,9 +42,9 @@ Activity:
# You can also update the activity via Discord using: /settings
# -------------------------
# Embeds
# -------------------------
# -------------------------
# Embeds
# -------------------------
Embed:
Colours:
@@ -55,12 +54,11 @@ Embed:
Warn: "#fca117"
Footer: "SupportBot | Developed by Emerald Development"
# Use 0x<hexcode> to change the colour of the embeds.
# -------------------------
# Roles
# -------------------------
# -------------------------
# Roles
# -------------------------
Roles:
AutoRole:
@@ -74,19 +72,18 @@ Roles:
Mod:
AllowSupportStaff: false
# Allow Support Staff to use the /mod command. (More in detail customisation in commands.yml)
# ----------------------------
# System Messages
# ----------------------------
# ----------------------------
# System Messages
# ----------------------------
Welcome:
Enabled: true
Welcome:
Enabled: false
Channel: "CHANNEL_ID"
Leave:
Enabled: true
Leave:
Enabled: false
Channel: "CHANNEL_ID"
# ----------------------------
@@ -110,7 +107,7 @@ Suggestions:
# If true this will allow the user to vote for a suggestion they created
ShowUsers: true
Threads:
Enabled: true
Title: "Suggestion-releated Thread"
@@ -121,7 +118,6 @@ Suggestions:
Downvote: "2"
RemoveVote: "4"
RemoveVote_Title: "Remove Vote"
# Available Button Styles
# 1 - Blurple
# 2 - Grey
@@ -129,21 +125,21 @@ Suggestions:
# 4 - Red
Tags:
Created: "TAG_ID"
Considering: "TAG_ID"
Solved: "TAG_ID"
Denied: "TAG_ID"
Created: "TAG_ID"
Considering: "TAG_ID"
Solved: "TAG_ID"
Denied: "TAG_ID"
# -------------------------
# Tickets
# -------------------------
VoiceTickets:
Name: "%username%'s VC"
Name: "%username%'s VC"
Category: "CATEGORY_ID"
Ticket:
TicketType: "channels"
TicketType: "channels"
# Available TicketTypes:
# channels - Tickets will be created as channels in the TicketChannelsCategory
@@ -154,14 +150,14 @@ Ticket:
DMOnRemove: true # DM the user when they are removed from the ticket
DMTranscript: true # DM the user a transcript of the ticket when it is closed
TicketHome: "1469028381638000725"
TicketHome: "CHANNEL_ID"
# What is TicketHome?
# - Channel where the Ticket creation panel is sent.
# - Channel where ticket threads are made. (only if ticket threads is enabled above.)
# For TicketType: channels
TicketChannelsCategory: "CATEGORY_ID"
TicketChannelsCategory: "CATEGORY_ID"
TicketChannelsCategory2: "CATEGORY_ID" # This will be used if the first category has reached the max channel limit.
TicketArchiveCategory: "CATEGORY_ID"
# ---
@@ -184,14 +180,15 @@ Ticket:
StaffOnly: true
# Set to false is anyone is able to close a ticket.
Invites: # Invites is for ticket threads.
Invites:
# Invites is for ticket threads.
StaffOnly: true
ClaimTickets:
Enabled: false
Channel: "CHANNEL_ID"
Channel: "CHANNEL_ID"
# Channel where the ticket assignments are sent for staff to claim.
ClaimAcceptTime: 120000
# How long the assigned user has to accept the ticket before it gets re-assigned to someone else.
# 120000 = 2 Minutes
@@ -203,7 +200,6 @@ Ticket:
ButtonTitle: "Claim Ticket"
ButtonEmoji: "🎫"
Button: "1"
# Available Button Styles
# 1 - Blurple
# 2 - Grey
@@ -211,12 +207,13 @@ Ticket:
# 4 - Red
ReviewSystem:
Enabled: false
Enabled: false
Channel: "CHANNEL_ID"
UseModal: true
Questions: # Default questions asked when a ticket is created, these are used if departments are disabled.
Enabled: false
Questions:
# Default questions asked when a ticket is created, these are used if departments are disabled.
Enabled: false
List:
- "Please provide your account email?"
- "What is the nature of your issue?"
@@ -228,16 +225,16 @@ Ticket:
TicketBlacklistLog: "CHANNEL_ID"
AIMode:
Enabled: true
Enabled: false
ThreadName: "Chat with SupportBot AI"
WelcomeMessage: "Hi! I’m SupportBot AI. You can chat with me here about your issue."
# -------------------------
# Ticket Departments
# -------------------------
# -------------------------
# Ticket Departments
# -------------------------
DepartmentSystem:
Enabled: true
Enabled: false
Placeholder: "Choose a ticket department"
DefaultDepartment: "general"
@@ -339,14 +336,14 @@ Buttons:
# 3 - Green
# 4 - Red
# -------------------------
# Select Menus
# -------------------------
# -------------------------
# Select Menus
# -------------------------
SelectMenus:
Tickets:
PanelEmoji: "⚙️"
CloseEmoji: "🗑️"
ArchiveEmoji: "♻️"
LockEmoji: "🔐"
+5 -3
View File
@@ -21,7 +21,8 @@ Panel: true
Style:
Title: "## SupportBot Ticket Creation"
Description: "Click on the button to file a `Ticket` and our team will try their best to assist you in the best way we can!"
Description: "Click on the button to file a `Ticket` and our team will try their
best to assist you in the best way we can!"
Image: "https://i.imgur.com/dejQvkg.png"
Color: "#45b463"
Layout: "4"
@@ -45,7 +46,7 @@ Button:
# 4 - Green
DepartmentMenu:
CustomId: "ticketdepartmentselect"
CustomId: "ticketdepartmentselect"
Placeholder: "Choose a ticket department"
DefaultDescription: "Open a support ticket"
DefaultEmoji: "🎫"
@@ -58,7 +59,8 @@ Settings:
BottomDivider: false
Messages:
NotConfigured: "Ticket Panel is not set up. Please configure it in `/Configs/ticket-panel.yml`."
NotConfigured: "Ticket Panel is not set up. Please configure it in
`/Configs/ticket-panel.yml`."
InvalidChannel: "TicketHome channel not found. Please check your config file."
PanelSent: "Ticket panel message has been sent!"
PanelSentWithDepartments: "Ticket panel message with department selection has been sent!"
+33
View File
@@ -0,0 +1,33 @@
Theme:
Background: '#0e0e0e'
Panel: '#1d1d1d'
PanelSecondary: '#222222'
PanelTertiary: '#1d2938'
Border: '#2e2e2e'
Text: '#e6edf3'
Muted: '#606060'
Accent: '#396ff8'
AccentSoft: rgba(34, 197, 94, 0.12)
AccentBorder: rgba(34, 197, 94, 0.25)
AccentText: '#8df0ad'
Link: '#396ff8'
AttachmentLink: '#396ff8'
CodeBackground: '#0e0e0e'
Typography:
FontFamily: Poppins
Header:
Title: Ticket Transcript
Subtitle: Exported conversation log for support ticket **{{ticketName}}**
Badge: Closed Transcript
ShowMetaCards: true
Meta:
ChannelLabel: Ticket Name
TicketIdLabel: Ticket ID
MessageCountLabel: Message Count
CloseReasonLabel: Close Reason
DefaultCloseReason: No Reason Provided.
Messages:
SectionTitle: Messages
EmptyState: No messages were found in this ticket.
Advanced:
CustomCss: ''
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
+29
View File
@@ -0,0 +1,29 @@
{
"version": 1,
"users": {
"829112572816130058": {
"id": "829112572816130058",
"username": "ch_ar.",
"globalName": "Char",
"avatar": "823630e777efe85c7fe71402f00ab0c1",
"role": "owner",
"permissions": null,
"enabled": true,
"createdAt": 1779820911269,
"updatedAt": 1779822114501,
"createdBy": "system"
},
"YOUR_DISCORD_USER_ID": {
"id": "YOUR_DISCORD_USER_ID",
"username": null,
"globalName": null,
"avatar": null,
"role": "owner",
"permissions": null,
"enabled": true,
"createdAt": 1779822020405,
"updatedAt": 1779822020405,
"createdBy": "system"
}
}
}
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
{
"autoDelete": {
"enabled": false,
"afterDays": 30
},
"publicAccess": {
"enabled": false
}
}
+12
View File
@@ -0,0 +1,12 @@
FROM node:22
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]
+1 -3
View File
@@ -5,9 +5,7 @@ const fs = require("fs");
const yaml = require("js-yaml");
const axios = require("axios");
const supportbotai = yaml.load(
fs.readFileSync("./Configs/supportbot-ai.yml", "utf8"),
);
const supportbotai = require("../../Structures/ConfigStore").supportbotAi;
function extractTextFromMessage(message) {
if (!message) return "";
+1 -3
View File
@@ -5,9 +5,7 @@ const fs = require("fs");
const yaml = require("js-yaml");
const OpenAI = require("openai");
const supportbotai = yaml.load(
fs.readFileSync("./Configs/supportbot-ai.yml", "utf8"),
);
const supportbotai = require("../../Structures/ConfigStore").supportbotAi;
const client = new OpenAI({
apiKey: supportbotai.General.Model_API_Key,
+1 -3
View File
@@ -5,9 +5,7 @@ const fs = require("fs");
const yaml = require("js-yaml");
const OpenAI = require("openai");
const supportbotai = yaml.load(
fs.readFileSync("./Configs/supportbot-ai.yml", "utf8"),
);
const supportbotai = require("../../Structures/ConfigStore").supportbotAi;
const client = new OpenAI({
apiKey: supportbotai.General.Model_API_Key,
+28 -6
View File
@@ -1,9 +1,31 @@
const Event = require("../Structures/Event.js");
module.exports = new Event("guildCreate", async (client) => {
console.log(
`\u001b[31m`,
`${client.user.username} is not in the correct server set in your config. Please leave all other servers and restart the bot.`
const {
getConfiguredGuildId,
syncGuildHealth,
logGuildWarning,
} = require("../Structures/GuildManager.js");
module.exports = new Event("guildCreate", async (client, guild) => {
const configuredId = getConfiguredGuildId();
if (!configuredId) {
logGuildWarning(
client,
`Joined "${guild.name}" (${guild.id}). Set General.GuildId in config to lock the bot to one server.`,
);
syncGuildHealth(client);
return;
}
if (guild.id === configuredId) {
syncGuildHealth(client);
return;
}
logGuildWarning(
client,
`Joined unauthorized server "${guild.name}" (${guild.id}). Leave it from the dashboard or remove the invite.`,
);
console.log(`\u001b[31m`, `${client.user.username} will now exit.`);
return process.exit(1);
syncGuildHealth(client);
});
+20 -7
View File
@@ -1,10 +1,23 @@
const Event = require("../Structures/Event.js");
const {
getConfiguredGuildId,
syncGuildHealth,
logGuildWarning,
} = require("../Structures/GuildManager.js");
module.exports = new Event("guildDelete", async (client) => {
console.log(
`\u001b[31m`,
`${client.user.username} is not in the correct server set in your config. Please join the server and restart the bot.`
);
console.log(`\u001b[31m`, `${client.user.username} will now exit.`);
return process.exit(1);
module.exports = new Event("guildDelete", async (client, guild) => {
const configuredId = getConfiguredGuildId();
if (configuredId && guild.id === configuredId) {
logGuildWarning(
client,
`Left the configured server "${guild.name}" (${guild.id}). Re-invite the bot or update General.GuildId.`,
);
} else if (!configuredId) {
logGuildWarning(client, `Left server "${guild.name}" (${guild.id}).`);
} else {
logGuildWarning(client, `Left server "${guild.name}" (${guild.id}).`);
}
syncGuildHealth(client);
});
+2 -8
View File
@@ -10,16 +10,10 @@ const {
ThumbnailBuilder,
MediaGalleryBuilder
} = require("discord.js");
const fs = require("fs");
const yaml = require("js-yaml");
const Event = require("../Structures/Event.js");
const supportbot = yaml.load(
fs.readFileSync("./Configs/supportbot.yml", "utf8")
);
const msgconfig = yaml.load(
fs.readFileSync("./Configs/messages.yml", "utf8")
);
const supportbot = require("../Structures/ConfigStore").supportbot;
const msgconfig = require("../Structures/ConfigStore").messages;
function getWelcomeThumbnail(client, member, iconCfg) {
switch ((iconCfg?.Mode || "").toUpperCase()) {
+2 -2
View File
@@ -3,8 +3,8 @@ const fs = require("fs");
const yaml = require("js-yaml");
const Event = require("../Structures/Event.js");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const supportbot = require("../Structures/ConfigStore").supportbot;
const msgconfig = require("../Structures/ConfigStore").messages;
module.exports = new Event("guildMemberRemove", async (client, member) => {
+4 -7
View File
@@ -1,12 +1,8 @@
const fs = require("fs");
const Discord = require("discord.js");
const yaml = require("js-yaml");
const supportbot = yaml.load(
fs.readFileSync("./Configs/supportbot.yml", "utf8"),
);
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const supportbot = require("../Structures/ConfigStore").supportbot;
const cmdconfig = require("../Structures/ConfigStore").commands;
const msgconfig = require("../Structures/ConfigStore").messages;
const Event = require("../Structures/Event.js");
const db = require("../Structures/Database.js");
@@ -69,6 +65,7 @@ module.exports = new Event("interactionCreate", async (client, interaction) => {
"\u001b[37;1m",
`${interaction.user.username} has executed ${command.name}`,
);
await command.run(interaction);
}
} catch (error) {
+2 -8
View File
@@ -1,14 +1,8 @@
const fs = require("fs");
const Discord = require("discord.js");
const yaml = require("js-yaml");
const axios = require("axios");
const supportbotai = yaml.load(
fs.readFileSync("./Configs/supportbot-ai.yml", "utf8"),
);
const supportbot = yaml.load(
fs.readFileSync("./Configs/supportbot.yml", "utf8"),
);
const supportbotai = require("../Structures/ConfigStore").supportbotAi;
const supportbot = require("../Structures/ConfigStore").supportbot;
const Event = require("../Structures/Event.js");
const AIDatabase = require("../Structures/AIDatabase.js");
+2 -2
View File
@@ -3,8 +3,8 @@ const fs = require("fs");
const yaml = require("js-yaml");
const Event = require("../Structures/Event.js");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const supportbot = require("../Structures/ConfigStore").supportbot;
const msgconfig = require("../Structures/ConfigStore").messages;
module.exports = new Event("messageDelete", async (client, message) => {
if (!message.guild) return;
+3 -10
View File
@@ -1,13 +1,6 @@
const fs = require("fs");
const yaml = require("js-yaml");
const supportbot = yaml.load(
fs.readFileSync("./Configs/supportbot.yml", "utf8"),
);
const supportbotai = yaml.load(
fs.readFileSync("./Configs/supportbot-ai.yml", "utf8"),
);
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const supportbot = require("../Structures/ConfigStore").supportbot;
const supportbotai = require("../Structures/ConfigStore").supportbotAi;
const cmdconfig = require("../Structures/ConfigStore").commands;
const Event = require("../Structures/Event.js");
+2 -2
View File
@@ -4,8 +4,8 @@ const yaml = require("js-yaml");
const Event = require("../Structures/Event.js");
// Load the configuration files
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const supportbot = require("../Structures/ConfigStore").supportbot;
const msgconfig = require("../Structures/ConfigStore").messages;
module.exports = new Event("messageUpdate", async (client, oldMessage, newMessage) => {
+5 -123
View File
@@ -1,126 +1,8 @@
const fs = require("fs");
const Discord = require("discord.js");
const yaml = require("js-yaml");
const Event = require("../Structures/Event.js");
// Load configs
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const ACTIVITY_TYPES = {
PLAYING: Discord.ActivityType.Playing,
WATCHING: Discord.ActivityType.Watching,
LISTENING: Discord.ActivityType.Listening,
COMPETING: Discord.ActivityType.Competing
};
const setActivity = (client, type, status) => {
const activityType = ACTIVITY_TYPES[type?.toUpperCase()];
if (!activityType) return;
client.user.setPresence({
activities: [{ name: status || "Online", type: activityType }],
status: "online"
});
};
// simple colors
const c = {
reset: "\x1b[0m",
gray: "\x1b[90m",
green: "\x1b[32m",
yellow: "\x1b[33m",
cyan: "\x1b[36m",
bold: "\x1b[1m"
};
function line() {
console.log(`${c.gray}────────────────────────────────────────────────────────${c.reset}`);
}
function section(title) {
console.log(`\n${c.green}${title}${c.reset}`);
console.log(`${c.gray}${"-".repeat(title.length)}${c.reset}`);
}
function info(label, value) {
console.log(`${c.gray}${label.padEnd(14)}${c.reset} ${value}`);
}
function status(label, ok, details = "") {
const icon = ok ? `${c.green}✓${c.reset}` : `${c.yellow}!${c.reset}`;
console.log(` ${icon} ${label}${details ? ` (${details})` : ""}`);
}
const logStartup = async (client) => {
console.clear();
const botName = supportbot?.General?.Name || "SupportBot";
const botVersion = supportbot?.SupportBot_Version || "Unknown";
const inviteUrl = `https://discord.com/api/oauth2/authorize?client_id=${client.user.id}&permissions=8&scope=bot%20applications.commands`;
line();
console.log(`${c.bold}${c.green}SupportBot${c.reset}`);
console.log(`${c.gray}Emerald Services${c.reset}`);
line();
section("System");
info("Bot Name", botName);
info("Version", botVersion);
info("Node.js", process.version);
info("Discord.js", `v${Discord.version}`);
info("Logged in as", client.user.tag);
info("Guilds", `${client.guilds.cache.size}`);
section("Links");
info("Docs", "https://emerald-services.gitbook.io/");
info("Discord", "https://dsc.gg/emerald-dev");
info("Invite", inviteUrl);
console.log("");
};
const checkConfigs = async (client) => {
const guild = client.guilds.cache.first();
if (!guild) return;
section("Config Check");
const roles = [
supportbot?.Roles?.StaffMember?.Admin,
supportbot?.Roles?.StaffMember?.Staff,
supportbot?.Roles?.AutoRole?.Role
].filter(Boolean);
const channels = [
supportbot?.Ticket?.TicketHome
].filter(Boolean);
const [roleResults, channelResults] = await Promise.all([
Promise.all(roles.map((role) => client.getRole(role, guild))),
Promise.all(channels.map((channel) => client.getChannel(channel, guild)))
]);
const missingRoles = roles.filter((_, i) => !roleResults[i]);
const missingChannels = channels.filter((_, i) => !channelResults[i]);
if (!missingRoles.length && !missingChannels.length) {
status("All configurations validated successfully", true);
} else {
if (missingRoles.length) {
status("Missing roles", false, missingRoles.join(", "));
}
if (missingChannels.length) {
status("Missing channels", false, missingChannels.join(", "));
}
}
console.log("");
};
const { runBotReady } = require("../Structures/BotStartup.js");
module.exports = new Event("clientReady", async (client) => {
setActivity(client, supportbot?.Activity?.Type, supportbot?.Activity?.Status);
await logStartup(client);
await checkConfigs(client);
});
// restartDiscordBot runs startup manually — clientReady often does not re-fire anyway
if (client.__explicitStartup) return;
await runBotReady(client, { clearConsole: true, logCommands: false });
});
+2
View File
@@ -0,0 +1,2 @@
[2026-05-20T12:58:22.767Z] (node:15252) Warning: Accessing non-existent property 'getIntrinsicHookSteps' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
+4
View File
@@ -0,0 +1,4 @@
[2026-05-26T18:08:20.799Z] Unhandled Rejection: DiscordjsError [TokenInvalid]: An invalid token was provided.
[2026-05-26T18:30:31.132Z] Unhandled Rejection: DiscordjsError [TokenInvalid]: An invalid token was provided.
[2026-05-26T18:34:34.094Z] Unhandled Rejection: DiscordjsError [TokenInvalid]: An invalid token was provided.
[2026-05-26T19:00:20.833Z] Unhandled Rejection: DiscordjsError [TokenInvalid]: An invalid token was provided.
+29
View File
@@ -0,0 +1,29 @@
[2026-05-19T22:25:25.691Z] [API] Server running on port 3000
[2026-05-19T22:25:26.507Z] ────────────────────────────────────────────────────────
[2026-05-19T22:25:26.508Z] SupportBot
[2026-05-19T22:25:26.508Z] Emerald Services
[2026-05-19T22:25:26.509Z] ────────────────────────────────────────────────────────
[2026-05-19T22:25:26.509Z]
System
[2026-05-19T22:25:26.519Z] ------
[2026-05-19T22:25:26.520Z] Bot Name  SupportBo
[2026-05-19T22:25:26.520Z] Version  v26.3.0
[2026-05-19T22:25:26.520Z] Node.js  v24.14.1
[2026-05-19T22:25:26.521Z] Discord.js  v14.26.4
[2026-05-19T22:25:26.521Z] Logged in as  BLITZ#7183
[2026-05-19T22:25:26.522Z] Guilds  1
[2026-05-19T22:25:26.522Z]
Links
[2026-05-19T22:25:26.523Z] -----
[2026-05-19T22:25:26.523Z] Docs  https://emerald-services.gitbook.io/
[2026-05-19T22:25:26.524Z] Discord  https://dsc.gg/emerald-dev
[2026-05-19T22:25:26.525Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-19T22:25:26.525Z]
[2026-05-19T22:25:26.526Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-19T22:25:26.527Z]
Config Check
[2026-05-19T22:25:26.528Z] ------------
[2026-05-19T22:25:26.530Z] ✓ All configurations validated successfully
[2026-05-19T22:25:26.531Z]
[2026-05-19T22:25:26.702Z]
✓ Slash Commands Registered for Char's Test Server
+292
View File
@@ -0,0 +1,292 @@
[2026-05-20T12:19:19.626Z] [API] Server running on port 3000
[2026-05-20T12:19:20.498Z] ────────────────────────────────────────────────────────
[2026-05-20T12:19:20.499Z] SupportBot
[2026-05-20T12:19:20.499Z] Emerald Services
[2026-05-20T12:19:20.500Z] ────────────────────────────────────────────────────────
[2026-05-20T12:19:20.500Z]
System
[2026-05-20T12:19:20.667Z] ------
[2026-05-20T12:19:20.667Z] Bot Name  SupportBo
[2026-05-20T12:19:20.668Z] Version  v26.3.0
[2026-05-20T12:19:20.668Z] Node.js  v24.14.1
[2026-05-20T12:19:20.668Z] Discord.js  v14.26.4
[2026-05-20T12:19:20.669Z] Logged in as  BLITZ#7183
[2026-05-20T12:19:20.669Z] Guilds  1
[2026-05-20T12:19:20.669Z]
Links
[2026-05-20T12:19:20.670Z] -----
[2026-05-20T12:19:20.670Z] Docs  https://emerald-services.gitbook.io/
[2026-05-20T12:19:20.670Z] Discord  https://dsc.gg/emerald-dev
[2026-05-20T12:19:20.671Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-20T12:19:20.671Z]
[2026-05-20T12:19:20.672Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-20T12:19:20.675Z]
Config Check
[2026-05-20T12:19:20.676Z] ------------
[2026-05-20T12:19:20.678Z] ✓ All configurations validated successfully
[2026-05-20T12:19:20.678Z]
[2026-05-20T12:19:20.887Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-20T12:24:38.643Z] [API] Server running on port 3000
[2026-05-20T12:24:39.659Z] ────────────────────────────────────────────────────────
[2026-05-20T12:24:39.660Z] SupportBot
[2026-05-20T12:24:39.660Z] Emerald Services
[2026-05-20T12:24:39.660Z] ────────────────────────────────────────────────────────
[2026-05-20T12:24:39.661Z]
System
[2026-05-20T12:24:39.661Z] ------
[2026-05-20T12:24:39.662Z] Bot Name  SupportBo
[2026-05-20T12:24:39.662Z] Version  v26.3.0
[2026-05-20T12:24:39.663Z] Node.js  v24.14.1
[2026-05-20T12:24:39.663Z] Discord.js  v14.26.4
[2026-05-20T12:24:39.663Z] Logged in as  BLITZ#7183
[2026-05-20T12:24:39.664Z] Guilds  1
[2026-05-20T12:24:39.664Z]
Links
[2026-05-20T12:24:39.665Z] -----
[2026-05-20T12:24:39.665Z] Docs  https://emerald-services.gitbook.io/
[2026-05-20T12:24:39.666Z] Discord  https://dsc.gg/emerald-dev
[2026-05-20T12:24:39.666Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-20T12:24:39.667Z]
[2026-05-20T12:24:39.667Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-20T12:24:39.670Z]
Config Check
[2026-05-20T12:24:39.671Z] ------------
[2026-05-20T12:24:39.674Z] ✓ All configurations validated successfully
[2026-05-20T12:24:39.674Z]
[2026-05-20T12:24:39.875Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-20T12:26:52.985Z] [API] Server running on port 3000
[2026-05-20T12:26:54.033Z] ────────────────────────────────────────────────────────
[2026-05-20T12:26:54.034Z] SupportBot
[2026-05-20T12:26:54.034Z] Emerald Services
[2026-05-20T12:26:54.035Z] ────────────────────────────────────────────────────────
[2026-05-20T12:26:54.035Z]
System
[2026-05-20T12:26:54.035Z] ------
[2026-05-20T12:26:54.036Z] Bot Name  SupportBo
[2026-05-20T12:26:54.036Z] Version  v26.3.0
[2026-05-20T12:26:54.037Z] Node.js  v24.14.1
[2026-05-20T12:26:54.037Z] Discord.js  v14.26.4
[2026-05-20T12:26:54.037Z] Logged in as  BLITZ#7183
[2026-05-20T12:26:54.038Z] Guilds  1
[2026-05-20T12:26:54.038Z]
Links
[2026-05-20T12:26:54.039Z] -----
[2026-05-20T12:26:54.039Z] Docs  https://emerald-services.gitbook.io/
[2026-05-20T12:26:54.040Z] Discord  https://dsc.gg/emerald-dev
[2026-05-20T12:26:54.040Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-20T12:26:54.041Z]
[2026-05-20T12:26:54.042Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-20T12:26:54.044Z]
Config Check
[2026-05-20T12:26:54.045Z] ------------
[2026-05-20T12:26:54.047Z] ✓ All configurations validated successfully
[2026-05-20T12:26:54.048Z]
[2026-05-20T12:26:54.256Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-20T12:27:29.337Z] [BotReload] Restarting Discord bot after config change…
[2026-05-20T12:27:30.140Z] ────────────────────────────────────────────────────────
[2026-05-20T12:27:30.141Z] SupportBot
[2026-05-20T12:27:30.141Z] Emerald Services
[2026-05-20T12:27:30.141Z] ────────────────────────────────────────────────────────
[2026-05-20T12:27:30.142Z]
System
[2026-05-20T12:27:30.142Z] ------
[2026-05-20T12:27:30.143Z] Bot Name  SupportBo
[2026-05-20T12:27:30.144Z] Version  v26.3.0
[2026-05-20T12:27:30.144Z] Node.js  v24.14.1
[2026-05-20T12:27:30.144Z] Discord.js  v14.26.4
[2026-05-20T12:27:30.145Z] Logged in as  BLITZ#7183
[2026-05-20T12:27:30.145Z] Guilds  1
[2026-05-20T12:27:30.146Z]
Links
[2026-05-20T12:27:30.146Z] -----
[2026-05-20T12:27:30.147Z] Docs  https://emerald-services.gitbook.io/
[2026-05-20T12:27:30.147Z] Discord  https://dsc.gg/emerald-dev
[2026-05-20T12:27:30.147Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-20T12:27:30.148Z]
[2026-05-20T12:27:30.149Z]
Config Check
[2026-05-20T12:27:30.149Z] ------------
[2026-05-20T12:27:30.150Z] ✓ All configurations validated successfully
[2026-05-20T12:27:30.150Z]
[2026-05-20T12:27:30.433Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-20T12:27:30.434Z] [BotReload] Bot restarted successfully
[2026-05-20T12:27:34.617Z]  [Executed]  ch_ar. has executed ticketpanel
[2026-05-20T12:27:34.856Z] [TICKET PANEL] Previous panel message not found, creating a new one.
[2026-05-20T12:39:22.918Z] [API] Server running on port 3000
[2026-05-20T12:39:23.738Z] ────────────────────────────────────────────────────────
[2026-05-20T12:39:23.739Z] SupportBot
[2026-05-20T12:39:23.739Z] Emerald Services
[2026-05-20T12:39:23.739Z] ────────────────────────────────────────────────────────
[2026-05-20T12:39:23.740Z]
System
[2026-05-20T12:39:23.740Z] ------
[2026-05-20T12:39:23.741Z] Bot Name  SupportBo
[2026-05-20T12:39:23.741Z] Version  v26.3.0
[2026-05-20T12:39:23.741Z] Node.js  v24.14.1
[2026-05-20T12:39:23.741Z] Discord.js  v14.26.4
[2026-05-20T12:39:23.742Z] Logged in as  BLITZ#7183
[2026-05-20T12:39:23.742Z] Guilds  1
[2026-05-20T12:39:23.743Z]
Links
[2026-05-20T12:39:23.743Z] -----
[2026-05-20T12:39:23.743Z] Docs  https://emerald-services.gitbook.io/
[2026-05-20T12:39:23.744Z] Discord  https://dsc.gg/emerald-dev
[2026-05-20T12:39:23.745Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-20T12:39:23.745Z]
[2026-05-20T12:39:23.746Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-20T12:39:23.748Z]
Config Check
[2026-05-20T12:39:23.750Z] ------------
[2026-05-20T12:39:23.752Z] ✓ All configurations validated successfully
[2026-05-20T12:39:23.752Z]
[2026-05-20T12:39:23.966Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-20T12:46:34.090Z] [API] Server running on port 3000
[2026-05-20T12:46:34.880Z] ────────────────────────────────────────────────────────
[2026-05-20T12:46:34.880Z] SupportBot
[2026-05-20T12:46:34.881Z] Emerald Services
[2026-05-20T12:46:34.881Z] ────────────────────────────────────────────────────────
[2026-05-20T12:46:34.882Z]
System
[2026-05-20T12:46:34.882Z] ------
[2026-05-20T12:46:34.882Z] Bot Name  SupportBo
[2026-05-20T12:46:34.883Z] Version  v26.3.0
[2026-05-20T12:46:34.883Z] Node.js  v24.14.1
[2026-05-20T12:46:34.884Z] Discord.js  v14.26.4
[2026-05-20T12:46:34.884Z] Logged in as  BLITZ#7183
[2026-05-20T12:46:34.885Z] Guilds  1
[2026-05-20T12:46:34.885Z]
Links
[2026-05-20T12:46:34.886Z] -----
[2026-05-20T12:46:34.887Z] Docs  https://emerald-services.gitbook.io/
[2026-05-20T12:46:34.887Z] Discord  https://dsc.gg/emerald-dev
[2026-05-20T12:46:34.888Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-20T12:46:34.888Z]
[2026-05-20T12:46:34.889Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-20T12:46:34.890Z]
Config Check
[2026-05-20T12:46:34.891Z] ------------
[2026-05-20T12:46:34.893Z] ✓ All configurations validated successfully
[2026-05-20T12:46:34.894Z]
[2026-05-20T12:46:35.096Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-20T12:52:39.673Z] [API] Server running on port 3000
[2026-05-20T12:52:40.422Z] ────────────────────────────────────────────────────────
[2026-05-20T12:52:40.423Z] SupportBot
[2026-05-20T12:52:40.423Z] Emerald Services
[2026-05-20T12:52:40.423Z] ────────────────────────────────────────────────────────
[2026-05-20T12:52:40.424Z]
System
[2026-05-20T12:52:40.424Z] ------
[2026-05-20T12:52:40.424Z] Bot Name  SupportBo
[2026-05-20T12:52:40.425Z] Version  v26.3.0
[2026-05-20T12:52:40.425Z] Node.js  v24.14.1
[2026-05-20T12:52:40.425Z] Discord.js  v14.26.4
[2026-05-20T12:52:40.426Z] Logged in as  BLITZ#7183
[2026-05-20T12:52:40.426Z] Guilds  1
[2026-05-20T12:52:40.426Z]
Links
[2026-05-20T12:52:40.427Z] -----
[2026-05-20T12:52:40.427Z] Docs  https://emerald-services.gitbook.io/
[2026-05-20T12:52:40.428Z] Discord  https://dsc.gg/emerald-dev
[2026-05-20T12:52:40.428Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-20T12:52:40.429Z]
[2026-05-20T12:52:40.429Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-20T12:52:40.431Z]
Config Check
[2026-05-20T12:52:40.431Z] ------------
[2026-05-20T12:52:40.435Z] ✓ All configurations validated successfully
[2026-05-20T12:52:40.436Z]
[2026-05-20T12:52:40.672Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-20T12:58:22.768Z] [API] Server running on port 3000
[2026-05-20T12:58:23.534Z] ────────────────────────────────────────────────────────
[2026-05-20T12:58:23.534Z] SupportBot
[2026-05-20T12:58:23.534Z] Emerald Services
[2026-05-20T12:58:23.535Z] ────────────────────────────────────────────────────────
[2026-05-20T12:58:23.535Z]
System
[2026-05-20T12:58:23.536Z] ------
[2026-05-20T12:58:23.536Z] Bot Name  SupportBo
[2026-05-20T12:58:23.536Z] Version  v26.3.0
[2026-05-20T12:58:23.537Z] Node.js  v24.14.1
[2026-05-20T12:58:23.537Z] Discord.js  v14.26.4
[2026-05-20T12:58:23.538Z] Logged in as  BLITZ#7183
[2026-05-20T12:58:23.538Z] Guilds  1
[2026-05-20T12:58:23.539Z]
Links
[2026-05-20T12:58:23.539Z] -----
[2026-05-20T12:58:23.540Z] Docs  https://emerald-services.gitbook.io/
[2026-05-20T12:58:23.540Z] Discord  https://dsc.gg/emerald-dev
[2026-05-20T12:58:23.541Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-20T12:58:23.541Z]
[2026-05-20T12:58:23.542Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-20T12:58:23.543Z]
Config Check
[2026-05-20T12:58:23.544Z] ------------
[2026-05-20T12:58:23.546Z] ✓ All configurations validated successfully
[2026-05-20T12:58:23.549Z]
[2026-05-20T12:58:23.750Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-20T13:00:24.932Z] [API] Server running on port 3000
[2026-05-20T13:00:25.900Z] ────────────────────────────────────────────────────────
[2026-05-20T13:00:25.901Z] SupportBot
[2026-05-20T13:00:25.901Z] Emerald Services
[2026-05-20T13:00:25.901Z] ────────────────────────────────────────────────────────
[2026-05-20T13:00:25.902Z]
System
[2026-05-20T13:00:25.902Z] ------
[2026-05-20T13:00:25.903Z] Bot Name  SupportBo
[2026-05-20T13:00:25.903Z] Version  v26.3.0
[2026-05-20T13:00:25.903Z] Node.js  v24.14.1
[2026-05-20T13:00:25.904Z] Discord.js  v14.26.4
[2026-05-20T13:00:25.904Z] Logged in as  BLITZ#7183
[2026-05-20T13:00:25.905Z] Guilds  1
[2026-05-20T13:00:25.905Z]
Links
[2026-05-20T13:00:25.906Z] -----
[2026-05-20T13:00:25.906Z] Docs  https://emerald-services.gitbook.io/
[2026-05-20T13:00:25.907Z] Discord  https://dsc.gg/emerald-dev
[2026-05-20T13:00:25.907Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-20T13:00:25.907Z]
[2026-05-20T13:00:25.908Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-20T13:00:25.909Z]
Config Check
[2026-05-20T13:00:25.910Z] ------------
[2026-05-20T13:00:25.912Z] ✓ All configurations validated successfully
[2026-05-20T13:00:25.913Z]
[2026-05-20T13:00:26.169Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-20T13:06:04.723Z] [API] Server running on port 3000
[2026-05-20T13:06:05.516Z] ────────────────────────────────────────────────────────
[2026-05-20T13:06:05.517Z] SupportBot
[2026-05-20T13:06:05.517Z] Emerald Services
[2026-05-20T13:06:05.518Z] ────────────────────────────────────────────────────────
[2026-05-20T13:06:05.518Z]
System
[2026-05-20T13:06:05.519Z] ------
[2026-05-20T13:06:05.519Z] Bot Name  SupportBo
[2026-05-20T13:06:05.519Z] Version  v26.3.0
[2026-05-20T13:06:05.520Z] Node.js  v24.14.1
[2026-05-20T13:06:05.520Z] Discord.js  v14.26.4
[2026-05-20T13:06:05.521Z] Logged in as  BLITZ#7183
[2026-05-20T13:06:05.521Z] Guilds  1
[2026-05-20T13:06:05.522Z]
Links
[2026-05-20T13:06:05.522Z] -----
[2026-05-20T13:06:05.523Z] Docs  https://emerald-services.gitbook.io/
[2026-05-20T13:06:05.524Z] Discord  https://dsc.gg/emerald-dev
[2026-05-20T13:06:05.525Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-20T13:06:05.525Z]
[2026-05-20T13:06:05.526Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-20T13:06:05.527Z]
Config Check
[2026-05-20T13:06:05.528Z] ------------
[2026-05-20T13:06:05.530Z] ✓ All configurations validated successfully
[2026-05-20T13:06:05.531Z]
[2026-05-20T13:06:05.724Z]
✓ Slash Commands Registered for Char's Test Server
+416
View File
@@ -0,0 +1,416 @@
[2026-05-26T18:08:20.392Z] [API] Server running on port 3000
[2026-05-26T18:09:50.058Z] [API] Server running on port 3000
[2026-05-26T18:09:50.812Z] ────────────────────────────────────────────────────────
[2026-05-26T18:09:50.812Z] SupportBot
[2026-05-26T18:09:50.813Z] Emerald Services
[2026-05-26T18:09:50.813Z] ────────────────────────────────────────────────────────
[2026-05-26T18:09:50.814Z]
System
[2026-05-26T18:09:50.814Z] ------
[2026-05-26T18:09:50.815Z] Bot Name  SupportBo
[2026-05-26T18:09:50.815Z] Version  v26.3.0
[2026-05-26T18:09:50.815Z] Node.js  v24.14.1
[2026-05-26T18:09:50.816Z] Discord.js  v14.26.4
[2026-05-26T18:09:50.816Z] Logged in as  BLITZ#7183
[2026-05-26T18:09:50.817Z] Guilds  1
[2026-05-26T18:09:50.817Z]
Links
[2026-05-26T18:09:50.818Z] -----
[2026-05-26T18:09:50.818Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T18:09:50.819Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T18:09:50.819Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T18:09:50.820Z]
[2026-05-26T18:09:50.820Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T18:09:50.822Z]
Config Check
[2026-05-26T18:09:50.822Z] ------------
[2026-05-26T18:09:50.824Z] ✓ All configurations validated successfully
[2026-05-26T18:09:50.825Z]
[2026-05-26T18:09:51.093Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T18:18:05.034Z] [API] Server running on port 3000
[2026-05-26T18:18:05.886Z] ────────────────────────────────────────────────────────
[2026-05-26T18:18:05.886Z] SupportBot
[2026-05-26T18:18:05.887Z] Emerald Services
[2026-05-26T18:18:05.887Z] ────────────────────────────────────────────────────────
[2026-05-26T18:18:05.887Z]
System
[2026-05-26T18:18:05.888Z] ------
[2026-05-26T18:18:05.888Z] Bot Name  SupportBo
[2026-05-26T18:18:05.889Z] Version  v26.3.0
[2026-05-26T18:18:05.889Z] Node.js  v24.14.1
[2026-05-26T18:18:05.889Z] Discord.js  v14.26.4
[2026-05-26T18:18:05.890Z] Logged in as  BLITZ#7183
[2026-05-26T18:18:05.890Z] Guilds  1
[2026-05-26T18:18:05.891Z]
Links
[2026-05-26T18:18:05.892Z] -----
[2026-05-26T18:18:05.893Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T18:18:05.894Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T18:18:05.895Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T18:18:05.901Z]
[2026-05-26T18:18:05.903Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T18:18:05.907Z]
Config Check
[2026-05-26T18:18:05.908Z] ------------
[2026-05-26T18:18:05.910Z] ✓ All configurations validated successfully
[2026-05-26T18:18:05.911Z]
[2026-05-26T18:18:06.116Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T18:24:36.850Z] [API] Server running on port 3000
[2026-05-26T18:24:37.648Z] ────────────────────────────────────────────────────────
[2026-05-26T18:24:37.648Z] SupportBot
[2026-05-26T18:24:37.649Z] Emerald Services
[2026-05-26T18:24:37.649Z] ────────────────────────────────────────────────────────
[2026-05-26T18:24:37.649Z]
System
[2026-05-26T18:24:37.650Z] ------
[2026-05-26T18:24:37.650Z] Bot Name  SupportBo
[2026-05-26T18:24:37.650Z] Version  v26.3.0
[2026-05-26T18:24:37.651Z] Node.js  v24.14.1
[2026-05-26T18:24:37.651Z] Discord.js  v14.26.4
[2026-05-26T18:24:37.652Z] Logged in as  BLITZ#7183
[2026-05-26T18:24:37.652Z] Guilds  1
[2026-05-26T18:24:37.653Z]
Links
[2026-05-26T18:24:37.653Z] -----
[2026-05-26T18:24:37.654Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T18:24:37.654Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T18:24:37.656Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T18:24:37.659Z]
[2026-05-26T18:24:37.659Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T18:24:37.661Z]
Config Check
[2026-05-26T18:24:37.662Z] ------------
[2026-05-26T18:24:37.664Z] ✓ All configurations validated successfully
[2026-05-26T18:24:37.664Z]
[2026-05-26T18:24:37.857Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T18:27:00.991Z] [API] Server running on port 3000
[2026-05-26T18:27:01.875Z] ────────────────────────────────────────────────────────
[2026-05-26T18:27:01.876Z] SupportBot
[2026-05-26T18:27:01.876Z] Emerald Services
[2026-05-26T18:27:01.877Z] ────────────────────────────────────────────────────────
[2026-05-26T18:27:01.877Z]
System
[2026-05-26T18:27:01.878Z] ------
[2026-05-26T18:27:01.878Z] Bot Name  SupportBo
[2026-05-26T18:27:01.879Z] Version  v26.3.0
[2026-05-26T18:27:01.879Z] Node.js  v24.14.1
[2026-05-26T18:27:01.879Z] Discord.js  v14.26.4
[2026-05-26T18:27:01.880Z] Logged in as  BLITZ#7183
[2026-05-26T18:27:01.880Z] Guilds  1
[2026-05-26T18:27:01.881Z]
Links
[2026-05-26T18:27:01.881Z] -----
[2026-05-26T18:27:01.882Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T18:27:01.883Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T18:27:01.883Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T18:27:01.884Z]
[2026-05-26T18:27:01.885Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T18:27:01.886Z]
Config Check
[2026-05-26T18:27:01.888Z] ------------
[2026-05-26T18:27:01.890Z] ✓ All configurations validated successfully
[2026-05-26T18:27:01.891Z]
[2026-05-26T18:27:02.152Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T18:29:06.705Z] [API] Server running on port 3000
[2026-05-26T18:29:07.459Z] ────────────────────────────────────────────────────────
[2026-05-26T18:29:07.459Z] SupportBot
[2026-05-26T18:29:07.460Z] Emerald Services
[2026-05-26T18:29:07.460Z] ────────────────────────────────────────────────────────
[2026-05-26T18:29:07.461Z]
System
[2026-05-26T18:29:07.461Z] ------
[2026-05-26T18:29:07.462Z] Bot Name  SupportBo
[2026-05-26T18:29:07.462Z] Version  v26.3.0
[2026-05-26T18:29:07.462Z] Node.js  v24.14.1
[2026-05-26T18:29:07.462Z] Discord.js  v14.26.4
[2026-05-26T18:29:07.463Z] Logged in as  BLITZ#7183
[2026-05-26T18:29:07.463Z] Guilds  1
[2026-05-26T18:29:07.465Z]
Links
[2026-05-26T18:29:07.466Z] -----
[2026-05-26T18:29:07.466Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T18:29:07.467Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T18:29:07.467Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T18:29:07.468Z]
[2026-05-26T18:29:07.469Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T18:29:07.470Z]
Config Check
[2026-05-26T18:29:07.471Z] ------------
[2026-05-26T18:29:07.473Z] ✓ All configurations validated successfully
[2026-05-26T18:29:07.474Z]
[2026-05-26T18:29:07.656Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T18:30:31.130Z] [API] Server running on port 3000
[2026-05-26T18:31:30.298Z] [BotReload] Restarting Discord bot after config change…
[2026-05-26T18:31:31.048Z] ────────────────────────────────────────────────────────
[2026-05-26T18:31:31.050Z] SupportBot
[2026-05-26T18:31:31.054Z] Emerald Services
[2026-05-26T18:31:31.058Z] ────────────────────────────────────────────────────────
[2026-05-26T18:31:31.061Z]
System
[2026-05-26T18:31:31.066Z] ------
[2026-05-26T18:31:31.069Z] Bot Name  SupportBo
[2026-05-26T18:31:31.071Z] Version  v26.3.0
[2026-05-26T18:31:31.075Z] Node.js  v24.14.1
[2026-05-26T18:31:31.078Z] Discord.js  v14.26.4
[2026-05-26T18:31:31.082Z] Logged in as  BLITZ#7183
[2026-05-26T18:31:31.085Z] Guilds  1
[2026-05-26T18:31:31.091Z]
Links
[2026-05-26T18:31:31.097Z] -----
[2026-05-26T18:31:31.101Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T18:31:31.106Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T18:31:31.113Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T18:31:31.118Z]
[2026-05-26T18:31:31.123Z]
Config Check
[2026-05-26T18:31:31.127Z] ------------
[2026-05-26T18:31:31.134Z] ! Missing roles (1198295676128329799, 1198299671576195213, 1491881628065337404)
[2026-05-26T18:31:31.139Z] ! Missing channels (1290752269880660079)
[2026-05-26T18:31:31.142Z]
[2026-05-26T18:31:31.183Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T18:31:31.412Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T18:31:31.413Z] [BotReload] Bot restarted successfully
[2026-05-26T18:31:31.682Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T18:31:46.891Z] [API] Server running on port 3000
[2026-05-26T18:31:47.594Z] ────────────────────────────────────────────────────────
[2026-05-26T18:31:47.594Z] SupportBot
[2026-05-26T18:31:47.595Z] Emerald Services
[2026-05-26T18:31:47.595Z] ────────────────────────────────────────────────────────
[2026-05-26T18:31:47.596Z]
System
[2026-05-26T18:31:47.597Z] ------
[2026-05-26T18:31:47.597Z] Bot Name  SupportBo
[2026-05-26T18:31:47.598Z] Version  v26.3.0
[2026-05-26T18:31:47.598Z] Node.js  v24.14.1
[2026-05-26T18:31:47.599Z] Discord.js  v14.26.4
[2026-05-26T18:31:47.600Z] Logged in as  BLITZ#7183
[2026-05-26T18:31:47.600Z] Guilds  1
[2026-05-26T18:31:47.601Z]
Links
[2026-05-26T18:31:47.602Z] -----
[2026-05-26T18:31:47.602Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T18:31:47.603Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T18:31:47.604Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T18:31:47.604Z]
[2026-05-26T18:31:47.605Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T18:31:47.607Z]
Config Check
[2026-05-26T18:31:47.608Z] ------------
[2026-05-26T18:31:47.610Z] ✓ All configurations validated successfully
[2026-05-26T18:31:47.611Z]
[2026-05-26T18:32:31.812Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T18:34:34.091Z] [API] Server running on port 3000
[2026-05-26T18:35:12.583Z] [BotReload] Restarting Discord bot after config change…
[2026-05-26T18:35:13.391Z] ────────────────────────────────────────────────────────
[2026-05-26T18:35:13.391Z] SupportBot
[2026-05-26T18:35:13.392Z] Emerald Services
[2026-05-26T18:35:13.392Z] ────────────────────────────────────────────────────────
[2026-05-26T18:35:13.393Z]
System
[2026-05-26T18:35:13.393Z] ------
[2026-05-26T18:35:13.394Z] Bot Name  SupportBo
[2026-05-26T18:35:13.394Z] Version  v26.3.0
[2026-05-26T18:35:13.395Z] Node.js  v24.14.1
[2026-05-26T18:35:13.395Z] Discord.js  v14.26.4
[2026-05-26T18:35:13.395Z] Logged in as  BLITZ#7183
[2026-05-26T18:35:13.396Z] Guilds  1
[2026-05-26T18:35:13.396Z]
Links
[2026-05-26T18:35:13.397Z] -----
[2026-05-26T18:35:13.398Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T18:35:13.399Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T18:35:13.400Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T18:35:13.400Z]
[2026-05-26T18:35:13.401Z]
Config Check
[2026-05-26T18:35:13.402Z] ------------
[2026-05-26T18:35:13.403Z] ! Missing roles (1198295676128329799, 1198299671576195213, 1491881628065337404)
[2026-05-26T18:35:13.404Z] ! Missing channels (1290752269880660079)
[2026-05-26T18:35:13.404Z]
[2026-05-26T18:35:13.429Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T18:35:13.621Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T18:35:13.621Z] [BotReload] Bot restarted successfully
[2026-05-26T18:35:13.853Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T18:35:27.209Z] [API] Server running on port 3000
[2026-05-26T18:35:27.933Z] ────────────────────────────────────────────────────────
[2026-05-26T18:35:27.933Z] SupportBot
[2026-05-26T18:35:27.933Z] Emerald Services
[2026-05-26T18:35:27.934Z] ────────────────────────────────────────────────────────
[2026-05-26T18:35:27.934Z]
System
[2026-05-26T18:35:27.935Z] ------
[2026-05-26T18:35:27.935Z] Bot Name  SupportBo
[2026-05-26T18:35:27.936Z] Version  v26.3.0
[2026-05-26T18:35:27.936Z] Node.js  v24.14.1
[2026-05-26T18:35:27.937Z] Discord.js  v14.26.4
[2026-05-26T18:35:27.937Z] Logged in as  BLITZ#7183
[2026-05-26T18:35:27.938Z] Guilds  1
[2026-05-26T18:35:27.938Z]
Links
[2026-05-26T18:35:27.938Z] -----
[2026-05-26T18:35:27.939Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T18:35:27.940Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T18:35:27.940Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T18:35:27.941Z]
[2026-05-26T18:35:27.941Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T18:35:27.943Z]
Config Check
[2026-05-26T18:35:27.943Z] ------------
[2026-05-26T18:35:27.945Z] ✓ All configurations validated successfully
[2026-05-26T18:35:27.946Z]
[2026-05-26T18:36:14.082Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T19:00:20.564Z] [API] Server running on port 3000
[2026-05-26T19:01:08.704Z] [BotReload] Restarting Discord bot after config change…
[2026-05-26T19:01:09.362Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T19:01:09.365Z] ────────────────────────────────────────────────────────
[2026-05-26T19:01:09.366Z] SupportBot
[2026-05-26T19:01:09.366Z] Emerald Services
[2026-05-26T19:01:09.366Z] ────────────────────────────────────────────────────────
[2026-05-26T19:01:09.367Z]
System
[2026-05-26T19:01:09.367Z] ------
[2026-05-26T19:01:09.367Z] Bot Name  SupportBo
[2026-05-26T19:01:09.368Z] Version  v26.3.0
[2026-05-26T19:01:09.368Z] Node.js  v24.14.1
[2026-05-26T19:01:09.368Z] Discord.js  v14.26.4
[2026-05-26T19:01:09.369Z] Logged in as  BLITZ#7183
[2026-05-26T19:01:09.369Z] Guilds  1
[2026-05-26T19:01:09.370Z]
Links
[2026-05-26T19:01:09.371Z] -----
[2026-05-26T19:01:09.371Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T19:01:09.372Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T19:01:09.373Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T19:01:09.373Z]
[2026-05-26T19:01:09.375Z]
Guild
[2026-05-26T19:01:09.376Z] -----
[2026-05-26T19:01:09.377Z] ! Guild setup (No guild ID is set. Add your Discord server ID under Bot config → General.)
[2026-05-26T19:01:09.377Z]
[2026-05-26T19:01:09.378Z]
Config Check
[2026-05-26T19:01:09.378Z] ------------
[2026-05-26T19:01:09.379Z] ! Missing roles (ROLE_ID, ROLE_ID, ROLE_ID)
[2026-05-26T19:01:09.380Z] ! Missing channels (CHANNEL_ID)
[2026-05-26T19:01:09.381Z]
[2026-05-26T19:01:09.547Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T19:01:09.923Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T19:01:09.923Z] [BotReload] Bot restarted successfully
[2026-05-26T19:01:44.692Z] [API] Server running on port 3000
[2026-05-26T19:01:45.455Z] ────────────────────────────────────────────────────────
[2026-05-26T19:01:45.455Z] SupportBot
[2026-05-26T19:01:45.456Z] Emerald Services
[2026-05-26T19:01:45.456Z] ────────────────────────────────────────────────────────
[2026-05-26T19:01:45.457Z]
System
[2026-05-26T19:01:45.457Z] ------
[2026-05-26T19:01:45.458Z] Bot Name  SupportBo
[2026-05-26T19:01:45.458Z] Version  v26.3.0
[2026-05-26T19:01:45.458Z] Node.js  v24.14.1
[2026-05-26T19:01:45.459Z] Discord.js  v14.26.4
[2026-05-26T19:01:45.459Z] Logged in as  BLITZ#7183
[2026-05-26T19:01:45.460Z] Guilds  1
[2026-05-26T19:01:45.462Z]
Links
[2026-05-26T19:01:45.462Z] -----
[2026-05-26T19:01:45.463Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T19:01:45.464Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T19:01:45.466Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T19:01:45.467Z]
[2026-05-26T19:01:45.468Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T19:01:45.469Z]
Guild
[2026-05-26T19:01:45.470Z] -----
[2026-05-26T19:01:45.471Z] ! Guild setup (No guild ID is set. Add your Discord server ID under Bot config → General.)
[2026-05-26T19:01:45.471Z]
[2026-05-26T19:01:45.471Z]
Config Check
[2026-05-26T19:01:45.472Z] ------------
[2026-05-26T19:01:45.473Z] ! Missing roles (ROLE_ID, ROLE_ID, ROLE_ID)
[2026-05-26T19:01:45.474Z] ! Missing channels (CHANNEL_ID)
[2026-05-26T19:01:45.474Z]
[2026-05-26T19:01:45.807Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T19:05:40.700Z] [API] Server running on port 3000
[2026-05-26T19:05:41.522Z] ────────────────────────────────────────────────────────
[2026-05-26T19:05:41.522Z] SupportBot
[2026-05-26T19:05:41.523Z] Emerald Services
[2026-05-26T19:05:41.523Z] ────────────────────────────────────────────────────────
[2026-05-26T19:05:41.524Z]
System
[2026-05-26T19:05:41.524Z] ------
[2026-05-26T19:05:41.524Z] Bot Name  SupportBo
[2026-05-26T19:05:41.525Z] Version  v26.3.0
[2026-05-26T19:05:41.525Z] Node.js  v24.14.1
[2026-05-26T19:05:41.525Z] Discord.js  v14.26.4
[2026-05-26T19:05:41.526Z] Logged in as  BLITZ#7183
[2026-05-26T19:05:41.526Z] Guilds  1
[2026-05-26T19:05:41.527Z]
Links
[2026-05-26T19:05:41.527Z] -----
[2026-05-26T19:05:41.528Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T19:05:41.528Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T19:05:41.529Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T19:05:41.530Z]
[2026-05-26T19:05:41.534Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T19:05:41.537Z]
Guild
[2026-05-26T19:05:41.537Z] -----
[2026-05-26T19:05:41.538Z] ! Guild setup (No guild ID is set. Add your Discord server ID under Bot config → General.)
[2026-05-26T19:05:41.539Z]
[2026-05-26T19:05:41.539Z]
Config Check
[2026-05-26T19:05:41.540Z] ------------
[2026-05-26T19:05:41.542Z] ! Missing roles (ROLE_ID, ROLE_ID, ROLE_ID)
[2026-05-26T19:05:41.543Z] ! Missing channels (CHANNEL_ID)
[2026-05-26T19:05:41.543Z]
[2026-05-26T19:05:41.761Z]
✓ Slash Commands Registered for Char's Test Server
[2026-05-26T19:07:41.900Z] [API] Server running on port 3000
[2026-05-26T19:07:42.738Z] ────────────────────────────────────────────────────────
[2026-05-26T19:07:42.739Z] SupportBot
[2026-05-26T19:07:42.739Z] Emerald Services
[2026-05-26T19:07:42.739Z] ────────────────────────────────────────────────────────
[2026-05-26T19:07:42.740Z]
System
[2026-05-26T19:07:42.740Z] ------
[2026-05-26T19:07:42.741Z] Bot Name  SupportBo
[2026-05-26T19:07:42.741Z] Version  v26.3.0
[2026-05-26T19:07:42.741Z] Node.js  v24.14.1
[2026-05-26T19:07:42.742Z] Discord.js  v14.26.4
[2026-05-26T19:07:42.742Z] Logged in as  BLITZ#7183
[2026-05-26T19:07:42.743Z] Guilds  1
[2026-05-26T19:07:42.743Z]
Links
[2026-05-26T19:07:42.744Z] -----
[2026-05-26T19:07:42.745Z] Docs  https://emerald-services.gitbook.io/
[2026-05-26T19:07:42.745Z] Discord  https://dsc.gg/emerald-dev
[2026-05-26T19:07:42.746Z] Invite  https://discord.com/api/oauth2/authorize?client_id=1289713673123922032&permissions=8&scope=bot%20applications.commands
[2026-05-26T19:07:42.746Z]
[2026-05-26T19:07:42.747Z] [Dashboard] Discord bot is ready — full stats and guild tools are available
[2026-05-26T19:07:42.748Z]
Guild
[2026-05-26T19:07:42.751Z] -----
[2026-05-26T19:07:42.752Z] ! Guild setup (No guild ID is set. Add your Discord server ID under Bot config → General.)
[2026-05-26T19:07:42.752Z]
[2026-05-26T19:07:42.753Z]
Config Check
[2026-05-26T19:07:42.753Z] ------------
[2026-05-26T19:07:42.756Z] ! Missing roles (ROLE_ID, ROLE_ID, ROLE_ID)
[2026-05-26T19:07:42.756Z] ! Missing channels (CHANNEL_ID)
[2026-05-26T19:07:42.757Z]
[2026-05-26T19:07:42.952Z]
✓ Slash Commands Registered for Char's Test Server
+170 -45
View File
@@ -40,58 +40,183 @@
</div>
<p align="center">
<a href="https://emeraldsrv.com/">Website</a>
•
<a href="https://github.com/Emerald-Services/SupportBot/wiki">Wiki</a>
<br>
<a href="#about">About</a>
•
<a href="#support">Support</a>
•
<a href="#license">License</a>
•
<a href="https://github.com/Emerald-Services/SupportBot/wiki/Third-Party-Developer">Third-Party</a>
•
<a href="#contributors">Contributors</a>
<a href="https://opensource.org/licenses/MIT">
<img src="https://img.shields.io/badge/license-MIT-green?style=for-the-badge" alt="MIT License">
</a>
<a href="https://github.com/discordjs/discord.js">
<img src="https://img.shields.io/badge/discord.js-v14-blue?style=for-the-badge" alt="discord.js v14">
</a>
<a href="https://nodejs.org/">
<img src="https://img.shields.io/badge/node.js-22.x-green?style=for-the-badge" alt="Node.js 22.x">
</a>
<a href="https://github.com/Emerald-Services/SupportBot">
<img src="https://img.shields.io/badge/upstream-SupportBot-purple?style=for-the-badge" alt="Upstream SupportBot">
</a>
</p>
<p align="center">
<a href="#about">About</a> ·
<a href="#features">Features</a> ·
<a href="#requirements">Requirements</a> ·
<a href="#getting-started">Getting started</a> ·
<a href="#dashboard-access">Dashboard access</a> ·
<a href="#configuration">Configuration</a> ·
<a href="#addons">Addons</a> ·
<a href="#development">Development</a> ·
<a href="#upstream--credits">Upstream & credits</a> ·
<a href="#license">License</a>
</p>
---
## About
SupportBot is an Open-Source discord bot built with [discord.js](https://github.com/discordjs/discord.js). It's primarily focused to help servers organise and manage their support system in a unique way with full customisation to match your brand.
This repository is a **community fork** of [SupportBot](https://github.com/Emerald-Services/SupportBot) — the open-source Discord support/ticket bot by [Emerald Services](https://emeraldsrv.dev). It is **not** affiliated with or endorsed by Emerald Services.
## Support
What this fork adds is a **self-hosted dashboard**: a modern web UI and REST API that run in the **same Node process** as the bot. You configure tickets, messages, commands, AI settings, addons, and more from the browser instead of editing YAML by hand. The API starts immediately on launch, so the dashboard stays reachable even while the bot is connecting or restarting.
<a href="https://emeraldsrv.com/discord">
<img alt="Discord" src="https://img.shields.io/discord/597779408295821323?logo=discord&logoColor=white&style=for-the-badge">
</a>
If you only need the original bot without the dashboard, use the [official SupportBot repository](https://github.com/Emerald-Services/SupportBot).
## Features
### Self-hosted dashboard
| Area | What you get |
|------|----------------|
| **Overview** | Live stats — servers, members, open/closed tickets, module setup status, RAM/CPU/uptime |
| **Visual config editors** | Edit `supportbot`, ticket panel, commands, messages, and AI config with form fields instead of raw YAML |
| **Discord pickers** | Choose channels, roles, and categories from dropdowns when configuring the bot (no copy-pasting IDs) |
| **Guild health** | Warnings if the bot is in the wrong server or extra guilds; quick link to fix `GuildId` or leave stray servers |
| **Logs** | Browse Output, Warn, and Error logs from the dashboard |
| **Transcripts** | View saved ticket HTML transcripts |
| **Notifications** | In-app alerts for bot restarts, update checks, and installs |
| **Settings** | Check for dashboard updates and apply them from the UI |
| **Users & roles** | Invite staff via Discord OAuth; assign owner, admin, editor, viewer, or custom per-page permissions |
| **Addons** | Browse and install addons from the [official Addons repo](https://github.com/Emerald-Services/Addons); edit addon configs in the sidebar like other config files |
### Bot & API (unchanged upstream behaviour, plus improvements)
- Full **SupportBot v26** ticket system, slash commands, AI assistant, and addon support
- **Discord OAuth** login for the dashboard (no shared API secret in the browser)
- **API key** (`SecretKey` in `api.yml`) still works for automation and scripts
- Config saves can **restart the Discord bot** while keeping the dashboard and API online
- Timeouts and caching so the UI does not hang when Discord or GitHub is slow
## Requirements
| Component | Version |
|-----------|---------|
| **Node.js** | 22.x (matches [SupportBot 8.x](https://github.com/Emerald-Services/SupportBot)) |
| **discord.js** | 14.x (installed via `package.json`) |
| **Discord bot** | Application with bot token and required intents |
| **Discord OAuth app** | For dashboard login (optional but recommended) |
You need a machine or VPS that can run Node and reach Discord’s API (and GitHub, if you use in-dashboard updates or the addon marketplace).
## Getting started
### 1. Clone and install
```bash
git clone https://github.com/C-h-a-r/SupportBot-Dashboard.git
cd SupportBot-Dashboard
npm install
```
### 2. Configure the bot
Edit `Configs/supportbot.yml`:
- Set `General.Token` to your bot token
- Set `General.GuildId` to your Discord server ID
- Enable addons if you use them: `General.Addons.Enabled: true`
Other YAML files in `Configs/` can stay at defaults until you open the dashboard.
### 3. Configure the API & dashboard
Edit `Configs/api.yml`:
```yaml
API:
Enabled: true
Port: 3000
SecretKey: "generate-a-long-random-string"
OAuth:
Enabled: true
ClientId: "YOUR_DISCORD_APP_CLIENT_ID"
ClientSecret: "YOUR_DISCORD_APP_CLIENT_SECRET"
RedirectUri: "http://localhost:3000/api/auth/discord/callback"
OwnerUserIds:
- "YOUR_DISCORD_USER_ID"
```
**Discord Developer Portal**
1. Create an application at [discord.com/developers/applications](https://discord.com/developers/applications)
2. Under **OAuth2 → Redirects**, add your callback URL(s). If users may sign in over **both** HTTP and HTTPS, register **both** (same host/path, different protocol), e.g. `http://bot.example.com/api/auth/discord/callback` and `https://bot.example.com/api/auth/discord/callback`.
3. Use the same app’s **Client ID** and **Client Secret** in `api.yml`
4. Put your Discord user ID in `OwnerUserIds` for full dashboard access
Set `RedirectUri` to your usual URL (host and path). By default, `UseRequestOrigin` keeps the **same protocol** as the page you opened (http vs https). Behind a reverse proxy, set `TrustProxy: 1` so forwarded `X-Forwarded-Proto` is respected.
### 4. Start the bot
```bash
npm start
```
When startup succeeds you should see:
- `[Dashboard] API listening on http://localhost:3000`
- Discord bot login and slash command registration
Open **http://localhost:3000** in your browser and sign in with Discord.
The web UI is shipped as static files in `public/dashboard/` (included in this repository). You do not need a separate frontend build step.
> **Tip:** On first run, invite the bot to your server with the permissions SupportBot needs. Set `General.GuildId` to that server’s ID so channel/role pickers and guild health checks work.
## Dashboard access
| Method | Use case |
|--------|----------|
| **Discord OAuth** | Normal use — open the site, click **Continue with Discord**, sign in as an owner or invited user |
| **Bearer token** | Scripts and automation — `Authorization: Bearer <SecretKey>` on `/api/*` routes |
Owners listed in `api.yml` (`OwnerUserIds`) always have full access. Additional users can be added under **Users** in the dashboard with granular permissions per config file and page.
## Configuration
| File | Purpose |
|------|---------|
| `Configs/supportbot.yml` | Bot token, guild, staff roles, ticket channels, embed colours, etc. |
| `Configs/ticket-panel.yml` | Ticket panel layout and buttons |
| `Configs/commands.yml` | Enable/disable slash commands |
| `Configs/messages.yml` | User-facing message strings |
| `Configs/supportbot-ai.yml` | AI assistant settings |
| `Configs/api.yml` | Dashboard port, session secret, OAuth |
| `Addons/Configs/*` | Per-addon config (after installing from **Addons** page) |
Most of these are editable from the sidebar under **Tickets & support**, **Community**, **Server control**, and **Addons**.
## Addons
1. Open **Addons** in the dashboard (or install manually into `Addons/` as in the [upstream docs](https://github.com/Emerald-Services/Addons))
2. Click **Install** on an addon from the marketplace — files are copied into `Addons/` and `Addons/Configs/`, then the bot restarts
3. Edit the addon’s config from the **Addons** section in the left sidebar (same editor as core configs)
4. Ensure `General.Addons.Enabled` is `true` in bot config
Official addon list: [github.com/Emerald-Services/Addons](https://github.com/Emerald-Services/Addons)
## Upstream & credits
- **Original project:** [Emerald-Services/SupportBot](https://github.com/Emerald-Services/SupportBot) — MIT license, ticket bot for Discord
- **Official addons:** [Emerald-Services/Addons](https://github.com/Emerald-Services/Addons)
- **Community:** [Emerald Discord](https://emeraldsrv.dev/discord) · [Wiki](https://github.com/Emerald-Services/SupportBot/wiki)
This fork is maintained independently. For bugs in **core ticket/command behaviour** that also exist upstream, consider reporting to the [official repo](https://github.com/Emerald-Services/SupportBot/issues). For **dashboard-specific** issues, use this repository’s issues.
## License
Released under the [MIT](https://opensource.org/licenses/MIT) license.
## Third-Party
- [Official addons repository](https://github.com/Emerald-Services/Addons/)
- [Syphers Addons](https://github.com/SypherRed/SB_Addons_Unofficial)
- [BuiltByBit]([https://builtbybit.com/supportbot](https://builtbybit.com/resources/supportbot-advanced-ticket-bot.8940/))
- [Polymart](https://polymart.org/resource/supportbot-1-discord-ticket-bot.518)
## Contributors
<a href="https://github.com/Emerald-Services/SupportBot/graphs/contributors">
<img src="https://contrib.rocks/image?repo=Emerald-Services/SupportBot">
</a>
## Hosting
You can use our [Pterodactyl egg](https://github.com/Emerald-Services/Pterodactyl-Egg) to host it on your own panel. We currently don't offer hosting for you, altough we might add this in the future.
If you don't know how to install pterodactyl, you could always host it on replit:
[![Run on Repl.it](https://repl.it/badge/github/ItsNyoty/IKI-bot)]([https://repl.it/github/ItsNyoty/iki](https://repl.it/github/Emerald-Services/SupportBot
)
Released under the [MIT License](https://opensource.org/licenses/MIT), same as upstream SupportBot.
+270
View File
@@ -0,0 +1,270 @@
const fs = require("fs");
const path = require("path");
const axios = require("axios");
const { withTimeout } = require("./asyncTimeout.js");
const ADDONS_REPO = "Emerald-Services/Addons";
const ADDONS_BRANCH = "main";
const GITHUB_API = `https://api.github.com/repos/${ADDONS_REPO}/contents`;
const GITHUB_RAW = `https://raw.githubusercontent.com/${ADDONS_REPO}/${ADDONS_BRANCH}`;
const README_PATTERN = /^readme\.md$/i;
function ensureAddonDirs() {
if (!fs.existsSync("./Addons")) {
fs.mkdirSync("./Addons", { recursive: true });
}
if (!fs.existsSync("./Addons/Configs")) {
fs.mkdirSync("./Addons/Configs", { recursive: true });
}
}
async function githubList(dirPath = "") {
const url = dirPath
? `${GITHUB_API}/${encodeURIComponent(dirPath)}?ref=${ADDONS_BRANCH}`
: `${GITHUB_API}?ref=${ADDONS_BRANCH}`;
const res = await withTimeout(
axios.get(url, {
headers: { Accept: "application/vnd.github+json" },
timeout: 15_000,
}),
18_000,
"GitHub API request timed out",
);
return res.data;
}
async function listCatalogAddons() {
const root = await githubList("");
const dirs = root.filter((entry) => entry.type === "dir");
const addons = [];
for (const dir of dirs) {
const summary = await summarizeAddon(dir.name);
if (summary) addons.push(summary);
}
return addons.sort((a, b) => a.name.localeCompare(b.name));
}
async function summarizeAddon(name) {
const files = await listAddonRepoFiles(name);
const jsFiles = files.filter((f) => f.name.endsWith(".js"));
if (jsFiles.length === 0) return null;
const configFiles = files
.filter((f) => f.relativePath.startsWith("Configs/"))
.map((f) => f.name);
const readme = files.find((f) => README_PATTERN.test(f.name));
return {
id: name,
name,
description: readme
? `Community addon from Emerald-Services/Addons`
: `Addon from ${name}`,
repositoryUrl: `https://github.com/${ADDONS_REPO}/tree/${ADDONS_BRANCH}/${name}`,
jsFiles: jsFiles.map((f) => f.name),
configFiles,
fileCount: files.length,
};
}
async function listAddonRepoFiles(addonName) {
const files = [];
const queue = [addonName];
while (queue.length) {
const dir = queue.shift();
const entries = await githubList(dir);
for (const entry of entries) {
if (entry.type === "dir") {
queue.push(entry.path);
continue;
}
if (entry.type !== "file") continue;
if (README_PATTERN.test(entry.name)) continue;
const relativePath = entry.path.slice(`${addonName}/`.length);
files.push({
name: entry.name,
path: entry.path,
relativePath,
downloadUrl: entry.download_url,
size: entry.size,
});
}
}
return files;
}
function mapRepoFileToLocal(addonName, relativePath) {
const parts = relativePath.split("/").filter(Boolean);
if (parts[0] === "Configs") {
return path.join("Addons", "Configs", ...parts.slice(1));
}
if (parts.length === 1 && parts[0].endsWith(".js")) {
return path.join("Addons", parts[0]);
}
return path.join("Addons", ...parts);
}
async function downloadFile(url) {
const res = await withTimeout(
axios.get(url, { responseType: "arraybuffer", timeout: 30_000 }),
35_000,
"Addon file download timed out",
);
return Buffer.from(res.data);
}
function listLocalAddonJs() {
ensureAddonDirs();
return fs
.readdirSync("./Addons")
.filter((f) => f.endsWith(".js") && f !== "addon.js");
}
function listLocalAddonConfigs() {
ensureAddonDirs();
const dir = "./Addons/Configs";
if (!fs.existsSync(dir)) return [];
return fs
.readdirSync(dir)
.filter((f) => f.endsWith(".yml") || f.endsWith(".yaml") || f.endsWith(".json"));
}
function isAddonInstalled(catalogEntry) {
const localJs = listLocalAddonJs();
return catalogEntry.jsFiles.every((file) => localJs.includes(file));
}
async function listInstalledAddons(catalog) {
const localJs = listLocalAddonJs();
const installed = [];
for (const entry of catalog) {
const allPresent = entry.jsFiles.every((file) => localJs.includes(file));
if (allPresent) {
installed.push({
id: entry.id,
name: entry.name,
jsFiles: entry.jsFiles,
configFiles: entry.configFiles.filter((f) => {
const local = listLocalAddonConfigs();
return local.includes(f);
}),
});
}
}
const orphanJs = localJs.filter(
(file) => !installed.some((a) => a.jsFiles.includes(file)),
);
for (const file of orphanJs) {
installed.push({
id: file.replace(/\.js$/, ""),
name: file.replace(/\.js$/, ""),
jsFiles: [file],
configFiles: [],
custom: true,
});
}
return installed;
}
async function installAddonFromCatalog(addonName) {
const safeName = String(addonName).replace(/[^a-zA-Z0-9_-]/g, "");
if (!safeName) {
throw new Error("Invalid addon name");
}
const summary = await summarizeAddon(safeName);
if (!summary) {
throw new Error(`Addon "${safeName}" was not found in the catalog`);
}
const files = await listAddonRepoFiles(safeName);
if (files.length === 0) {
throw new Error(`Addon "${safeName}" has no installable files`);
}
ensureAddonDirs();
const written = [];
for (const file of files) {
const localPath = mapRepoFileToLocal(safeName, file.relativePath);
const dir = path.dirname(localPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const content = await downloadFile(file.downloadUrl);
fs.writeFileSync(localPath, content);
written.push(localPath.replace(/\\/g, "/"));
}
return {
addon: summary,
filesWritten: written,
};
}
function readAddonConfig(filename) {
const safe = path.basename(filename);
if (!/^[a-zA-Z0-9_.-]+\.(yml|yaml|json)$/.test(safe)) {
throw new Error("Invalid config filename");
}
const filePath = path.join("./Addons/Configs", safe);
if (!fs.existsSync(filePath)) {
throw new Error("Addon config not found");
}
const raw = fs.readFileSync(filePath, "utf8");
if (safe.endsWith(".json")) {
return { filename: safe, format: "json", data: JSON.parse(raw), raw };
}
const yaml = require("js-yaml");
return { filename: safe, format: "yaml", data: yaml.load(raw) || {}, raw };
}
function writeAddonConfig(filename, data) {
const safe = path.basename(filename);
if (!/^[a-zA-Z0-9_.-]+\.(yml|yaml|json)$/.test(safe)) {
throw new Error("Invalid config filename");
}
ensureAddonDirs();
const filePath = path.join("./Addons/Configs", safe);
let content;
if (safe.endsWith(".json")) {
content = `${JSON.stringify(data, null, 2)}\n`;
} else {
const yaml = require("js-yaml");
content = yaml.dump(data, { lineWidth: 120, noRefs: true });
}
fs.writeFileSync(filePath, content);
return { filename: safe, path: filePath.replace(/\\/g, "/") };
}
module.exports = {
ADDONS_REPO,
listCatalogAddons,
listInstalledAddons,
isAddonInstalled,
installAddonFromCatalog,
listLocalAddonConfigs,
readAddonConfig,
writeAddonConfig,
mapRepoFileToLocal,
};
+6
View File
@@ -0,0 +1,6 @@
function getBotInviteUrl(clientId) {
if (!clientId) return null;
return `https://discord.com/api/oauth2/authorize?client_id=${clientId}&permissions=8&scope=bot%20applications.commands`;
}
module.exports = { getBotInviteUrl };
+150
View File
@@ -0,0 +1,150 @@
const fs = require("fs");
const path = require("path");
const configStore = require("./ConfigStore.js");
const { getPrimaryGuild } = require("./GuildManager.js");
const {
applyPresence,
runBotReady,
logSlashCommandsRegistered,
} = require("./BotStartup.js");
function walk(dir, ext = ".js", fileList = []) {
if (!fs.existsSync(dir)) return fileList;
for (const file of fs.readdirSync(dir)) {
const full = path.join(dir, file);
if (fs.statSync(full).isDirectory()) {
walk(full, ext, fileList);
} else if (file.endsWith(ext)) {
fileList.push(full.replace(/\\/g, "/"));
}
}
return fileList;
}
async function refreshSlashCommands(client) {
if (!client?.application) return { count: 0 };
const cmdconfig = configStore.commands;
const commandFiles = walk("./Commands");
client.commands.clear();
for (const file of commandFiles) {
const resolved = path.resolve(file);
if (require.cache[resolved]) {
delete require.cache[resolved];
}
}
let count = 0;
for (const file of commandFiles) {
const command = require(path.resolve(file));
const matchingConfig = Object.values(cmdconfig).find(
(entry) =>
entry &&
typeof entry === "object" &&
entry.Command &&
String(entry.Command).toLowerCase() ===
String(command.name).toLowerCase(),
);
if (matchingConfig && matchingConfig.Enabled === false) {
continue;
}
client.commands.set(command.name, command);
count++;
}
const payload = client.commands.map((cmd) => cmd.data ?? cmd);
for (const guild of client.guilds.cache.values()) {
await guild.commands.set(payload);
}
return { count };
}
async function reloadBot(client, options = {}) {
const { fileKey, refreshCommands = true } = options;
let reloaded;
if (fileKey) {
configStore.reloadFile(fileKey);
reloaded = [fileKey];
} else {
reloaded = configStore.reloadBotConfigs();
}
applyPresence(client);
let commands = null;
if (refreshCommands && (!fileKey || fileKey === "commands")) {
commands = await refreshSlashCommands(client);
}
return {
reloaded,
commands,
};
}
/**
* Reload configs from disk, reconnect the Discord session, and refresh presence/commands.
* API and dashboard keep running on the same process.
*/
async function restartDiscordBot(client) {
if (!client) {
const err = new Error("Bot client not available");
err.code = "NO_CLIENT";
throw err;
}
const reloaded = configStore.reloadBotConfigs();
const token = configStore.supportbot?.General?.Token;
if (!token || String(token).trim() === "" || token === "BOT_TOKEN") {
const err = new Error("Invalid or missing bot token in supportbot.yml");
err.code = "INVALID_TOKEN";
throw err;
}
console.log("[BotReload] Restarting Discord bot after config change…");
client.__restarting = true;
if (client.user) {
try {
await client.destroy();
} catch (destroyErr) {
console.warn("[BotReload] destroy:", destroyErr.message);
}
}
client.__explicitStartup = true;
try {
try {
await client.login(token);
} catch (loginErr) {
console.error("[BotReload] login failed:", loginErr.message);
const err = new Error(`Could not start bot: ${loginErr.message}`);
err.code = "LOGIN_FAILED";
throw err;
}
// clientReady does not fire again after destroy()+login() — run startup explicitly
await runBotReady(client, { clearConsole: true, logCommands: false });
const commands = await refreshSlashCommands(client);
logSlashCommandsRegistered(client);
console.log("[BotReload] Bot restarted successfully");
return { restarted: true, reloaded, commands };
} finally {
client.__explicitStartup = false;
client.__restarting = false;
}
}
module.exports = {
applyPresence,
refreshSlashCommands,
reloadBot,
restartDiscordBot,
};
+174
View File
@@ -0,0 +1,174 @@
const Discord = require("discord.js");
const configStore = require("./ConfigStore.js");
const {
getPrimaryGuild,
syncGuildHealth,
} = require("./GuildManager.js");
const ACTIVITY_TYPES = {
PLAYING: Discord.ActivityType.Playing,
WATCHING: Discord.ActivityType.Watching,
LISTENING: Discord.ActivityType.Listening,
COMPETING: Discord.ActivityType.Competing,
STREAMING: Discord.ActivityType.Streaming,
};
function applyPresence(client) {
if (!client?.user) return;
const activity = configStore.supportbot?.Activity;
const typeKey = activity?.Type?.toUpperCase();
const type = ACTIVITY_TYPES[typeKey] ?? Discord.ActivityType.Playing;
const name = activity?.Status || "Online";
const activityPayload = { name, type };
if (typeKey === "STREAMING" && activity?.StreamingURL) {
activityPayload.url = activity.StreamingURL;
}
client.user.setPresence({
activities: [activityPayload],
status: "online",
});
}
const c = {
reset: "\x1b[0m",
gray: "\x1b[90m",
green: "\x1b[32m",
yellow: "\x1b[33m",
bold: "\x1b[1m",
white: "\x1b[37m",
};
function line() {
console.log(
`${c.gray}────────────────────────────────────────────────────────${c.reset}`,
);
}
function section(title) {
console.log(`\n${c.green}${title}${c.reset}`);
console.log(`${c.gray}${"-".repeat(title.length)}${c.reset}`);
}
function info(label, value) {
console.log(`${c.gray}${label.padEnd(14)}${c.reset} ${value}`);
}
function status(label, ok, details = "") {
const icon = ok ? `${c.green}✓${c.reset}` : `${c.yellow}!${c.reset}`;
console.log(` ${icon} ${label}${details ? ` (${details})` : ""}`);
}
async function logStartup(client, options = {}) {
const { clearConsole = true } = options;
const supportbot = configStore.supportbot;
if (clearConsole) {
console.clear();
}
const botName = supportbot?.General?.Name || "SupportBot";
const botVersion = supportbot?.SupportBot_Version || "Unknown";
const { getBotInviteUrl } = require("./BotInvite.js");
const inviteUrl = getBotInviteUrl(client.user.id);
line();
console.log(`${c.bold}${c.green}SupportBot${c.reset}`);
console.log(`${c.gray}Emerald Services${c.reset}`);
line();
section("System");
info("Bot Name", botName);
info("Version", botVersion);
info("Node.js", process.version);
info("Discord.js", `v${Discord.version}`);
info("Logged in as", client.user.tag);
info("Guilds", `${client.guilds.cache.size}`);
section("Links");
info("Docs", "https://emerald-services.gitbook.io/");
info("Discord", "https://dsc.gg/emerald-dev");
info("Invite", inviteUrl);
console.log("");
}
async function checkConfigs(client) {
const supportbot = configStore.supportbot;
const health = syncGuildHealth(client);
if (health.status !== "ok") {
section("Guild");
status("Guild setup", false, health.message || health.status);
console.log("");
}
const guild = getPrimaryGuild(client);
if (!guild) return;
section("Config Check");
const roles = [
supportbot?.Roles?.StaffMember?.Admin,
supportbot?.Roles?.StaffMember?.Staff,
supportbot?.Roles?.AutoRole?.Role,
].filter(Boolean);
const channels = [supportbot?.Ticket?.TicketHome].filter(Boolean);
const [roleResults, channelResults] = await Promise.all([
Promise.all(roles.map((role) => client.getRole(role, guild))),
Promise.all(channels.map((channel) => client.getChannel(channel, guild))),
]);
const missingRoles = roles.filter((_, i) => !roleResults[i]);
const missingChannels = channels.filter((_, i) => !channelResults[i]);
if (!missingRoles.length && !missingChannels.length) {
status("All configurations validated successfully", true);
} else {
if (missingRoles.length) {
status("Missing roles", false, missingRoles.join(", "));
}
if (missingChannels.length) {
status("Missing channels", false, missingChannels.join(", "));
}
}
console.log("");
}
function logSlashCommandsRegistered(client) {
const guild = getPrimaryGuild(client);
if (!guild) return;
console.log(
`\n${c.green}✓${c.reset} ${c.white}Slash Commands Registered${c.reset} ${c.gray}for ${guild.name}${c.reset}`,
);
}
/**
* Same work as Events/ready.js — safe to call after config reload reconnects.
*/
async function runBotReady(client, options = {}) {
const { clearConsole = true, logCommands = false } = options;
syncGuildHealth(client);
applyPresence(client);
await logStartup(client, { clearConsole });
await checkConfigs(client);
if (logCommands) {
logSlashCommandsRegistered(client);
}
}
module.exports = {
applyPresence,
logStartup,
checkConfigs,
logSlashCommandsRegistered,
runBotReady,
};
+11 -9
View File
@@ -2,11 +2,12 @@ const fs = require("fs");
const path = require("path");
const Discord = require("discord.js");
const { GatewayIntentBits, Partials } = require("discord.js");
const yaml = require("js-yaml");
const { Command, Event } = require("./Addon.js");
const configStore = require("./ConfigStore.js");
const { getPrimaryGuild } = require("./GuildManager.js");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const supportbot = configStore.supportbot;
const cmdconfig = configStore.commands;
const c = {
reset: "\x1b[0m",
@@ -50,6 +51,7 @@ class Client extends Discord.Client {
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.MessageContent,
],
partials: [Partials.Message, Partials.Channel, Partials.Reaction],
@@ -158,12 +160,12 @@ class Client extends Discord.Client {
});
}
this.once("clientReady", async () => {
await this.guilds.cache.first()?.commands.set(this.commands);
console.log(
`\n${c.green}✓${c.reset} ${c.white}Slash Commands Registered${c.reset} ${c.gray}for ${this.guilds.cache.first().name}${c.reset}`,
);
this.on("clientReady", async () => {
const guild = getPrimaryGuild(this);
if (!guild) return;
await guild.commands.set(this.commands);
const { logSlashCommandsRegistered } = require("./BotStartup.js");
logSlashCommandsRegistered(this);
});
section("Events");
+89
View File
@@ -0,0 +1,89 @@
// Live config objects — reload mutates in place so existing references stay valid.
const fs = require("fs");
const path = require("path");
const yaml = require("js-yaml");
const CONFIG_DIR = path.join(__dirname, "../Configs");
const FILE_KEYS = [
"supportbot",
"commands",
"messages",
"ticket-panel",
"supportbot-ai",
"api",
];
function readConfig(name) {
return yaml.load(fs.readFileSync(path.join(CONFIG_DIR, `${name}.yml`), "utf8"));
}
function deepAssign(target, source) {
if (!target || typeof target !== "object" || Array.isArray(target)) {
return source;
}
if (!source || typeof source !== "object" || Array.isArray(source)) {
return source;
}
for (const key of Object.keys(source)) {
const next = source[key];
if (
next &&
typeof next === "object" &&
!Array.isArray(next) &&
target[key] &&
typeof target[key] === "object" &&
!Array.isArray(target[key])
) {
deepAssign(target[key], next);
} else {
target[key] = next;
}
}
for (const key of Object.keys(target)) {
if (!(key in source)) {
delete target[key];
}
}
return target;
}
const store = {};
for (const name of FILE_KEYS) {
store[name] = readConfig(name);
}
function reloadFile(fileKey) {
if (!FILE_KEYS.includes(fileKey)) {
throw new Error(`Unknown config: ${fileKey}`);
}
const fresh = readConfig(fileKey);
deepAssign(store[fileKey], fresh);
return store[fileKey];
}
function reloadBotConfigs() {
const reloaded = [];
for (const name of FILE_KEYS) {
if (name === "api") continue;
reloadFile(name);
reloaded.push(name);
}
return reloaded;
}
module.exports = {
supportbot: store.supportbot,
commands: store.commands,
messages: store.messages,
ticketPanel: store["ticket-panel"],
supportbotAi: store["supportbot-ai"],
api: store.api,
store,
reloadFile,
reloadBotConfigs,
readConfig,
};
+229
View File
@@ -0,0 +1,229 @@
/**
* Dashboard alert registry — server-side providers for actionable banners.
*
* Register a provider to surface new alerts anywhere in the dashboard:
*
* const { dashboardAlerts } = require("./DashboardAlerts.js");
* dashboardAlerts.register("my-addon", (ctx) => {
* if (!ctx.configStore.myAddon?.Configured) {
* return [{
* id: "my-addon:setup",
* severity: "warning",
* category: "my-addon",
* title: "My addon needs setup",
* message: "Finish configuration to enable this feature.",
* action: { label: "Configure", href: "/configs?file=my-addon" },
* }];
* }
* return [];
* });
*/
const { evaluateGuildHealth } = require("./GuildManager.js");
const { evaluateAllModules } = require("./ModuleStatus.js");
const SEVERITY_ORDER = { error: 0, warning: 1, info: 2 };
const MODULE_LINKS = {
tickets: {
title: "Ticket system",
href: "/configs?file=ticket-panel",
},
supportbot: {
title: "Core bot settings",
href: "/configs?file=supportbot",
},
transcripts: {
title: "Ticket transcripts",
href: "/transcripts",
},
suggestions: {
title: "Suggestions",
href: "/configs?file=messages",
},
ai: {
title: "AI assistant",
href: "/configs?file=supportbot-ai",
},
commands: {
title: "Commands",
href: "/configs?file=commands",
},
};
class DashboardAlertRegistry {
constructor() {
/** @type {Map<string, (ctx: DashboardAlertContext) => DashboardAlert[] | Promise<DashboardAlert[]>>} */
this.providers = new Map();
}
/**
* @param {string} id Unique provider id (used for debugging / overrides)
* @param {(ctx: DashboardAlertContext) => DashboardAlert[] | Promise<DashboardAlert[]>} fn
*/
register(id, fn) {
this.providers.set(id, fn);
return this;
}
unregister(id) {
this.providers.delete(id);
}
/** @param {DashboardAlertContext} ctx */
async evaluate(ctx) {
const alerts = [];
for (const fn of this.providers.values()) {
const result = await fn(ctx);
if (Array.isArray(result) && result.length) {
alerts.push(...result);
}
}
return sortAlerts(alerts);
}
}
function sortAlerts(alerts) {
return [...alerts].sort((a, b) => {
const sa = SEVERITY_ORDER[a.severity] ?? 9;
const sb = SEVERITY_ORDER[b.severity] ?? 9;
if (sa !== sb) return sa - sb;
return a.title.localeCompare(b.title);
});
}
function guildSeverity(status) {
if (status === "offline") return "error";
return "warning";
}
function shouldSkipModuleAlert(moduleId, info) {
if (info.status === "done") return true;
if (moduleId === "ai" && info.subtitle === "AI is disabled in config") return true;
// Transcripts are automatic — empty archive is normal, not a setup step.
if (moduleId === "transcripts") return true;
// Partially configured modules are tracked on Overview — only banner when nothing is done yet.
if (info.status === "progress" && (info.passed ?? 0) > 0) return true;
return false;
}
function moduleSeverity(moduleId, info) {
if (info.status === "todo") {
return moduleId === "tickets" || moduleId === "supportbot" ? "warning" : "info";
}
return "info";
}
function evaluateGuildAlerts(ctx) {
const { client } = ctx;
if (!client?.user) {
return [
{
id: "guild:offline",
severity: "error",
category: "guild",
title: "Bot offline",
message: "The bot is not connected to Discord. Check your token and restart the server.",
action: { label: "Bot config", href: "/configs?file=supportbot" },
meta: { status: "offline" },
},
];
}
const health = evaluateGuildHealth(client);
if (health.status === "ok") return [];
return [
{
id: "guild:health",
severity: guildSeverity(health.status),
category: "guild",
title: "Server setup required",
message: health.message,
action: { label: "Bot config", href: "/configs?file=supportbot" },
meta: {
status: health.status,
configuredGuildId: health.configuredGuildId,
configuredGuild: health.configuredGuild,
extraGuilds: health.extraGuilds,
},
},
];
}
function evaluateModuleAlerts(ctx) {
const { configStore, transcriptCount = 0 } = ctx;
const modules = evaluateAllModules(configStore, { transcriptCount });
const alerts = [];
for (const [moduleId, info] of Object.entries(modules)) {
if (shouldSkipModuleAlert(moduleId, info)) continue;
const link = MODULE_LINKS[moduleId] || {
title: moduleId,
href: "/configs",
};
const progress =
info.total > 0 ? `${info.passed ?? 0} of ${info.total} checks complete` : null;
alerts.push({
id: `module:${moduleId}`,
severity: moduleSeverity(moduleId, info),
category: "modules",
title:
info.status === "todo"
? `${link.title} — setup required`
: `${link.title} — in progress`,
message: info.subtitle,
action: { label: "Open module", href: link.href },
meta: {
moduleId,
status: info.status,
passed: info.passed,
total: info.total,
progress,
},
});
}
return alerts;
}
const dashboardAlerts = new DashboardAlertRegistry();
dashboardAlerts.register("guild", evaluateGuildAlerts);
dashboardAlerts.register("modules", evaluateModuleAlerts);
/**
* @typedef {Object} DashboardAlertAction
* @property {string} label
* @property {string} href
*/
/**
* @typedef {Object} DashboardAlert
* @property {string} id
* @property {"error"|"warning"|"info"} severity
* @property {string} category
* @property {string} title
* @property {string} message
* @property {DashboardAlertAction} [action]
* @property {Record<string, unknown>} [meta]
*/
/**
* @typedef {Object} DashboardAlertContext
* @property {import("discord.js").Client} [client]
* @property {import("./ConfigStore.js")} configStore
* @property {number} [transcriptCount]
*/
async function evaluateDashboardAlerts(ctx) {
return dashboardAlerts.evaluate(ctx);
}
module.exports = {
dashboardAlerts,
evaluateDashboardAlerts,
sortAlerts,
MODULE_LINKS,
};
+57
View File
@@ -0,0 +1,57 @@
const { fullPermissions, hasPermission, canAccessConfig } = require("./DashboardPermissions.js");
function grantServiceAccess(req) {
req.dashboardService = true;
req.dashboardPermissions = fullPermissions();
req.dashboardRole = "service";
req.dashboardIsOwner = true;
}
function forbid(res, message = "Forbidden") {
return res.status(403).json({ success: false, error: message });
}
function createPermissionMiddleware(getPermissions) {
return function requirePermission(permission) {
return (req, res, next) => {
if (req.dashboardService) return next();
const perms = getPermissions(req) || req.dashboardPermissions;
if (hasPermission(perms, permission)) return next();
return forbid(res);
};
};
}
function createConfigMiddleware(getPermissions) {
return function requireConfigAccess(mode = "view") {
return (req, res, next) => {
if (req.dashboardService) return next();
const perms = getPermissions(req) || req.dashboardPermissions;
const file = req.params?.file || req.body?.filename;
if (!file) return next();
if (!canAccessConfig(perms, file, mode)) return forbid(res);
return next();
};
};
}
function assertConfigFilesEditable(permissions, files, res) {
if (!permissions) return forbid(res);
for (const file of files) {
if (!canAccessConfig(permissions, file, "edit")) {
return forbid(res, `No permission to edit ${file}.yml`);
}
}
return null;
}
module.exports = {
grantServiceAccess,
forbid,
createPermissionMiddleware,
createConfigMiddleware,
assertConfigFilesEditable,
fullPermissions,
hasPermission,
canAccessConfig,
};
+168
View File
@@ -0,0 +1,168 @@
const fs = require('fs');
const path = require('path');
const BRANDING_DIR = path.join(__dirname, '../Data/branding');
const BRANDING_FILE = path.join(BRANDING_DIR, 'branding.json');
const FAVICON_BASENAME = 'favicon';
const DEFAULTS = {
title: 'SupportBot',
pageTitle: 'SupportBot Dashboard',
faviconFile: null,
faviconMime: null,
updatedAt: null,
};
const ALLOWED_MIME = new Set([
'image/png',
'image/jpeg',
'image/x-icon',
'image/vnd.microsoft.icon',
'image/svg+xml',
'image/webp',
]);
const MIME_EXT = {
'image/png': '.png',
'image/jpeg': '.jpg',
'image/x-icon': '.ico',
'image/vnd.microsoft.icon': '.ico',
'image/svg+xml': '.svg',
'image/webp': '.webp',
};
function ensureDir() {
if (!fs.existsSync(BRANDING_DIR)) {
fs.mkdirSync(BRANDING_DIR, { recursive: true });
}
}
function readBranding() {
ensureDir();
if (!fs.existsSync(BRANDING_FILE)) {
return { ...DEFAULTS };
}
try {
const raw = JSON.parse(fs.readFileSync(BRANDING_FILE, 'utf8'));
return {
title: String(raw.title || DEFAULTS.title).slice(0, 64),
pageTitle: String(raw.pageTitle || DEFAULTS.pageTitle).slice(0, 80),
faviconFile: raw.faviconFile || null,
faviconMime: raw.faviconMime || null,
updatedAt: raw.updatedAt || null,
};
} catch {
return { ...DEFAULTS };
}
}
function writeBranding(data) {
ensureDir();
const next = {
title: String(data.title || DEFAULTS.title).slice(0, 64),
pageTitle: String(data.pageTitle || DEFAULTS.pageTitle).slice(0, 80),
faviconFile: data.faviconFile ?? null,
faviconMime: data.faviconMime ?? null,
updatedAt: Date.now(),
};
fs.writeFileSync(BRANDING_FILE, JSON.stringify(next, null, 2), 'utf8');
return next;
}
function publicPayload(branding) {
const hasFavicon = Boolean(branding.faviconFile);
return {
title: branding.title,
pageTitle: branding.pageTitle,
hasFavicon,
faviconUrl: hasFavicon ? '/api/branding/favicon' : null,
updatedAt: branding.updatedAt,
};
}
function updateBranding({ title, pageTitle }) {
const current = readBranding();
return writeBranding({
...current,
title: title !== undefined ? title : current.title,
pageTitle: pageTitle !== undefined ? pageTitle : current.pageTitle,
});
}
function removeExistingFavicons() {
if (!fs.existsSync(BRANDING_DIR)) return;
for (const file of fs.readdirSync(BRANDING_DIR)) {
if (file.startsWith(`${FAVICON_BASENAME}.`)) {
fs.unlinkSync(path.join(BRANDING_DIR, file));
}
}
}
function saveFaviconFromBase64(dataUrl) {
const match = String(dataUrl || '').match(
/^data:([\w/+.-]+);base64,([A-Za-z0-9+/=]+)$/,
);
if (!match) {
throw new Error('Invalid image data. Upload a PNG, ICO, SVG, or WebP file.');
}
const mime = match[1];
if (!ALLOWED_MIME.has(mime)) {
throw new Error('Unsupported image type. Use PNG, ICO, SVG, JPEG, or WebP.');
}
const buffer = Buffer.from(match[2], 'base64');
if (buffer.length > 512 * 1024) {
throw new Error('Favicon must be 512 KB or smaller.');
}
ensureDir();
removeExistingFavicons();
const ext = MIME_EXT[mime] || '.png';
const filename = `${FAVICON_BASENAME}${ext}`;
const filePath = path.join(BRANDING_DIR, filename);
fs.writeFileSync(filePath, buffer);
const current = readBranding();
return writeBranding({
...current,
faviconFile: filename,
faviconMime: mime,
});
}
function clearFavicon() {
removeExistingFavicons();
const current = readBranding();
return writeBranding({
...current,
faviconFile: null,
faviconMime: null,
});
}
function getFaviconPath() {
const branding = readBranding();
if (!branding.faviconFile) return null;
const filePath = path.join(BRANDING_DIR, branding.faviconFile);
if (!fs.existsSync(filePath)) return null;
return { filePath, mime: branding.faviconMime || 'image/png' };
}
function resetBranding() {
clearFavicon();
return writeBranding({ ...DEFAULTS });
}
module.exports = {
readBranding,
writeBranding,
publicPayload,
updateBranding,
saveFaviconFromBase64,
clearFavicon,
getFaviconPath,
resetBranding,
DEFAULTS,
};
+134
View File
@@ -0,0 +1,134 @@
const CONFIG_FILES = [
"supportbot",
"ticket-panel",
"commands",
"messages",
"supportbot-ai",
];
const ROLES = ["owner", "admin", "moderator", "editor", "viewer", "custom"];
function configMap(view, edit) {
const configs = {};
for (const file of CONFIG_FILES) {
configs[file] = { view: Boolean(view), edit: Boolean(edit) };
}
return configs;
}
function fullPermissions() {
return {
overview: true,
logs: true,
transcripts: true,
settings: { view: true, update: true },
configs: configMap(true, true),
users: { view: true, manage: true },
};
}
function permissionsFromRole(role, customPermissions) {
switch (role) {
case "owner":
case "admin":
return fullPermissions();
case "moderator":
return {
overview: true,
logs: true,
transcripts: true,
settings: { view: true, update: false },
configs: configMap(true, false),
users: { view: false, manage: false },
};
case "editor":
return {
overview: true,
logs: true,
transcripts: false,
settings: { view: true, update: false },
configs: configMap(true, true),
users: { view: false, manage: false },
};
case "viewer":
return {
overview: true,
logs: true,
transcripts: true,
settings: { view: true, update: false },
configs: configMap(true, false),
users: { view: false, manage: false },
};
case "custom":
return normalizePermissions(customPermissions);
default:
return permissionsFromRole("viewer");
}
}
function normalizePermissions(input) {
const base = permissionsFromRole("viewer");
if (!input || typeof input !== "object") return base;
return {
overview: input.overview ?? base.overview,
logs: input.logs ?? base.logs,
transcripts: input.transcripts ?? base.transcripts,
settings: {
view: input.settings?.view ?? base.settings.view,
update: input.settings?.update ?? base.settings.update,
},
configs: CONFIG_FILES.reduce((acc, file) => {
acc[file] = {
view: input.configs?.[file]?.view ?? base.configs[file].view,
edit: input.configs?.[file]?.edit ?? base.configs[file].edit,
};
return acc;
}, {}),
users: {
view: input.users?.view ?? base.users.view,
manage: input.users?.manage ?? base.users.manage,
},
};
}
function hasPermission(permissions, check) {
if (!permissions) return false;
if (check === "overview") return Boolean(permissions.overview);
if (check === "logs") return Boolean(permissions.logs);
if (check === "transcripts") return Boolean(permissions.transcripts);
if (check === "settings.view") return Boolean(permissions.settings?.view);
if (check === "settings.update") return Boolean(permissions.settings?.update);
if (check === "users.view") return Boolean(permissions.users?.view);
if (check === "users.manage") return Boolean(permissions.users?.manage);
const configView = check.match(/^configs\.([a-z0-9-]+)\.view$/);
if (configView) {
const file = configView[1];
return Boolean(permissions.configs?.[file]?.view);
}
const configEdit = check.match(/^configs\.([a-z0-9-]+)\.edit$/);
if (configEdit) {
const file = configEdit[1];
return Boolean(permissions.configs?.[file]?.edit);
}
return false;
}
function canAccessConfig(permissions, file, mode = "view") {
if (!CONFIG_FILES.includes(file)) return false;
return hasPermission(permissions, `configs.${file}.${mode}`);
}
module.exports = {
CONFIG_FILES,
ROLES,
fullPermissions,
permissionsFromRole,
normalizePermissions,
hasPermission,
canAccessConfig,
};
+75
View File
@@ -0,0 +1,75 @@
const crypto = require("crypto");
const SESSION_COOKIE = "sb_dashboard";
const SESSION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
function signSession(payload, secret) {
const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
const sig = crypto
.createHmac("sha256", secret)
.update(body)
.digest("base64url");
return `${body}.${sig}`;
}
function verifySession(token, secret) {
if (!token || typeof token !== "string") return null;
const dot = token.lastIndexOf(".");
if (dot <= 0) return null;
const body = token.slice(0, dot);
const sig = token.slice(dot + 1);
const expected = crypto
.createHmac("sha256", secret)
.update(body)
.digest("base64url");
if (sig.length !== expected.length) return null;
if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) {
return null;
}
try {
const payload = JSON.parse(
Buffer.from(body, "base64url").toString("utf8"),
);
if (!payload?.userId || !payload?.exp) return null;
if (Date.now() > payload.exp) return null;
return payload;
} catch {
return null;
}
}
function createSessionPayload(user) {
return {
userId: user.id,
username: user.username,
globalName: user.global_name || null,
avatar: user.avatar || null,
exp: Date.now() + SESSION_MAX_AGE_MS,
};
}
function sessionCookieOptions(maxAgeMs = SESSION_MAX_AGE_MS, opts = {}) {
const secure =
opts.secure !== undefined
? Boolean(opts.secure)
: process.env.NODE_ENV === "production";
return {
httpOnly: true,
secure,
sameSite: "lax",
maxAge: maxAgeMs,
path: "/",
};
}
module.exports = {
SESSION_COOKIE,
SESSION_MAX_AGE_MS,
signSession,
verifySession,
createSessionPayload,
sessionCookieOptions,
};
+421
View File
@@ -0,0 +1,421 @@
const fs = require("fs");
const path = require("path");
const axios = require("axios");
const YAML = require("yaml");
const configStore = require("./ConfigStore.js");
const { CALLBACK_PATH } = require("./DiscordOAuth.js");
const DISCORD_API = "https://discord.com/api/v10";
const CONFIG_DIR = path.join(__dirname, "../Configs");
const API_FILE = path.join(CONFIG_DIR, "api.yml");
const SUPPORTBOT_FILE = path.join(CONFIG_DIR, "supportbot.yml");
const PLACEHOLDER_PATTERNS = [
/DISCORD_CLIENT_ID/i,
/DISCORD_CLIENT_SECRET/i,
/YOUR_DISCORD_USER_ID/i,
/CHANGE_ME/i,
/BOT_TOKEN/i,
/PUT_RANDOM_STRING/i,
];
function isEmpty(value) {
if (value == null) return true;
if (typeof value === "boolean") return false;
if (typeof value === "number") return false;
return String(value).trim() === "";
}
function isPlaceholder(value) {
if (isEmpty(value)) return true;
const s = String(value).trim();
return PLACEHOLDER_PATTERNS.some((p) => p.test(s));
}
function isDiscordSnowflake(value) {
return /^\d{17,20}$/.test(String(value).trim());
}
function isValidBotToken(value) {
if (isPlaceholder(value)) return false;
const s = String(value).trim();
return s.length >= 50 && s.includes(".");
}
function isValidSecretKey(value) {
if (isPlaceholder(value)) return false;
return String(value).trim().length >= 16;
}
function readApiRoot() {
if (!fs.existsSync(API_FILE)) return null;
try {
const raw = YAML.parse(fs.readFileSync(API_FILE, "utf8"));
return raw?.API ?? raw ?? null;
} catch {
return null;
}
}
function readSupportbotRoot() {
if (!fs.existsSync(SUPPORTBOT_FILE)) return {};
try {
return YAML.parse(fs.readFileSync(SUPPORTBOT_FILE, "utf8")) || {};
} catch {
return {};
}
}
function getOwnerIds(oauth) {
const ids = [];
for (const id of oauth?.OwnerUserIds || []) {
const s = String(id).trim();
if (s) ids.push(s);
}
if (ids.length === 0) {
for (const id of oauth?.AllowedUserIds || []) {
const s = String(id).trim();
if (s) ids.push(s);
}
}
return ids;
}
function buildSteps(apiRoot, supportbot) {
const oauth = apiRoot?.OAuth || {};
const token = supportbot?.General?.Token;
return [
{
id: "botToken",
title: "Bot token",
description: "From the Discord Developer Portal → your application → Bot → Reset Token.",
complete: isValidBotToken(token),
},
{
id: "secretKey",
title: "Dashboard session secret",
description: "Random string used to sign login cookies. Keep it private.",
complete: isValidSecretKey(apiRoot?.SecretKey),
},
{
id: "oauth",
title: "Discord OAuth app",
description: "Same application as your bot — Client ID and Client Secret from OAuth2.",
complete:
!isPlaceholder(oauth.ClientId) &&
!isPlaceholder(oauth.ClientSecret) &&
isDiscordSnowflake(oauth.ClientId),
},
{
id: "redirectUri",
title: "OAuth redirect URL",
description: `Add this exact URL under OAuth2 → Redirects in the Discord portal.`,
complete: isValidRedirectUriConfigured(oauth.RedirectUri),
},
{
id: "owners",
title: "Dashboard owners",
description: "Discord user IDs that can sign in and manage the dashboard (at least one).",
complete: getOwnerIds(oauth).length > 0 && getOwnerIds(oauth).every(isDiscordSnowflake),
},
];
}
function isValidRedirectUriConfigured(uri) {
if (isPlaceholder(uri)) return false;
try {
const u = new URL(String(uri).trim());
if (!["http:", "https:"].includes(u.protocol)) return false;
return u.pathname.replace(/\/$/, "") === CALLBACK_PATH.replace(/\/$/, "");
} catch {
return false;
}
}
function isSetupComplete() {
const apiRoot = readApiRoot();
if (!apiRoot?.Enabled) return false;
const oauth = apiRoot.OAuth || {};
if (!oauth.Enabled) return false;
const steps = buildSteps(apiRoot, readSupportbotRoot());
return steps.every((s) => s.complete);
}
function getSetupStatus(req) {
const apiRoot = readApiRoot() || {};
const steps = buildSteps(apiRoot, readSupportbotRoot());
const complete = steps.every((s) => s.complete);
let suggestedRedirectUri = null;
if (req) {
const proto =
req.get("x-forwarded-proto")?.split(",")[0]?.trim() ||
req.protocol ||
"http";
const host = req.get("x-forwarded-host")?.split(",")[0]?.trim() || req.get("host");
if (host) {
suggestedRedirectUri = `${proto}://${host}${CALLBACK_PATH}`;
}
}
if (!suggestedRedirectUri) {
suggestedRedirectUri = `http://localhost:${apiRoot.Port || 3000}${CALLBACK_PATH}`;
}
return {
complete,
steps,
suggestedRedirectUri,
oauthCallbackPath: CALLBACK_PATH,
};
}
async function validateBotToken(token) {
const trimmed = String(token || "").trim();
if (!isValidBotToken(trimmed)) {
return { ok: false, error: "Enter a valid bot token from the Discord Developer Portal." };
}
try {
const [userRes, appRes] = await Promise.all([
axios.get(`${DISCORD_API}/users/@me`, {
headers: { Authorization: `Bot ${trimmed}` },
timeout: 12_000,
}),
axios.get(`${DISCORD_API}/oauth2/applications/@me`, {
headers: { Authorization: `Bot ${trimmed}` },
timeout: 12_000,
}),
]);
return {
ok: true,
bot: {
id: userRes.data.id,
username: userRes.data.username,
discriminator: userRes.data.discriminator,
},
applicationId: String(appRes.data.id),
};
} catch (err) {
const status = err.response?.status;
if (status === 401) {
return { ok: false, error: "Discord rejected this bot token (401 Unauthorized)." };
}
return {
ok: false,
error: err.response?.data?.message || err.message || "Could not verify bot token.",
};
}
}
async function validateOAuthCredentials(clientId, clientSecret, botToken) {
const id = String(clientId || "").trim();
const secret = String(clientSecret || "").trim();
if (!isDiscordSnowflake(id)) {
return { ok: false, error: "Client ID must be a numeric Discord application ID." };
}
if (isPlaceholder(secret) || secret.length < 20) {
return { ok: false, error: "Enter the OAuth Client Secret from the Discord portal." };
}
if (botToken) {
const botCheck = await validateBotToken(botToken);
if (botCheck.ok && botCheck.applicationId && botCheck.applicationId !== id) {
return {
ok: false,
error: `Client ID does not match the bot application (${botCheck.applicationId}). Use the same app's credentials.`,
};
}
}
try {
await axios.post(
`${DISCORD_API}/oauth2/token`,
new URLSearchParams({ grant_type: "client_credentials", scope: "identify" }),
{
auth: { username: id, password: secret },
headers: { "Content-Type": "application/x-www-form-urlencoded" },
timeout: 12_000,
},
);
return { ok: true, clientId: id };
} catch (err) {
const status = err.response?.status;
if (botToken) {
const botCheck = await validateBotToken(botToken);
if (botCheck.ok && botCheck.applicationId === id) {
return {
ok: true,
clientId: id,
warning:
"Could not verify the client secret with Discord (token endpoint). ID matches your bot — double-check the secret in the portal.",
};
}
}
if (status === 401 || status === 400) {
return { ok: false, error: "Invalid Client ID or Client Secret." };
}
return {
ok: false,
error: err.response?.data?.error_description || err.message || "OAuth validation failed.",
};
}
}
function validateRedirectUri(uri) {
const trimmed = String(uri || "").trim();
if (!isValidRedirectUriConfigured(trimmed)) {
return {
ok: false,
error: `Redirect URL must end with ${CALLBACK_PATH} and use http or https.`,
};
}
return { ok: true, redirectUri: trimmed };
}
async function validateOwnerUserIds(ownerIds, botToken) {
const ids = (Array.isArray(ownerIds) ? ownerIds : [ownerIds])
.map((id) => String(id).trim())
.filter(Boolean);
if (ids.length === 0) {
return { ok: false, error: "Add at least one Discord user ID." };
}
const invalid = ids.filter((id) => !isDiscordSnowflake(id));
if (invalid.length) {
return { ok: false, error: `Invalid user ID: ${invalid[0]}` };
}
if (!botToken || !isValidBotToken(botToken)) {
return { ok: true, ownerUserIds: ids, warning: "User IDs format OK (bot token not verified yet)." };
}
const users = [];
try {
for (const id of ids) {
const res = await axios.get(`${DISCORD_API}/users/${id}`, {
headers: { Authorization: `Bot ${String(botToken).trim()}` },
timeout: 12_000,
});
users.push({
id: res.data.id,
username: res.data.username,
globalName: res.data.global_name || null,
});
}
return { ok: true, ownerUserIds: ids, users };
} catch (err) {
if (err.response?.status === 404) {
return { ok: false, error: "One or more user IDs were not found. Check Developer Mode → Copy User ID." };
}
if (err.response?.status === 403) {
return {
ok: false,
error: "Bot could not look up users. Ensure the bot is in a server with those users, or verify IDs manually.",
};
}
return { ok: false, error: err.message || "Failed to verify owner user IDs." };
}
}
function validateSecretKey(secretKey) {
if (!isValidSecretKey(secretKey)) {
return { ok: false, error: "Use at least 16 characters (not CHANGE_ME)." };
}
return { ok: true };
}
async function validateSetupPayload(payload) {
const results = {};
if (payload.botToken != null) {
results.botToken = await validateBotToken(payload.botToken);
}
if (payload.secretKey != null) {
results.secretKey = validateSecretKey(payload.secretKey);
}
if (payload.clientId != null && payload.clientSecret != null) {
results.oauth = await validateOAuthCredentials(
payload.clientId,
payload.clientSecret,
payload.botToken,
);
}
if (payload.redirectUri != null) {
results.redirectUri = validateRedirectUri(payload.redirectUri);
}
if (payload.ownerUserIds != null) {
results.owners = await validateOwnerUserIds(payload.ownerUserIds, payload.botToken);
}
const allOk = Object.values(results).every((r) => r?.ok);
return { ok: allOk, results };
}
function ensureApiFile() {
if (fs.existsSync(API_FILE)) return;
const example = path.join(CONFIG_DIR, "api.yml.example");
if (fs.existsSync(example)) {
fs.copyFileSync(example, API_FILE);
configStore.reloadFile("api");
} else {
throw new Error("Configs/api.yml is missing. Copy Configs/api.yml.example to api.yml.");
}
}
function applySetup(payload) {
ensureApiFile();
const ownerIds = (Array.isArray(payload.ownerUserIds)
? payload.ownerUserIds
: String(payload.ownerUserIds || "").split(/[\s,]+/)
)
.map((id) => String(id).trim())
.filter(Boolean);
const apiDoc = YAML.parseDocument(fs.readFileSync(API_FILE, "utf8"));
if (!apiDoc.get("API")) apiDoc.set("API", {});
apiDoc.setIn(["API", "Enabled"], true);
apiDoc.setIn(["API", "SecretKey"], String(payload.secretKey).trim());
if (payload.port != null && payload.port !== "") {
apiDoc.setIn(["API", "Port"], Number(payload.port) || 3000);
}
if (!apiDoc.getIn(["API", "OAuth"])) apiDoc.setIn(["API", "OAuth"], {});
apiDoc.setIn(["API", "OAuth", "Enabled"], true);
apiDoc.setIn(["API", "OAuth", "ClientId"], String(payload.clientId).trim());
apiDoc.setIn(["API", "OAuth", "ClientSecret"], String(payload.clientSecret).trim());
apiDoc.setIn(["API", "OAuth", "RedirectUri"], String(payload.redirectUri).trim());
apiDoc.setIn(["API", "OAuth", "OwnerUserIds"], ownerIds);
apiDoc.setIn(["API", "OAuth", "AllowedUserIds"], []);
fs.writeFileSync(API_FILE, apiDoc.toString());
const sbDoc = YAML.parseDocument(fs.readFileSync(SUPPORTBOT_FILE, "utf8"));
sbDoc.setIn(["General", "Token"], String(payload.botToken).trim());
fs.writeFileSync(SUPPORTBOT_FILE, sbDoc.toString());
configStore.reloadFile("api");
configStore.reloadFile("supportbot");
return {
ownerUserIds: ownerIds,
api: configStore.api?.API || configStore.api,
};
}
module.exports = {
isSetupComplete,
getSetupStatus,
validateBotToken,
validateOAuthCredentials,
validateRedirectUri,
validateOwnerUserIds,
validateSecretKey,
validateSetupPayload,
applySetup,
};
+291
View File
@@ -0,0 +1,291 @@
const fs = require("fs");
const path = require("path");
const {
CONFIG_FILES,
ROLES,
fullPermissions,
permissionsFromRole,
normalizePermissions,
hasPermission,
canAccessConfig,
} = require("./DashboardPermissions.js");
const { discordAvatarUrl } = require("./DiscordOAuth.js");
const STORE_PATH = path.join(__dirname, "../Data/dashboard-users.json");
function ensureDataDir() {
const dir = path.dirname(STORE_PATH);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}
function emptyStore() {
return { version: 1, users: {} };
}
function readStore() {
ensureDataDir();
if (!fs.existsSync(STORE_PATH)) return emptyStore();
try {
const raw = JSON.parse(fs.readFileSync(STORE_PATH, "utf8"));
if (!raw.users || typeof raw.users !== "object") return emptyStore();
return raw;
} catch {
return emptyStore();
}
}
function writeStore(store) {
ensureDataDir();
fs.writeFileSync(STORE_PATH, JSON.stringify(store, null, 2), "utf8");
}
function getOwnerIds(oauth) {
const owners = new Set();
for (const id of oauth?.OwnerUserIds || []) owners.add(String(id));
for (const id of oauth?.AllowedUserIds || []) owners.add(String(id));
return owners;
}
function isYamlOwner(userId, oauth) {
return getOwnerIds(oauth).has(String(userId));
}
function bootstrapFromOAuth(oauth) {
const store = readStore();
const owners = getOwnerIds(oauth);
let changed = false;
for (const id of owners) {
if (!store.users[id]) {
store.users[id] = {
id,
username: null,
globalName: null,
avatar: null,
role: "owner",
permissions: null,
enabled: true,
createdAt: Date.now(),
updatedAt: Date.now(),
createdBy: "system",
};
changed = true;
}
}
if (changed) writeStore(store);
return store;
}
function syncDiscordProfile(userId, profile) {
const store = readStore();
const entry = store.users[userId];
if (!entry) return;
entry.username = profile.username ?? entry.username;
entry.globalName = profile.globalName ?? entry.globalName;
entry.avatar = profile.avatar ?? entry.avatar;
entry.updatedAt = Date.now();
writeStore(store);
}
function resolvePermissions(entry, oauth, userId) {
if (isYamlOwner(userId, oauth)) {
return { permissions: fullPermissions(), role: "owner", isOwner: true };
}
if (!entry?.enabled) return null;
const role = entry.role || "viewer";
const permissions =
role === "custom"
? permissionsFromRole("custom", entry.permissions)
: permissionsFromRole(role);
return { permissions, role, isOwner: false };
}
function getAccess(userId, oauth) {
bootstrapFromOAuth(oauth);
const store = readStore();
const id = String(userId);
if (isYamlOwner(id, oauth)) {
const entry = store.users[id];
return {
entry: entry || { id, role: "owner" },
permissions: fullPermissions(),
role: "owner",
isOwner: true,
yamlOwner: true,
};
}
const entry = store.users[id];
const resolved = resolvePermissions(entry, oauth, id);
if (!resolved) return null;
return {
entry,
permissions: resolved.permissions,
role: resolved.role,
isOwner: false,
yamlOwner: false,
};
}
function canLogin(userId, oauth) {
return Boolean(getAccess(userId, oauth));
}
function formatPublicUser(entry, access, discordProfile) {
const id = String(entry?.id || discordProfile?.id);
const avatarHash = entry?.avatar ?? discordProfile?.avatar ?? null;
return {
id,
username: entry?.username || discordProfile?.username || "Unknown",
globalName: entry?.globalName ?? discordProfile?.global_name ?? null,
avatar: avatarHash
? discordAvatarUrl({ id, avatar: avatarHash })
: discordProfile
? discordAvatarUrl(discordProfile)
: discordAvatarUrl({ id, avatar: null }),
role: access.role,
isOwner: access.isOwner,
permissions: access.permissions,
};
}
function listUsers(oauth) {
bootstrapFromOAuth(oauth);
const store = readStore();
const yamlOwners = getOwnerIds(oauth);
return Object.values(store.users).map((entry) => {
const access = resolvePermissions(entry, oauth, entry.id) || {
permissions: permissionsFromRole("viewer"),
role: entry.role,
isOwner: false,
};
return {
id: entry.id,
username: entry.username,
globalName: entry.globalName,
avatar: entry.avatar
? discordAvatarUrl({ id: entry.id, avatar: entry.avatar })
: discordAvatarUrl({ id: entry.id, avatar: null }),
role: yamlOwners.has(String(entry.id)) ? "owner" : entry.role,
permissions:
entry.role === "custom"
? normalizePermissions(entry.permissions)
: access.permissions,
enabled: entry.enabled !== false,
isOwner: yamlOwners.has(String(entry.id)),
yamlOwner: yamlOwners.has(String(entry.id)),
createdAt: entry.createdAt,
updatedAt: entry.updatedAt,
};
});
}
function addUser(payload, actorId, oauth) {
const id = String(payload.id || "").trim();
if (!/^\d{17,20}$/.test(id)) {
throw new Error("Invalid Discord user ID");
}
const role = payload.role || "viewer";
if (!ROLES.includes(role)) throw new Error("Invalid role");
if (role === "owner" && !isYamlOwner(actorId, oauth)) {
throw new Error("Only api.yml owners can assign the owner role");
}
const store = readStore();
if (store.users[id]) throw new Error("User already exists");
store.users[id] = {
id,
username: payload.username || null,
globalName: payload.globalName || null,
avatar: null,
role,
permissions:
role === "custom" ? normalizePermissions(payload.permissions) : null,
enabled: payload.enabled !== false,
createdAt: Date.now(),
updatedAt: Date.now(),
createdBy: String(actorId),
};
writeStore(store);
return listUsers(oauth).find((u) => u.id === id);
}
function updateUser(id, payload, actorId, oauth) {
const store = readStore();
const entry = store.users[String(id)];
if (!entry) throw new Error("User not found");
if (isYamlOwner(id, oauth) && payload.enabled === false) {
throw new Error("Cannot disable an owner defined in api.yml");
}
if (payload.role) {
if (!ROLES.includes(payload.role)) throw new Error("Invalid role");
if (payload.role === "owner" && !isYamlOwner(actorId, oauth)) {
throw new Error("Only api.yml owners can assign the owner role");
}
if (isYamlOwner(id, oauth) && payload.role !== "owner") {
throw new Error("Cannot change role of an api.yml owner");
}
entry.role = payload.role;
}
if (payload.enabled !== undefined) entry.enabled = Boolean(payload.enabled);
if (payload.username !== undefined) entry.username = payload.username;
if (payload.globalName !== undefined) entry.globalName = payload.globalName;
if (payload.permissions !== undefined) {
entry.permissions = normalizePermissions(payload.permissions);
if (entry.role !== "custom") entry.role = "custom";
}
if (entry.role === "custom" && payload.permissions === undefined && payload.role !== "custom") {
entry.permissions = null;
}
entry.updatedAt = Date.now();
writeStore(store);
return listUsers(oauth).find((u) => u.id === String(id));
}
function removeUser(id, oauth) {
if (isYamlOwner(id, oauth)) {
throw new Error("Remove this user from OwnerUserIds in api.yml instead");
}
const store = readStore();
if (!store.users[String(id)]) throw new Error("User not found");
delete store.users[String(id)];
writeStore(store);
}
module.exports = {
CONFIG_FILES,
STORE_PATH,
getOwnerIds,
isYamlOwner,
bootstrapFromOAuth,
syncDiscordProfile,
getAccess,
canLogin,
formatPublicUser,
listUsers,
addUser,
updateUser,
removeUser,
hasPermission,
canAccessConfig,
ROLES,
};
+233
View File
@@ -0,0 +1,233 @@
const crypto = require("crypto");
const axios = require("axios");
const DISCORD_API = "https://discord.com/api";
const OAUTH_STATE_COOKIE = "sb_oauth_state";
const OAUTH_REDIRECT_COOKIE = "sb_oauth_redirect";
const OAUTH_STATE_MAX_AGE_MS = 10 * 60 * 1000;
const CALLBACK_PATH = "/api/auth/discord/callback";
function discordAvatarUrl(user) {
if (user.avatar) {
const ext = user.avatar.startsWith("a_") ? "gif" : "png";
return `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.${ext}?size=128`;
}
const index = Number((BigInt(user.id) >> 22n) % 6n);
return `https://cdn.discordapp.com/embed/avatars/${index}.png`;
}
function getTrustProxySetting(apiConfig) {
if (apiConfig?.TrustProxy === false) return false;
if (typeof apiConfig?.TrustProxy === "number") return apiConfig.TrustProxy;
if (apiConfig?.TrustProxy === true) return 1;
return false;
}
function getRequestProto(req, apiConfig) {
if (apiConfig?.TrustProxy !== false) {
const forwarded = req.get("x-forwarded-proto");
if (forwarded) {
return forwarded.split(",")[0].trim().toLowerCase();
}
}
return (req.protocol || "http").toLowerCase();
}
function getRequestHost(req) {
const forwarded = req.get("x-forwarded-host");
if (forwarded) {
return forwarded.split(",")[0].trim();
}
return req.get("host") || "";
}
function getRequestOrigin(req, apiConfig) {
const proto = getRequestProto(req, apiConfig);
const host = getRequestHost(req);
if (!host) return null;
return `${proto}://${host}`;
}
function normalizeRedirectUri(uri) {
try {
const u = new URL(uri);
u.hash = "";
u.search = "";
return u.toString();
} catch {
return null;
}
}
function redirectUriMatchesHostPath(a, b) {
try {
const ua = new URL(a);
const ub = new URL(b);
return ua.host === ub.host && ua.pathname === ub.pathname;
} catch {
return false;
}
}
function collectConfiguredRedirectUris(oauth) {
const list = [];
if (oauth?.RedirectUri) {
const normalized = normalizeRedirectUri(oauth.RedirectUri);
if (normalized) list.push(normalized);
}
if (Array.isArray(oauth?.RedirectUris)) {
for (const entry of oauth.RedirectUris) {
const normalized = normalizeRedirectUri(entry);
if (normalized && !list.includes(normalized)) {
list.push(normalized);
}
}
}
return list;
}
/**
* Pick the OAuth redirect_uri for this request. When UseRequestOrigin is enabled
* (default), uses the same host/path as RedirectUri but the protocol the user
* actually used (http vs https). Register every variant in the Discord portal.
*/
function resolveOAuthRedirectUri(req, oauth, apiConfig) {
const configured = collectConfiguredRedirectUris(oauth);
const fallback = configured[0] || oauth?.RedirectUri || "";
const useRequestOrigin = oauth?.UseRequestOrigin !== false;
if (!useRequestOrigin || !req) {
return fallback;
}
const origin = getRequestOrigin(req, apiConfig);
if (!origin) return fallback;
const dynamic = `${origin}${CALLBACK_PATH}`;
const normalizedDynamic = normalizeRedirectUri(dynamic);
if (!normalizedDynamic) return fallback;
if (configured.includes(normalizedDynamic)) {
return normalizedDynamic;
}
const matchesConfigured = configured.some((uri) =>
redirectUriMatchesHostPath(uri, normalizedDynamic),
);
if (matchesConfigured) {
return normalizedDynamic;
}
return fallback;
}
function isSecureRequest(req, oauth, apiConfig) {
if (oauth?.CookieSecure === true) return true;
if (oauth?.CookieSecure === false) return false;
if (req) {
if (typeof req.secure === "boolean") return req.secure;
return getRequestProto(req, apiConfig) === "https";
}
return process.env.NODE_ENV === "production";
}
function buildAuthorizeUrl(oauth, state, redirectUri) {
const params = new URLSearchParams({
client_id: oauth.ClientId,
redirect_uri: redirectUri,
response_type: "code",
scope: "identify",
state,
prompt: "none",
});
return `${DISCORD_API}/oauth2/authorize?${params.toString()}`;
}
async function exchangeCode(oauth, code, redirectUri) {
const body = new URLSearchParams({
client_id: oauth.ClientId,
client_secret: oauth.ClientSecret,
grant_type: "authorization_code",
code,
redirect_uri: redirectUri,
});
const { data } = await axios.post(`${DISCORD_API}/oauth2/token`, body, {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
timeout: 15000,
});
return data.access_token;
}
async function fetchDiscordUser(accessToken) {
const { data } = await axios.get(`${DISCORD_API}/users/@me`, {
headers: { Authorization: `Bearer ${accessToken}` },
timeout: 15000,
});
return data;
}
function createOAuthState() {
return crypto.randomBytes(24).toString("hex");
}
function oauthStateCookieOptions(req, oauth, apiConfig) {
return {
httpOnly: true,
secure: isSecureRequest(req, oauth, apiConfig),
sameSite: "lax",
maxAge: OAUTH_STATE_MAX_AGE_MS,
path: "/",
};
}
function oauthRedirectCookieOptions(req, oauth, apiConfig) {
return oauthStateCookieOptions(req, oauth, apiConfig);
}
function isOAuthConfigured(oauth) {
return Boolean(
oauth?.Enabled &&
oauth.ClientId &&
oauth.ClientSecret &&
oauth.RedirectUri,
);
}
function isUserAllowed(userId, oauth) {
const allowed = oauth?.AllowedUserIds;
if (!Array.isArray(allowed) || allowed.length === 0) {
return false;
}
return allowed.map(String).includes(String(userId));
}
function formatPublicUser(user) {
return {
id: user.id,
username: user.username,
globalName: user.global_name || null,
avatar: discordAvatarUrl(user),
};
}
module.exports = {
OAUTH_STATE_COOKIE,
OAUTH_REDIRECT_COOKIE,
OAUTH_STATE_MAX_AGE_MS,
CALLBACK_PATH,
getTrustProxySetting,
resolveOAuthRedirectUri,
isSecureRequest,
buildAuthorizeUrl,
exchangeCode,
fetchDiscordUser,
createOAuthState,
oauthStateCookieOptions,
oauthRedirectCookieOptions,
isOAuthConfigured,
isUserAllowed,
formatPublicUser,
discordAvatarUrl,
};
+276
View File
@@ -0,0 +1,276 @@
const { ChannelType } = require("discord.js");
const configStore = require("./ConfigStore.js");
const { withTimeout } = require("./asyncTimeout.js");
const RESOURCES_CACHE_MS = 90 * 1000;
/** Bump when resource payload shape changes (e.g. added emojis). */
const RESOURCES_CACHE_VERSION = 2;
let resourcesCache = { guildId: null, data: null, at: 0, version: 0 };
let resourcesInflight = null;
function getConfiguredGuildId() {
const id = configStore.supportbot?.General?.GuildId;
if (!id || id === "GUILD_ID" || String(id).trim() === "") return null;
return String(id).trim();
}
function setConfiguredGuildId(guildId) {
if (!configStore.supportbot.General) {
configStore.supportbot.General = {};
}
configStore.supportbot.General.GuildId = guildId ? String(guildId) : "";
}
function getPrimaryGuild(client) {
if (!client) return null;
const configuredId = getConfiguredGuildId();
if (configuredId) {
const match = client.guilds.cache.get(configuredId);
if (match) return match;
}
return client.guilds.cache.first() || null;
}
function evaluateGuildHealth(client) {
const configuredId = getConfiguredGuildId();
const guilds = [...client.guilds.cache.values()];
if (!configuredId) {
return {
status: "missing_config",
configuredGuildId: null,
message:
"No guild ID is set. Add your Discord server ID under Bot config → General.",
configuredGuild: null,
extraGuilds: guilds.map(formatGuildSummary),
};
}
const configuredGuild = client.guilds.cache.get(configuredId) || null;
const extraGuilds = guilds
.filter((g) => g.id !== configuredId)
.map(formatGuildSummary);
if (!configuredGuild) {
return {
status: "not_in_guild",
configuredGuildId: configuredId,
message: `The bot is not in the configured server (${configuredId}). Invite it or update the guild ID.`,
configuredGuild: null,
extraGuilds: guilds.map(formatGuildSummary),
};
}
if (extraGuilds.length > 0) {
return {
status: "extra_guilds",
configuredGuildId: configuredId,
message: `The bot is in ${extraGuilds.length} extra server(s). Leave them so only your configured server remains.`,
configuredGuild: formatGuildSummary(configuredGuild),
extraGuilds,
};
}
return {
status: "ok",
configuredGuildId: configuredId,
message: null,
configuredGuild: formatGuildSummary(configuredGuild),
extraGuilds: [],
};
}
function formatGuildSummary(guild) {
return {
id: guild.id,
name: guild.name,
memberCount: guild.memberCount ?? null,
icon: guild.iconURL?.({ size: 128 }) ?? null,
};
}
function syncGuildHealth(client) {
if (!client?.user) {
client.guildHealth = {
status: "offline",
configuredGuildId: getConfiguredGuildId(),
message: "Bot is not connected to Discord.",
configuredGuild: null,
extraGuilds: [],
};
return client.guildHealth;
}
client.guildHealth = evaluateGuildHealth(client);
return client.guildHealth;
}
function logGuildWarning(client, message) {
const name = client?.user?.username || "Bot";
console.warn(`\x1b[33m[Guild]\x1b[0m ${name}: ${message}`);
}
async function leaveGuild(client, guildId) {
const guild = client.guilds.cache.get(String(guildId));
if (!guild) {
throw new Error("Bot is not in that server.");
}
const configuredId = getConfiguredGuildId();
if (configuredId && guild.id === configuredId) {
throw new Error("Cannot leave the configured server. Change the guild ID first.");
}
await guild.leave();
syncGuildHealth(client);
return syncGuildHealth(client);
}
function buildResourcesFromGuild(guild) {
const roles = [...guild.roles.cache.values()]
.filter((r) => r.id !== guild.id)
.sort((a, b) => b.position - a.position)
.map((r) => ({
id: r.id,
name: r.name,
color: r.hexColor || null,
}));
const channels = [...guild.channels.cache.values()]
.filter(
(c) =>
c.type === ChannelType.GuildText ||
c.type === ChannelType.GuildVoice ||
c.type === ChannelType.GuildAnnouncement ||
c.type === ChannelType.GuildStageVoice ||
c.type === ChannelType.GuildForum,
)
.sort((a, b) => a.name.localeCompare(b.name))
.map((c) => ({
id: c.id,
name: c.name,
type: c.type,
}));
const categories = [...guild.channels.cache.values()]
.filter((c) => c.type === ChannelType.GuildCategory)
.sort((a, b) => a.name.localeCompare(b.name))
.map((c) => ({
id: c.id,
name: c.name,
}));
const emojis = [...guild.emojis.cache.values()]
.sort((a, b) => a.name.localeCompare(b.name))
.map((e) => {
const animated = Boolean(e.animated);
const ext = animated ? "gif" : "png";
return {
id: e.id,
name: e.name,
animated,
url:
e.imageURL({ extension: ext, size: 64 }) ||
`https://cdn.discordapp.com/emojis/${e.id}.${ext}?size=64`,
};
});
return {
guildId: guild.id,
guildName: guild.name,
roles,
channels,
categories,
emojis,
};
}
async function fetchGuildResourcesFromDiscord(client, guildId) {
const id = guildId || getConfiguredGuildId();
if (!id) return null;
const guild = client.guilds.cache.get(id);
if (!guild) return null;
try {
await withTimeout(
Promise.all([guild.channels.fetch(), guild.roles.fetch()]),
12_000,
"Discord channel/role fetch timed out",
);
} catch (err) {
console.warn("[Guild] Failed to fetch channels/roles:", err.message);
if (guild.roles.cache.size === 0 && guild.channels.cache.size === 0) {
return null;
}
}
try {
await withTimeout(guild.emojis.fetch(), 12_000, "Discord emoji fetch timed out");
} catch (err) {
console.warn("[Guild] Failed to fetch guild emojis:", err.message);
}
return buildResourcesFromGuild(guild);
}
async function fetchGuildResources(client, guildId) {
const id = guildId || getConfiguredGuildId();
if (!id || !client?.user) return null;
const now = Date.now();
if (
resourcesCache.data &&
resourcesCache.version === RESOURCES_CACHE_VERSION &&
resourcesCache.guildId === id &&
now - resourcesCache.at < RESOURCES_CACHE_MS
) {
return resourcesCache.data;
}
if (resourcesInflight) {
try {
return await resourcesInflight;
} catch {
/* fall through to retry */
}
}
resourcesInflight = (async () => {
const data = await fetchGuildResourcesFromDiscord(client, id);
if (data) {
resourcesCache = {
guildId: id,
data,
at: Date.now(),
version: RESOURCES_CACHE_VERSION,
};
}
return data;
})();
try {
return await resourcesInflight;
} finally {
resourcesInflight = null;
}
}
function clearGuildResourcesCache() {
resourcesCache = { guildId: null, data: null, at: 0, version: 0 };
resourcesInflight = null;
}
module.exports = {
getConfiguredGuildId,
setConfiguredGuildId,
getPrimaryGuild,
evaluateGuildHealth,
syncGuildHealth,
logGuildWarning,
leaveGuild,
fetchGuildResources,
clearGuildResourcesCache,
};
+181
View File
@@ -0,0 +1,181 @@
const fs = require("fs");
const path = require("path");
const LOG_ROOT = path.resolve(__dirname, "../Logs");
const LOG_TYPES = ["Output", "Warn", "Error"];
function todayDate() {
return new Date().toISOString().split("T")[0];
}
function getLogPath(type, date = todayDate()) {
return path.join(LOG_ROOT, type, `${type}-${date}.log`);
}
/** Prefer today's file; fall back to the newest log in the folder. */
function resolveLogPath(type) {
const todayPath = getLogPath(type);
if (fs.existsSync(todayPath)) return todayPath;
const dir = path.join(LOG_ROOT, type);
if (!fs.existsSync(dir)) return todayPath;
const files = fs
.readdirSync(dir)
.filter((f) => f.endsWith(".log"))
.sort()
.reverse();
if (!files.length) return todayPath;
return path.join(dir, files[0]);
}
function stripAnsi(text) {
return String(text).replace(/\x1b\[[0-9;]*m/g, "");
}
function parseLogLine(line, type) {
const trimmed = line.trimEnd();
if (!trimmed) return null;
const match = trimmed.match(/^\[([^\]]+)\]\s?(.*)$/);
if (match) {
return {
type,
timestamp: match[1],
message: stripAnsi(match[2]),
};
}
return {
type,
timestamp: null,
message: stripAnsi(trimmed),
};
}
function readFromByte(filePath, fromByte) {
if (!fs.existsSync(filePath)) {
return { lines: [], position: 0 };
}
const stat = fs.statSync(filePath);
if (stat.size === 0) {
return { lines: [], position: 0 };
}
const start = Math.max(0, Math.min(fromByte, stat.size));
if (start >= stat.size) {
return { lines: [], position: stat.size };
}
const fd = fs.openSync(filePath, "r");
const buffer = Buffer.alloc(stat.size - start);
fs.readSync(fd, buffer, 0, buffer.length, start);
fs.closeSync(fd);
const text = buffer.toString("utf8");
const lines = text.split(/\r?\n/).filter((l) => l.length > 0);
return { lines, position: stat.size };
}
function readLastLines(filePath, maxLines) {
if (!fs.existsSync(filePath)) {
return { lines: [], position: 0 };
}
const stat = fs.statSync(filePath);
if (stat.size === 0) {
return { lines: [], position: 0 };
}
const chunkSize = Math.min(stat.size, 512 * 1024);
const start = Math.max(0, stat.size - chunkSize);
const fd = fs.openSync(filePath, "r");
const buffer = Buffer.alloc(chunkSize);
fs.readSync(fd, buffer, 0, chunkSize, start);
fs.closeSync(fd);
const lines = buffer
.toString("utf8")
.split(/\r?\n/)
.filter((l) => l.length > 0);
const slice = lines.slice(-maxLines);
return { lines: slice, position: stat.size };
}
/**
* @param {string[]} types
* @param {Record<string, number>} cursor byte offsets per type
* @param {number} initialLines lines to load when cursor is empty
*/
function fetchLogs(types, cursor = {}, initialLines = 300) {
const validTypes = types.filter((t) => LOG_TYPES.includes(t));
const entries = [];
const nextCursor = { ...cursor };
for (const type of validTypes) {
const filePath = resolveLogPath(type);
const prevPos = cursor[type] ?? 0;
let lines = [];
let position = 0;
if (!fs.existsSync(filePath)) {
nextCursor[type] = 0;
continue;
}
if (prevPos === 0 && initialLines > 0) {
const tail = readLastLines(filePath, initialLines);
lines = tail.lines;
position = tail.position;
} else if (prevPos > 0) {
const chunk = readFromByte(filePath, prevPos);
lines = chunk.lines;
position = chunk.position;
} else {
// No tail requested and no cursor — skip content, anchor at EOF
position = fs.statSync(filePath).size;
}
nextCursor[type] = position;
for (const line of lines) {
const entry = parseLogLine(line, type);
if (entry) entries.push(entry);
}
}
entries.sort((a, b) => {
const ta = a.timestamp ? Date.parse(a.timestamp) : 0;
const tb = b.timestamp ? Date.parse(b.timestamp) : 0;
return ta - tb;
});
return { entries, cursor: nextCursor };
}
function getLogMeta() {
const date = todayDate();
return LOG_TYPES.map((type) => {
const filePath = resolveLogPath(type);
const exists = fs.existsSync(filePath) && fs.statSync(filePath).size > 0;
return {
type,
date,
file: exists ? path.basename(filePath) : null,
size: exists ? fs.statSync(filePath).size : 0,
};
});
}
module.exports = {
LOG_ROOT,
LOG_TYPES,
fetchLogs,
getLogMeta,
getLogPath,
resolveLogPath,
};
+270
View File
@@ -0,0 +1,270 @@
const fs = require("fs");
const path = require("path");
const PLACEHOLDER_PATTERNS = [
/ROLE_ID/i,
/CHANNEL_ID/i,
/CATEGORY_ID/i,
/TAG_ID/i,
/FORUM_CHANNEL_ID/i,
/BOT_TOKEN/i,
/MODEL_API_KEY/i,
/PASTEBIN_API_KEY/i,
/YOUR_/i,
/PUT_RANDOM_STRING/i,
/example\.com/i,
];
function isEmpty(value) {
if (value == null) return true;
if (typeof value === "boolean") return false;
if (typeof value === "number") return false;
return String(value).trim() === "";
}
function isPlaceholder(value) {
if (isEmpty(value)) return true;
const s = String(value).trim();
return PLACEHOLDER_PATTERNS.some((p) => p.test(s));
}
function isDiscordId(value) {
return /^\d{17,20}$/.test(String(value).trim());
}
function isConfiguredId(value) {
return isDiscordId(value) && !isPlaceholder(value);
}
function isValidToken(value) {
if (isPlaceholder(value)) return false;
const s = String(value).trim();
return s.length >= 50 && s.includes(".");
}
function scoreChecks(checks) {
const total = checks.length;
const passed = checks.filter((c) => c.ok).length;
if (total === 0) {
return { status: "done", subtitle: "Ready", passed: 0, total: 0 };
}
if (passed === 0) {
const hint = checks.find((c) => !c.ok)?.hint ?? "Not configured yet";
return { status: "todo", subtitle: hint, passed, total };
}
if (passed === total) {
return { status: "done", subtitle: "Configured and ready", passed, total };
}
const next = checks.find((c) => !c.ok);
return {
status: "progress",
subtitle: next?.hint ?? `${passed} of ${total} steps complete`,
passed,
total,
};
}
function evaluateTickets(supportbot, ticketPanel) {
const ticket = supportbot?.Ticket ?? {};
const ticketType = String(ticket.TicketType || "channels").toLowerCase();
return scoreChecks([
{
ok: ticketPanel?.Panel === true,
hint: "Enable the ticket panel",
},
{
ok: isConfiguredId(ticket.TicketHome),
hint: "Set TicketHome channel ID",
},
{
ok:
ticketType !== "channels" ||
isConfiguredId(ticket.TicketChannelsCategory),
hint: "Set ticket category ID",
},
{
ok: !isPlaceholder(ticketPanel?.Button?.Text),
hint: "Configure panel button text",
},
]);
}
function evaluateSupportbot(supportbot) {
const roles = supportbot?.Roles?.StaffMember ?? {};
const welcome = supportbot?.Welcome ?? {};
return scoreChecks([
{ ok: isValidToken(supportbot?.General?.Token), hint: "Add your bot token" },
{
ok:
isConfiguredId(roles.Staff) ||
isConfiguredId(roles.Admin) ||
isConfiguredId(roles.Moderator),
hint: "Set staff role IDs",
},
{
ok: !welcome.Enabled || isConfiguredId(welcome.Channel),
hint: "Set welcome channel ID",
},
{
ok: !isPlaceholder(supportbot?.Activity?.Status),
hint: "Set bot activity status",
},
]);
}
function evaluateTranscripts(supportbot, transcriptCount) {
const ticketReady = isConfiguredId(supportbot?.Ticket?.TicketHome);
if (!ticketReady) {
// Ticket setup is tracked by the tickets module — avoid a misleading transcripts alert.
return {
status: "done",
subtitle: "Available after ticket channels are configured",
passed: 0,
total: 0,
};
}
if (transcriptCount > 0) {
return {
status: "done",
subtitle: `${transcriptCount} transcript${transcriptCount === 1 ? "" : "s"} saved`,
passed: 1,
total: 1,
};
}
return {
status: "done",
subtitle: "No transcripts yet — they are created when tickets close",
passed: 1,
total: 1,
};
}
function evaluateSuggestions(supportbot) {
const sug = supportbot?.Suggestions ?? {};
const mode = String(sug.Mode || "Channel").toLowerCase();
const channelOk =
mode === "forum"
? isConfiguredId(sug.ForumChannel)
: isConfiguredId(sug.Channel);
return scoreChecks([
{
ok: channelOk,
hint:
mode === "forum"
? "Set suggestions forum channel"
: "Set suggestions channel ID",
},
{
ok: !isPlaceholder(sug.UpvoteEmoji) && !isPlaceholder(sug.DownvoteEmoji),
hint: "Configure voting emojis",
},
]);
}
function evaluateAi(supportbotAi) {
if (supportbotAi?.Enabled !== true) {
return {
status: "progress",
subtitle: "AI is disabled in config",
passed: 0,
total: 3,
};
}
return scoreChecks([
{
ok: !isPlaceholder(supportbotAi?.General?.Model_API_Key),
hint: "Add your model API key",
},
{
ok: isConfiguredId(supportbotAi?.Channels?.AIChannel),
hint: "Set AI channel ID",
},
{
ok: !isPlaceholder(supportbotAi?.General?.Model),
hint: "Choose an AI model",
},
]);
}
function evaluateCommands(commands) {
const entries = Object.entries(commands || {}).filter(
([, v]) => v && typeof v === "object" && "Enabled" in v,
);
if (!entries.length) {
return { status: "todo", subtitle: "No commands configured", passed: 0, total: 0 };
}
const enabled = entries.filter(([, v]) => v.Enabled !== false).length;
const total = entries.length;
const ratio = enabled / total;
if (ratio >= 0.85) {
return {
status: "done",
subtitle: `${enabled} of ${total} commands enabled`,
passed: enabled,
total,
};
}
if (enabled === 0) {
return {
status: "todo",
subtitle: "Enable slash commands",
passed: 0,
total,
};
}
return {
status: "progress",
subtitle: `${enabled} of ${total} commands enabled`,
passed: enabled,
total,
};
}
function countTranscripts() {
const dir = path.resolve(__dirname, "../Data/Transcripts");
if (!fs.existsSync(dir)) return 0;
return fs
.readdirSync(dir)
.filter((f) => f.endsWith("-transcript.html")).length;
}
function evaluateAllModules(configStore, options = {}) {
const supportbot = configStore.supportbot;
const ticketPanel = configStore.ticketPanel;
const supportbotAi = configStore.supportbotAi;
const commands = configStore.commands;
const transcriptCount =
options.transcriptCount ?? countTranscripts();
return {
tickets: evaluateTickets(supportbot, ticketPanel),
supportbot: evaluateSupportbot(supportbot),
transcripts: evaluateTranscripts(supportbot, transcriptCount),
suggestions: evaluateSuggestions(supportbot),
ai: evaluateAi(supportbotAi),
commands: evaluateCommands(commands),
};
}
module.exports = {
evaluateAllModules,
isPlaceholder,
isConfiguredId,
};
+63
View File
@@ -0,0 +1,63 @@
const notificationStore = require("./NotificationStore.js");
const { fetchUpdateInfo } = require("./UpdateChecker.js");
function notifyBotRestart(success, errorMessage) {
if (success) {
return notificationStore.add({
type: "bot",
title: "Bot restarted",
message:
"Discord bot reconnected with your latest config. API and dashboard stayed online.",
});
}
return notificationStore.add({
type: "error",
title: "Bot failed to restart",
message: errorMessage || "Check the logs for details.",
href: "/logs",
});
}
function notifyUpdateAvailable(info) {
return notificationStore.add({
id: "update-available",
type: "update",
title: "Update available",
message: `Version ${info.latest} is ready (you are on ${info.current}).`,
href: "/settings",
});
}
function notifyUpdateInstalled(message) {
return notificationStore.add({
type: "update",
title: "Update installed",
message:
message ||
"Files were updated. Restart your server (npm start) to finish applying changes.",
href: "/settings",
});
}
function clearUpdateAvailable() {
notificationStore.dismiss("update-available");
}
async function runUpdateCheck() {
const info = await fetchUpdateInfo();
if (info.updateAvailable) {
notifyUpdateAvailable(info);
} else {
clearUpdateAvailable();
}
return info;
}
module.exports = {
notifyBotRestart,
notifyUpdateAvailable,
notifyUpdateInstalled,
clearUpdateAvailable,
runUpdateCheck,
};
+86
View File
@@ -0,0 +1,86 @@
const MAX_NOTIFICATIONS = 50;
/** @type {Map<string, object>} */
const byId = new Map();
/** @type {string[]} */
let order = [];
/**
* @param {object} input
* @param {string} [input.id] Stable id replaces existing (e.g. update-available)
*/
function add(input) {
const id =
input.id ||
`n-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const item = {
id,
type: input.type || "info",
title: input.title || "Notification",
message: input.message || "",
href: input.href || null,
createdAt: input.createdAt || Date.now(),
read: false,
};
if (byId.has(id)) {
order = order.filter((x) => x !== id);
}
byId.set(id, item);
order.unshift(id);
while (order.length > MAX_NOTIFICATIONS) {
const removed = order.pop();
if (removed) byId.delete(removed);
}
return item;
}
function list() {
return order.map((id) => byId.get(id)).filter(Boolean);
}
function unreadCount() {
let n = 0;
for (const item of byId.values()) {
if (!item.read) n++;
}
return n;
}
function markRead(ids) {
if (ids === "all") {
for (const item of byId.values()) {
item.read = true;
}
return;
}
for (const id of ids) {
const item = byId.get(id);
if (item) item.read = true;
}
}
function dismiss(id) {
if (!byId.has(id)) return false;
byId.delete(id);
order = order.filter((x) => x !== id);
return true;
}
function clear() {
byId.clear();
order = [];
}
module.exports = {
add,
list,
unreadCount,
markRead,
dismiss,
clear,
};
+9 -395
View File
@@ -1,11 +1,12 @@
const fs = require("fs");
const fs = require("fs");
const path = require("path");
const Discord = require("discord.js");
const yaml = require("js-yaml");
const db = require("./Database.js");
const supportbot = yaml.load(fs.readFileSync("./Configs/supportbot.yml", "utf8"));
const msgconfig = yaml.load(fs.readFileSync("./Configs/messages.yml", "utf8"));
const supportbot = require("./ConfigStore").supportbot;
const msgconfig = require("./ConfigStore").messages;
const { createTranscriptHTML } = require("./TranscriptTemplate.js");
function escapeHtml(str = "") {
return String(str)
@@ -68,7 +69,7 @@ function renderAttachment(att) {
if (type === "image") {
return `
<div class="attachment">
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
<div class="attachment-preview attachment-image">
<img src="${url}" alt="${name}" loading="lazy">
</div>
@@ -79,7 +80,7 @@ function renderAttachment(att) {
if (type === "video") {
return `
<div class="attachment">
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
<div class="attachment-preview">
<video controls preload="metadata">
<source src="${url}">
@@ -92,7 +93,7 @@ function renderAttachment(att) {
if (type === "audio") {
return `
<div class="attachment">
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
<div class="attachment-preview">
<audio controls preload="metadata">
<source src="${url}">
@@ -104,7 +105,7 @@ function renderAttachment(att) {
return `
<div class="attachment">
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
</div>
`;
}
@@ -134,393 +135,6 @@ function renderEmbeds(embeds = []) {
.join("");
}
function createTranscriptHTML(ticket, reason) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transcript - ${escapeHtml(ticket.name)}</title>
<style>
:root {
--bg: #0b0f14;
--panel: #111821;
--panel-2: #182230;
--panel-3: #1d2938;
--border: #283548;
--text: #e6edf3;
--muted: #9fb0c3;
--accent: #22c55e;
--accent-soft: rgba(34, 197, 94, 0.12);
--code: #0f1720;
}
* {
box-sizing: border-box;
}
html, body {
margin: 0;
padding: 0;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
body {
padding: 32px 20px;
}
.page {
max-width: 1100px;
margin: 0 auto;
}
.header {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 16px;
padding: 24px;
margin-bottom: 18px;
}
.header-top {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
flex-wrap: wrap;
}
.title-wrap h1 {
margin: 0;
font-size: 1.8rem;
line-height: 1.2;
font-weight: 800;
letter-spacing: -0.02em;
}
.title-wrap p {
margin: 8px 0 0;
color: var(--muted);
font-size: 0.98rem;
}
.badge {
display: inline-flex;
align-items: center;
gap: 8px;
background: var(--accent-soft);
color: #8df0ad;
border: 1px solid rgba(34, 197, 94, 0.25);
padding: 8px 12px;
border-radius: 999px;
font-size: 0.9rem;
font-weight: 700;
white-space: nowrap;
}
.meta-grid {
margin-top: 18px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px;
}
.meta-card {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 12px;
padding: 14px;
}
.meta-label {
color: var(--muted);
font-size: 0.82rem;
margin-bottom: 6px;
text-transform: uppercase;
letter-spacing: 0.08em;
font-weight: 700;
}
.meta-value {
font-size: 0.98rem;
font-weight: 600;
word-break: break-word;
}
.messages-wrap {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 16px;
overflow: hidden;
}
.messages-header {
padding: 18px 20px;
border-bottom: 1px solid var(--border);
background: var(--panel-2);
font-weight: 800;
font-size: 1rem;
}
.message {
display: flex;
gap: 14px;
padding: 18px 20px;
border-bottom: 1px solid var(--border);
}
.message:last-child {
border-bottom: none;
}
.avatar {
width: 42px;
height: 42px;
min-width: 42px;
border-radius: 50%;
object-fit: cover;
background: var(--panel-3);
border: 1px solid var(--border);
}
.message-body {
min-width: 0;
flex: 1;
}
.message-header {
display: flex;
align-items: baseline;
gap: 10px;
flex-wrap: wrap;
margin-bottom: 8px;
}
.username {
font-weight: 800;
color: var(--text);
font-size: 0.98rem;
}
.userid {
color: var(--muted);
font-size: 0.8rem;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.timestamp {
color: var(--muted);
font-size: 0.82rem;
margin-left: auto;
}
.content {
color: var(--text);
font-size: 0.96rem;
line-height: 1.6;
word-break: break-word;
}
.content:empty {
display: none;
}
.discord-embed {
margin-top: 12px;
background: var(--panel-2);
border: 1px solid var(--border);
border-left: 4px solid var(--accent);
border-radius: 10px;
padding: 12px 14px;
}
.discord-embed-title {
font-weight: 800;
margin-bottom: 6px;
}
.discord-embed-description {
color: var(--text);
line-height: 1.5;
}
.embed-field {
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid rgba(255,255,255,0.06);
}
.embed-field-name {
font-weight: 700;
margin-bottom: 4px;
}
.embed-field-value {
color: var(--text);
line-height: 1.5;
}
.attachment {
margin-top: 12px;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 12px;
padding: 12px;
}
.attachment-file {
display: inline-block;
color: #8fd9a8;
text-decoration: none;
font-weight: 700;
word-break: break-word;
}
.attachment-file:hover {
text-decoration: underline;
}
.attachment-preview {
margin-top: 10px;
}
.attachment-preview img,
.attachment-preview video {
width: 100%;
max-width: 560px;
border-radius: 10px;
border: 1px solid var(--border);
display: block;
background: #0a0f15;
}
.attachment-preview audio {
width: 100%;
max-width: 560px;
display: block;
}
code {
background: var(--code);
border: 1px solid var(--border);
padding: 2px 6px;
border-radius: 6px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.9em;
}
pre {
background: var(--code);
border: 1px solid var(--border);
padding: 12px;
border-radius: 10px;
overflow-x: auto;
white-space: pre-wrap;
word-break: break-word;
}
pre code {
background: transparent;
border: none;
padding: 0;
}
a {
color: #8fd9ff;
}
.empty-state {
padding: 24px 20px;
color: var(--muted);
}
@media (max-width: 700px) {
body {
padding: 18px 12px;
}
.header,
.messages-wrap {
border-radius: 12px;
}
.message {
padding: 14px;
}
.timestamp {
width: 100%;
margin-left: 0;
}
}
</style>
</head>
<body>
<div class="page">
<section class="header">
<div class="header-top">
<div class="title-wrap">
<h1>Ticket Transcript</h1>
<p>Exported conversation log for support ticket <strong>${escapeHtml(ticket.name)}</strong></p>
</div>
<div class="badge">Closed Transcript</div>
</div>
<div class="meta-grid">
<div class="meta-card">
<div class="meta-label">Channel</div>
<div class="meta-value">${escapeHtml(ticket.name)}</div>
</div>
<div class="meta-card">
<div class="meta-label">Ticket ID</div>
<div class="meta-value">${escapeHtml(ticket.id)}</div>
</div>
<div class="meta-card">
<div class="meta-label">Message Count</div>
<div class="meta-value">${ticket.messages.length}</div>
</div>
<div class="meta-card">
<div class="meta-label">Close Reason</div>
<div class="meta-value">${escapeHtml(reason || "No Reason Provided.")}</div>
</div>
</div>
</section>
<section class="messages-wrap">
<div class="messages-header">Messages</div>
${
ticket.messages.length
? ticket.messages
.map(
(msg) => `
<article class="message">
<img src="${escapeHtml(msg.avatar || "")}" alt="Avatar" class="avatar">
<div class="message-body">
<div class="message-header">
<span class="username">${escapeHtml(msg.username || "Unknown User")}</span>
<span class="userid">${escapeHtml(msg.userId || "Unknown ID")}</span>
<span class="timestamp">${formatDate(msg.timestamp)}</span>
</div>
<div class="content">${parseMarkdown(msg.content || "")}</div>
${renderEmbeds(msg.embeds || [])}
${(msg.attachments || []).map(renderAttachment).join("")}
</div>
</article>
`,
)
.join("")
: `<div class="empty-state">No messages were found in this ticket.</div>`
}
</section>
</div>
</body>
</html>`;
}
async function createTranscript(interaction, ticket, reason) {
const { getChannel } = interaction.client;
@@ -633,4 +247,4 @@ async function createTranscript(interaction, ticket, reason) {
module.exports = {
createTranscript,
};
};
+223
View File
@@ -0,0 +1,223 @@
const fs = require('fs');
const path = require('path');
const TRANSCRIPT_DIR = path.join(__dirname, '../Data/Transcripts');
const SETTINGS_FILE = path.join(__dirname, '../Data/transcript-settings.json');
const DEFAULT_SETTINGS = {
autoDelete: {
enabled: false,
afterDays: 30,
},
publicAccess: {
enabled: false,
},
};
let purgeTimer = null;
function ensureTranscriptDir() {
if (!fs.existsSync(TRANSCRIPT_DIR)) {
fs.mkdirSync(TRANSCRIPT_DIR, { recursive: true });
}
}
function getSettings() {
try {
if (!fs.existsSync(SETTINGS_FILE)) {
return JSON.parse(JSON.stringify(DEFAULT_SETTINGS));
}
const raw = JSON.parse(fs.readFileSync(SETTINGS_FILE, 'utf8'));
const days = Number(raw?.autoDelete?.afterDays);
return {
autoDelete: {
enabled: Boolean(raw?.autoDelete?.enabled),
afterDays:
Number.isFinite(days) && days >= 1
? Math.min(Math.floor(days), 3650)
: DEFAULT_SETTINGS.autoDelete.afterDays,
},
publicAccess: {
enabled: Boolean(raw?.publicAccess?.enabled),
},
};
} catch {
return JSON.parse(JSON.stringify(DEFAULT_SETTINGS));
}
}
function saveSettings(patch) {
const current = getSettings();
const next = {
autoDelete: {
enabled:
patch?.autoDelete?.enabled !== undefined
? Boolean(patch.autoDelete.enabled)
: current.autoDelete.enabled,
afterDays:
patch?.autoDelete?.afterDays !== undefined
? Math.min(
Math.max(Math.floor(Number(patch.autoDelete.afterDays) || 1), 1),
3650,
)
: current.autoDelete.afterDays,
},
publicAccess: {
enabled:
patch?.publicAccess?.enabled !== undefined
? Boolean(patch.publicAccess.enabled)
: current.publicAccess.enabled,
},
};
const dir = path.dirname(SETTINGS_FILE);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(SETTINGS_FILE, JSON.stringify(next, null, 2), 'utf8');
return next;
}
function normalizeId(rawId) {
return String(rawId).replace(/[^0-9]/g, '');
}
function readTranscriptFile(rawId) {
const id = normalizeId(rawId);
if (!id) return null;
ensureTranscriptDir();
const filePath = path.join(TRANSCRIPT_DIR, `${id}-transcript.html`);
if (!fs.existsSync(filePath)) return null;
const content = fs.readFileSync(filePath, 'utf8');
const titleMatch = content.match(/<title>\s*Transcript\s*-\s*([^<]+)\s*<\/title>/i);
return {
id,
filePath,
filename: `${id}-transcript.html`,
content,
ticketName: titleMatch ? titleMatch[1].trim() : null,
};
}
function listTranscripts() {
ensureTranscriptDir();
if (!fs.existsSync(TRANSCRIPT_DIR)) {
return [];
}
return fs
.readdirSync(TRANSCRIPT_DIR)
.filter((f) => f.endsWith('-transcript.html'))
.map((f) => {
const id = f.replace('-transcript.html', '');
const stats = fs.statSync(path.join(TRANSCRIPT_DIR, f));
const parsed = readTranscriptFile(id);
return {
id,
filename: f,
createdAt: stats.mtime.toISOString(),
size: stats.size,
ticketName: parsed?.ticketName ?? null,
};
})
.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
}
function deleteTranscript(rawId) {
const id = normalizeId(rawId);
if (!id) return false;
const filePath = path.join(TRANSCRIPT_DIR, `${id}-transcript.html`);
if (!fs.existsSync(filePath)) return false;
fs.unlinkSync(filePath);
return true;
}
function purgeExpiredTranscripts() {
const settings = getSettings();
if (!settings.autoDelete.enabled) {
return { deleted: 0, skipped: true };
}
ensureTranscriptDir();
const maxAgeMs = settings.autoDelete.afterDays * 24 * 60 * 60 * 1000;
const cutoff = Date.now() - maxAgeMs;
let deleted = 0;
for (const f of fs.readdirSync(TRANSCRIPT_DIR)) {
if (!f.endsWith('-transcript.html')) continue;
const filePath = path.join(TRANSCRIPT_DIR, f);
const stats = fs.statSync(filePath);
if (stats.mtime.getTime() < cutoff) {
fs.unlinkSync(filePath);
deleted += 1;
}
}
return { deleted, skipped: false };
}
function notFoundHtml(message = 'Transcript not found') {
return `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Transcript</title>
<style>body{font-family:system-ui,sans-serif;padding:2rem;background:#0b0f14;color:#e6edf3;margin:0}</style></head>
<body><h1>${message}</h1></body></html>`;
}
function servePublicTranscript(req, res) {
const settings = getSettings();
if (!settings.publicAccess.enabled) {
return res.status(404).type('html').send(notFoundHtml('Transcript not found'));
}
const transcript = readTranscriptFile(req.params.id);
if (!transcript) {
return res.status(404).type('html').send(notFoundHtml('Transcript not found'));
}
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Cache-Control', 'public, max-age=120');
return res.send(transcript.content);
}
function startAutoDeleteScheduler(intervalMs = 60 * 60 * 1000) {
if (purgeTimer) return;
const run = () => {
try {
const result = purgeExpiredTranscripts();
if (result.deleted > 0) {
console.log(
`[Transcripts] Auto-deleted ${result.deleted} transcript(s) older than ${getSettings().autoDelete.afterDays} day(s)`,
);
}
} catch (err) {
console.error('[Transcripts] Auto-delete failed:', err.message);
}
};
run();
purgeTimer = setInterval(run, intervalMs);
if (typeof purgeTimer.unref === 'function') {
purgeTimer.unref();
}
}
function getPublicUrl(req, id) {
const settings = getSettings();
if (!settings.publicAccess.enabled) return null;
const host = req.get('host');
const proto = req.get('x-forwarded-proto') || req.protocol || 'http';
return `${proto}://${host}/transcripts/${id}`;
}
module.exports = {
TRANSCRIPT_DIR,
DEFAULT_SETTINGS,
getSettings,
saveSettings,
readTranscriptFile,
listTranscripts,
deleteTranscript,
purgeExpiredTranscripts,
servePublicTranscript,
startAutoDeleteScheduler,
getPublicUrl,
};
+680
View File
@@ -0,0 +1,680 @@
const fs = require("fs");
const path = require("path");
const yaml = require("js-yaml");
const {
normalizeFontFamily,
resolveTypography,
} = require("./googleFonts.js");
const TEMPLATE_PATH = path.join(__dirname, "../Configs/transcript-template.yml");
let cachedTemplate = null;
function escapeHtml(str = "") {
return String(str)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function parseMarkdown(content = "") {
let safe = escapeHtml(content);
safe = safe.replace(/```([\s\S]*?)```/g, "<pre><code>$1</code></pre>");
safe = safe.replace(/`(.*?)`/g, "<code>$1</code>");
safe = safe.replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>");
safe = safe.replace(/\*(.*?)\*/g, "<em>$1</em>");
safe = safe.replace(/_(.*?)_/g, "<em>$1</em>");
safe = safe.replace(
/\[(.*?)\]\((.*?)\)/g,
'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>',
);
return safe.replace(/\n/g, "<br>");
}
function formatDate(iso) {
try {
return new Date(iso).toLocaleString("en-GB", {
dateStyle: "medium",
timeStyle: "short",
});
} catch {
return iso;
}
}
function getFileTypeInfo(att) {
const fileName = String(att.name || "attachment").toLowerCase();
if (/\.(png|jpg|jpeg|gif|webp|bmp|svg)$/i.test(fileName)) {
return "image";
}
if (/\.(mp4|webm|mov|m4v)$/i.test(fileName)) {
return "video";
}
if (/\.(mp3|wav|ogg|m4a|flac)$/i.test(fileName)) {
return "audio";
}
return "file";
}
function renderAttachment(att) {
const url = escapeHtml(att.url || "");
const name = escapeHtml(att.name || "attachment");
const type = getFileTypeInfo(att);
if (type === "image") {
return `
<div class="attachment">
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
<div class="attachment-preview attachment-image">
<img src="${url}" alt="${name}" loading="lazy">
</div>
</div>
`;
}
if (type === "video") {
return `
<div class="attachment">
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
<div class="attachment-preview">
<video controls preload="metadata">
<source src="${url}">
</video>
</div>
</div>
`;
}
if (type === "audio") {
return `
<div class="attachment">
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
<div class="attachment-preview">
<audio controls preload="metadata">
<source src="${url}">
</audio>
</div>
</div>
`;
}
return `
<div class="attachment">
<a href="${url}" target="_blank" rel="noopener noreferrer" class="attachment-file">📎 ${name}</a>
</div>
`;
}
function renderEmbeds(embeds = []) {
return embeds
.map((embed) => {
const fields = (embed.fields || [])
.map(
(field) => `
<div class="embed-field">
<div class="embed-field-name">${escapeHtml(field.name || "Field")}</div>
<div class="embed-field-value">${parseMarkdown(field.value || "")}</div>
</div>
`,
)
.join("");
return `
<div class="discord-embed">
${embed.title ? `<div class="discord-embed-title">${escapeHtml(embed.title)}</div>` : ""}
${embed.description ? `<div class="discord-embed-description">${parseMarkdown(embed.description)}</div>` : ""}
${fields}
</div>
`;
})
.join("");
}
function deepMerge(base, patch) {
const out = structuredClone(base);
for (const [key, val] of Object.entries(patch || {})) {
if (
val &&
typeof val === "object" &&
!Array.isArray(val) &&
out[key] &&
typeof out[key] === "object" &&
!Array.isArray(out[key])
) {
out[key] = deepMerge(out[key], val);
} else {
out[key] = val;
}
}
return out;
}
function getDefaultTemplate() {
return {
Theme: {
Background: "#0b0f14",
Panel: "#111821",
PanelSecondary: "#182230",
PanelTertiary: "#1d2938",
Border: "#283548",
Text: "#e6edf3",
Muted: "#9fb0c3",
Accent: "#22c55e",
AccentSoft: "rgba(34, 197, 94, 0.12)",
AccentBorder: "rgba(34, 197, 94, 0.25)",
AccentText: "#8df0ad",
Link: "#8fd9ff",
AttachmentLink: "#8fd9a8",
CodeBackground: "#0f1720",
},
Typography: {
FontFamily: "Inter",
},
Header: {
Title: "Ticket Transcript",
Subtitle:
"Exported conversation log for support ticket **{{ticketName}}**",
Badge: "Closed Transcript",
ShowMetaCards: true,
},
Meta: {
ChannelLabel: "Channel",
TicketIdLabel: "Ticket ID",
MessageCountLabel: "Message Count",
CloseReasonLabel: "Close Reason",
DefaultCloseReason: "No Reason Provided.",
},
Messages: {
SectionTitle: "Messages",
EmptyState: "No messages were found in this ticket.",
},
Advanced: {
CustomCss: "",
},
};
}
function normalizeTemplate(raw) {
const merged = deepMerge(getDefaultTemplate(), raw || {});
if (merged.Typography) {
merged.Typography.FontFamily = normalizeFontFamily(
merged.Typography.FontFamily,
);
}
return merged;
}
function loadTemplateFromDisk() {
try {
if (!fs.existsSync(TEMPLATE_PATH)) {
const defaults = getDefaultTemplate();
fs.mkdirSync(path.dirname(TEMPLATE_PATH), { recursive: true });
fs.writeFileSync(TEMPLATE_PATH, yaml.dump(defaults), "utf8");
return defaults;
}
const parsed = yaml.load(fs.readFileSync(TEMPLATE_PATH, "utf8"));
return normalizeTemplate(parsed);
} catch (err) {
console.error("[TranscriptTemplate] Failed to load template:", err.message);
return getDefaultTemplate();
}
}
function getTemplate() {
if (!cachedTemplate) {
cachedTemplate = loadTemplateFromDisk();
}
return structuredClone(cachedTemplate);
}
function reloadTemplate() {
cachedTemplate = loadTemplateFromDisk();
return getTemplate();
}
function saveTemplate(data) {
const merged = normalizeTemplate(data);
fs.mkdirSync(path.dirname(TEMPLATE_PATH), { recursive: true });
fs.writeFileSync(TEMPLATE_PATH, yaml.dump(merged), "utf8");
cachedTemplate = merged;
return merged;
}
function applyPlaceholders(text, ctx) {
return String(text || "")
.replace(/\{\{ticketName\}\}/g, ctx.name || "")
.replace(/\{\{ticketId\}\}/g, ctx.id || "")
.replace(/\{\{messageCount\}\}/g, String(ctx.messageCount ?? 0))
.replace(/\{\{reason\}\}/g, ctx.reason || "");
}
function formatHeaderText(text, ctx) {
const withPlaceholders = applyPlaceholders(text, ctx);
const escaped = escapeHtml(withPlaceholders);
return escaped.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
}
function buildStyles(template) {
const t = template.Theme;
const { fontFamilyCss } = resolveTypography(template.Typography?.FontFamily);
const custom = String(template.Advanced?.CustomCss || "").trim();
return `
:root {
--bg: ${t.Background};
--panel: ${t.Panel};
--panel-2: ${t.PanelSecondary};
--panel-3: ${t.PanelTertiary};
--border: ${t.Border};
--text: ${t.Text};
--muted: ${t.Muted};
--accent: ${t.Accent};
--accent-soft: ${t.AccentSoft};
--accent-border: ${t.AccentBorder};
--accent-text: ${t.AccentText};
--link: ${t.Link};
--attachment-link: ${t.AttachmentLink};
--code: ${t.CodeBackground};
}
* { box-sizing: border-box; }
html, body {
margin: 0;
padding: 0;
background: var(--bg);
color: var(--text);
font-family: ${fontFamilyCss};
}
body { padding: 32px 20px; }
.page { max-width: 1100px; margin: 0 auto; }
.header {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 16px;
padding: 24px;
margin-bottom: 18px;
}
.header-top {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
flex-wrap: wrap;
}
.title-wrap h1 {
margin: 0;
font-size: 1.8rem;
line-height: 1.2;
font-weight: 800;
letter-spacing: -0.02em;
}
.title-wrap p {
margin: 8px 0 0;
color: var(--muted);
font-size: 0.98rem;
}
.badge {
display: inline-flex;
align-items: center;
gap: 8px;
background: var(--accent-soft);
color: var(--accent-text);
border: 1px solid var(--accent-border);
padding: 8px 12px;
border-radius: 999px;
font-size: 0.9rem;
font-weight: 700;
white-space: nowrap;
}
.meta-grid {
margin-top: 18px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px;
}
.meta-card {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 12px;
padding: 14px;
}
.meta-label {
color: var(--muted);
font-size: 0.82rem;
margin-bottom: 6px;
text-transform: uppercase;
letter-spacing: 0.08em;
font-weight: 700;
}
.meta-value {
font-size: 0.98rem;
font-weight: 600;
word-break: break-word;
}
.messages-wrap {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 16px;
overflow: hidden;
}
.messages-header {
padding: 18px 20px;
border-bottom: 1px solid var(--border);
background: var(--panel-2);
font-weight: 800;
font-size: 1rem;
}
.message {
display: flex;
gap: 14px;
padding: 18px 20px;
border-bottom: 1px solid var(--border);
}
.message:last-child { border-bottom: none; }
.avatar {
width: 42px;
height: 42px;
min-width: 42px;
border-radius: 50%;
object-fit: cover;
background: var(--panel-3);
border: 1px solid var(--border);
}
.message-body { min-width: 0; flex: 1; }
.message-header {
display: flex;
align-items: baseline;
gap: 10px;
flex-wrap: wrap;
margin-bottom: 8px;
}
.username {
font-weight: 800;
color: var(--text);
font-size: 0.98rem;
}
.userid {
color: var(--muted);
font-size: 0.8rem;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.timestamp {
color: var(--muted);
font-size: 0.82rem;
margin-left: auto;
}
.content {
color: var(--text);
font-size: 0.96rem;
line-height: 1.6;
word-break: break-word;
}
.content:empty { display: none; }
.discord-embed {
margin-top: 12px;
background: var(--panel-2);
border: 1px solid var(--border);
border-left: 4px solid var(--accent);
border-radius: 10px;
padding: 12px 14px;
}
.discord-embed-title { font-weight: 800; margin-bottom: 6px; }
.discord-embed-description { color: var(--text); line-height: 1.5; }
.embed-field {
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid rgba(255,255,255,0.06);
}
.embed-field-name { font-weight: 700; margin-bottom: 4px; }
.embed-field-value { color: var(--text); line-height: 1.5; }
.attachment {
margin-top: 12px;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 12px;
padding: 12px;
}
.attachment-file {
display: inline-block;
color: var(--attachment-link);
text-decoration: none;
font-weight: 700;
word-break: break-word;
}
.attachment-file:hover { text-decoration: underline; }
.attachment-preview { margin-top: 10px; }
.attachment-preview img,
.attachment-preview video {
width: 100%;
max-width: 560px;
border-radius: 10px;
border: 1px solid var(--border);
display: block;
background: #0a0f15;
}
.attachment-preview audio {
width: 100%;
max-width: 560px;
display: block;
}
code {
background: var(--code);
border: 1px solid var(--border);
padding: 2px 6px;
border-radius: 6px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.9em;
}
pre {
background: var(--code);
border: 1px solid var(--border);
padding: 12px;
border-radius: 10px;
overflow-x: auto;
white-space: pre-wrap;
word-break: break-word;
}
pre code { background: transparent; border: none; padding: 0; }
a { color: var(--link); }
.empty-state { padding: 24px 20px; color: var(--muted); }
@media (max-width: 700px) {
body { padding: 18px 12px; }
.header, .messages-wrap { border-radius: 12px; }
.message { padding: 14px; }
.timestamp { width: 100%; margin-left: 0; }
}
${custom}
`;
}
function getSampleTicket() {
return {
id: "123456789012345678",
name: "ticket-support-demo",
messages: [
{
username: "SupportBot",
userId: "100000000000000001",
avatar: "https://cdn.discordapp.com/embed/avatars/0.png",
timestamp: new Date().toISOString(),
content: "Hello! Thanks for opening a ticket. How can we help?",
embeds: [],
attachments: [],
},
{
username: "Member",
userId: "100000000000000002",
avatar: "https://cdn.discordapp.com/embed/avatars/1.png",
timestamp: new Date(Date.now() - 60000).toISOString(),
content: "I need help with my purchase — order **#48291**.",
embeds: [
{
title: "Order details",
description: "Payment received · awaiting delivery",
fields: [{ name: "Status", value: "Pending" }],
},
],
attachments: [],
},
],
};
}
function createTranscriptHTML(ticket, reason, templateInput) {
const template = templateInput
? normalizeTemplate(templateInput)
: getTemplate();
const header = template.Header;
const meta = template.Meta;
const messagesCfg = template.Messages;
const closeReason = reason || meta.DefaultCloseReason;
const ctx = {
name: ticket.name,
id: ticket.id,
messageCount: ticket.messages.length,
reason: closeReason,
};
const { headLinks } = resolveTypography(template.Typography?.FontFamily);
const metaSection = header.ShowMetaCards
? `
<div class="meta-grid">
<div class="meta-card">
<div class="meta-label">${escapeHtml(meta.ChannelLabel)}</div>
<div class="meta-value">${escapeHtml(ticket.name)}</div>
</div>
<div class="meta-card">
<div class="meta-label">${escapeHtml(meta.TicketIdLabel)}</div>
<div class="meta-value">${escapeHtml(ticket.id)}</div>
</div>
<div class="meta-card">
<div class="meta-label">${escapeHtml(meta.MessageCountLabel)}</div>
<div class="meta-value">${ticket.messages.length}</div>
</div>
<div class="meta-card">
<div class="meta-label">${escapeHtml(meta.CloseReasonLabel)}</div>
<div class="meta-value">${escapeHtml(closeReason)}</div>
</div>
</div>
`
: "";
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transcript - ${escapeHtml(ticket.name)}</title>
${headLinks}
<style>${buildStyles(template)}</style>
</head>
<body>
<div class="page">
<section class="header">
<div class="header-top">
<div class="title-wrap">
<h1>${escapeHtml(header.Title)}</h1>
<p>${formatHeaderText(header.Subtitle, ctx)}</p>
</div>
<div class="badge">${escapeHtml(header.Badge)}</div>
</div>
${metaSection}
</section>
<section class="messages-wrap">
<div class="messages-header">${escapeHtml(messagesCfg.SectionTitle)}</div>
${
ticket.messages.length
? ticket.messages
.map(
(msg) => `
<article class="message">
<img src="${escapeHtml(msg.avatar || "")}" alt="Avatar" class="avatar">
<div class="message-body">
<div class="message-header">
<span class="username">${escapeHtml(msg.username || "Unknown User")}</span>
<span class="userid">${escapeHtml(msg.userId || "Unknown ID")}</span>
<span class="timestamp">${formatDate(msg.timestamp)}</span>
</div>
<div class="content">${parseMarkdown(msg.content || "")}</div>
${renderEmbeds(msg.embeds || [])}
${(msg.attachments || []).map(renderAttachment).join("")}
</div>
</article>
`,
)
.join("")
: `<div class="empty-state">${escapeHtml(messagesCfg.EmptyState)}</div>`
}
</section>
</div>
</body>
</html>`;
}
function renderPreview(templateInput) {
const sample = getSampleTicket();
return createTranscriptHTML(
sample,
"Resolved — thank you for contacting support.",
templateInput,
);
}
module.exports = {
TEMPLATE_PATH,
getDefaultTemplate,
getTemplate,
reloadTemplate,
saveTemplate,
normalizeTemplate,
getSampleTicket,
createTranscriptHTML,
renderPreview,
};
+55
View File
@@ -0,0 +1,55 @@
const fs = require("fs");
const path = require("path");
const UPDATE_REPO = "C-h-a-r/SupportBot-Dashboard";
const UPDATE_BRANCH = "release";
function compareVersions(a, b) {
const pa = String(a)
.replace(/^v/i, "")
.split(".")
.map((n) => parseInt(n, 10) || 0);
const pb = String(b)
.replace(/^v/i, "")
.split(".")
.map((n) => parseInt(n, 10) || 0);
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
if ((pa[i] || 0) > (pb[i] || 0)) return 1;
if ((pa[i] || 0) < (pb[i] || 0)) return -1;
}
return 0;
}
async function fetchUpdateInfo() {
const axios = require("axios");
const pkgPath = path.join(__dirname, "../package.json");
const currentPkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
const current = currentPkg.version;
const remoteRes = await axios.get(
`https://raw.githubusercontent.com/${UPDATE_REPO}/${UPDATE_BRANCH}/package.json`,
{
timeout: 15000,
headers: { "User-Agent": "SupportBot-Dashboard" },
},
);
const latest = remoteRes.data?.version || current;
const updateAvailable = compareVersions(latest, current) > 0;
return {
current,
latest,
updateAvailable,
repository: `https://github.com/${UPDATE_REPO}`,
branch: UPDATE_BRANCH,
zipUrl: `https://github.com/${UPDATE_REPO}/archive/refs/heads/${UPDATE_BRANCH}.zip`,
};
}
module.exports = {
compareVersions,
fetchUpdateInfo,
UPDATE_REPO,
UPDATE_BRANCH,
};
+14
View File
@@ -0,0 +1,14 @@
function withTimeout(promise, ms, message) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => {
reject(new Error(message || `Timed out after ${ms}ms`));
}, ms);
});
return Promise.race([promise, timeout]).finally(() => {
clearTimeout(timer);
});
}
module.exports = { withTimeout };
+84
View File
@@ -0,0 +1,84 @@
/** Curated Google Fonts for transcript HTML (keep in sync with dashboard/src/lib/google-fonts.ts). */
const SYSTEM_FALLBACK =
'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
const GOOGLE_FONTS = [
{ id: "Inter", label: "Inter" },
{ id: "Roboto", label: "Roboto" },
{ id: "Open Sans", label: "Open Sans" },
{ id: "Lato", label: "Lato" },
{ id: "Montserrat", label: "Montserrat" },
{ id: "Poppins", label: "Poppins" },
{ id: "Nunito", label: "Nunito" },
{ id: "Raleway", label: "Raleway" },
{ id: "Work Sans", label: "Work Sans" },
{ id: "Source Sans 3", label: "Source Sans 3" },
{ id: "DM Sans", label: "DM Sans" },
{ id: "Manrope", label: "Manrope" },
{ id: "Outfit", label: "Outfit" },
{ id: "Rubik", label: "Rubik" },
{ id: "Ubuntu", label: "Ubuntu" },
{ id: "Fira Sans", label: "Fira Sans" },
{ id: "PT Sans", label: "PT Sans" },
{ id: "Noto Sans", label: "Noto Sans" },
{ id: "Oswald", label: "Oswald" },
{ id: "Merriweather", label: "Merriweather" },
{ id: "Playfair Display", label: "Playfair Display" },
{ id: "Libre Baskerville", label: "Libre Baskerville" },
{ id: "JetBrains Mono", label: "JetBrains Mono" },
{ id: "Fira Code", label: "Fira Code" },
];
const GOOGLE_FONT_IDS = new Set(GOOGLE_FONTS.map((f) => f.id));
function normalizeFontFamily(fontFamily) {
if (!fontFamily || typeof fontFamily !== "string") return "Inter";
const trimmed = fontFamily.trim();
if (trimmed === "system") return "system";
if (!trimmed.includes(",")) {
return GOOGLE_FONT_IDS.has(trimmed) ? trimmed : "Inter";
}
const match = trimmed.match(/^["']?([^"',]+)["']?/);
const first = match?.[1]?.trim();
if (first && GOOGLE_FONT_IDS.has(first)) return first;
return "Inter";
}
function googleFontsCssUrl(familyIds) {
const families = familyIds
.map((id) => {
const encoded = encodeURIComponent(id).replace(/%20/g, "+");
return `family=${encoded}:wght@400;600;700;800`;
})
.join("&");
return `https://fonts.googleapis.com/css2?${families}&display=swap`;
}
function resolveTypography(fontFamily) {
const id = normalizeFontFamily(fontFamily);
if (id === "system") {
return {
fontId: "system",
fontFamilyCss: SYSTEM_FALLBACK,
headLinks: "",
};
}
const url = googleFontsCssUrl([id]);
return {
fontId: id,
fontFamilyCss: `"${id}", ${SYSTEM_FALLBACK}`,
headLinks: `<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="${url}" rel="stylesheet">`,
};
}
module.exports = {
GOOGLE_FONTS,
GOOGLE_FONT_IDS,
SYSTEM_FALLBACK,
normalizeFontFamily,
googleFontsCssUrl,
resolveTypography,
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

+19 -9
View File
@@ -13,23 +13,33 @@
const fs = require("fs");
const path = require("path");
const yaml = require("js-yaml");
const supportbot = yaml.load(
fs.readFileSync("./Configs/supportbot.yml", "utf8")
);
const configStore = require("./Structures/ConfigStore.js");
const Client = require("./Structures/Client.js");
const client = new Client({
intents: ['Guilds', 'GuildMembers', 'GuildMessages', 'MessageContent']
intents: ["Guilds", "GuildMembers", "GuildMessages", "MessageContent"],
});
const APIServer = require("./API/server.js");
client.start(supportbot.General.Token);
// Start dashboard API immediately — do not wait for Discord clientReady
const api = new APIServer(client);
client.apiServer = api;
client.once('clientReady', () => {
const api = new APIServer(client);
api.start();
if (api.config?.Enabled) {
const port = api.config.Port || 3000;
api.start(port);
console.log(
`[Dashboard] API listening on http://localhost:${port} (bot may still be connecting)`,
);
} else {
console.warn("[Dashboard] API disabled in Configs/api.yml");
}
client.start(configStore.supportbot.General.Token);
client.on("clientReady", () => {
console.log("[Dashboard] Discord bot is ready — full stats and guild tools are available");
});
// SupportBot - New Logging System
+2479
View File
File diff suppressed because it is too large. Load diff
+4 -2
View File
@@ -1,11 +1,12 @@
{
"name": "supportbot",
"version": "26.1.1",
"version": "26.3.0",
"description": "SupportBot is an open-sourced support system for discord. It's completely free to use with high amounts of customization to match your own brand.",
"main": "index.js",
"scripts": {
"setup": "npm i && node index.js",
"start": "node index.js"
"start": "node index.js",
"git:setup": "node scripts/setup-git-security.js"
},
"repository": {
"type": "git",
@@ -21,6 +22,7 @@
"@vitalets/google-translate-api": "^9.2.1",
"axios": "^1.7.2",
"better-sqlite3": "^12.2.0",
"cookie-parser": "^1.4.7",
"cors": "^2.8.6",
"discord.js": "^14.13.0",
"express": "^5.2.1",
+191
View File
@@ -0,0 +1,191 @@
var RN=Object.defineProperty;var AN=(e,n,a)=>n in e?RN(e,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[n]=a;var m1=(e,n,a)=>AN(e,typeof n!="symbol"?n+"":n,a);function _N(e,n){for(var a=0;a<n.length;a++){const o=n[a];if(typeof o!="string"&&!Array.isArray(o)){for(const l in o)if(l!=="default"&&!(l in e)){const i=Object.getOwnPropertyDescriptor(o,l);i&&Object.defineProperty(e,l,i.get?i:{enumerable:!0,get:()=>o[l]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))o(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const d of i.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&o(d)}).observe(document,{childList:!0,subtree:!0});function a(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(l){if(l.ep)return;l.ep=!0;const i=a(l);fetch(l.href,i)}})();function Xx(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Rm={exports:{}},Nl={};/**
* @license React
* react-jsx-runtime.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var p1;function MN(){if(p1)return Nl;p1=1;var e=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function a(o,l,i){var d=null;if(i!==void 0&&(d=""+i),l.key!==void 0&&(d=""+l.key),"key"in l){i={};for(var m in l)m!=="key"&&(i[m]=l[m])}else i=l;return l=i.ref,{$$typeof:e,type:o,key:d,ref:l!==void 0?l:null,props:i}}return Nl.Fragment=n,Nl.jsx=a,Nl.jsxs=a,Nl}var h1;function ON(){return h1||(h1=1,Rm.exports=MN()),Rm.exports}var c=ON(),Am={exports:{}},_e={};/**
* @license React
* react.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var g1;function DN(){if(g1)return _e;g1=1;var e=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),l=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),d=Symbol.for("react.context"),m=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),v=Symbol.for("react.activity"),x=Symbol.iterator;function S(_){return _===null||typeof _!="object"?null:(_=x&&_[x]||_["@@iterator"],typeof _=="function"?_:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,N={};function E(_,O,H){this.props=_,this.context=O,this.refs=N,this.updater=H||j}E.prototype.isReactComponent={},E.prototype.setState=function(_,O){if(typeof _!="object"&&typeof _!="function"&&_!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,_,O,"setState")},E.prototype.forceUpdate=function(_){this.updater.enqueueForceUpdate(this,_,"forceUpdate")};function k(){}k.prototype=E.prototype;function A(_,O,H){this.props=_,this.context=O,this.refs=N,this.updater=H||j}var R=A.prototype=new k;R.constructor=A,C(R,E.prototype),R.isPureReactComponent=!0;var L=Array.isArray;function z(){}var B={H:null,A:null,T:null,S:null},U=Object.prototype.hasOwnProperty;function q(_,O,H){var I=H.ref;return{$$typeof:e,type:_,key:O,ref:I!==void 0?I:null,props:H}}function Z(_,O){return q(_.type,O,_.props)}function Q(_){return typeof _=="object"&&_!==null&&_.$$typeof===e}function fe(_){var O={"=":"=0",":":"=2"};return"$"+_.replace(/[=:]/g,function(H){return O[H]})}var de=/\/+/g;function ce(_,O){return typeof _=="object"&&_!==null&&_.key!=null?fe(""+_.key):O.toString(36)}function he(_){switch(_.status){case"fulfilled":return _.value;case"rejected":throw _.reason;default:switch(typeof _.status=="string"?_.then(z,z):(_.status="pending",_.then(function(O){_.status==="pending"&&(_.status="fulfilled",_.value=O)},function(O){_.status==="pending"&&(_.status="rejected",_.reason=O)})),_.status){case"fulfilled":return _.value;case"rejected":throw _.reason}}throw _}function M(_,O,H,I,V){var ne=typeof _;(ne==="undefined"||ne==="boolean")&&(_=null);var J=!1;if(_===null)J=!0;else switch(ne){case"bigint":case"string":case"number":J=!0;break;case"object":switch(_.$$typeof){case e:case n:J=!0;break;case y:return J=_._init,M(J(_._payload),O,H,I,V)}}if(J)return V=V(_),J=I===""?"."+ce(_,0):I,L(V)?(H="",J!=null&&(H=J.replace(de,"$&/")+"/"),M(V,O,H,"",function(G){return G})):V!=null&&(Q(V)&&(V=Z(V,H+(V.key==null||_&&_.key===V.key?"":(""+V.key).replace(de,"$&/")+"/")+J)),O.push(V)),1;J=0;var me=I===""?".":I+":";if(L(_))for(var pe=0;pe<_.length;pe++)I=_[pe],ne=me+ce(I,pe),J+=M(I,O,H,ne,V);else if(pe=S(_),typeof pe=="function")for(_=pe.call(_),pe=0;!(I=_.next()).done;)I=I.value,ne=me+ce(I,pe++),J+=M(I,O,H,ne,V);else if(ne==="object"){if(typeof _.then=="function")return M(he(_),O,H,I,V);throw O=String(_),Error("Objects are not valid as a React child (found: "+(O==="[object Object]"?"object with keys {"+Object.keys(_).join(", ")+"}":O)+"). If you meant to render a collection of children, use an array instead.")}return J}function K(_,O,H){if(_==null)return _;var I=[],V=0;return M(_,I,"","",function(ne){return O.call(H,ne,V++)}),I}function re(_){if(_._status===-1){var O=_._result;O=O(),O.then(function(H){(_._status===0||_._status===-1)&&(_._status=1,_._result=H)},function(H){(_._status===0||_._status===-1)&&(_._status=2,_._result=H)}),_._status===-1&&(_._status=0,_._result=O)}if(_._status===1)return _._result.default;throw _._result}var oe=typeof reportError=="function"?reportError:function(_){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var O=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof _=="object"&&_!==null&&typeof _.message=="string"?String(_.message):String(_),error:_});if(!window.dispatchEvent(O))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",_);return}console.error(_)},ee={map:K,forEach:function(_,O,H){K(_,function(){O.apply(this,arguments)},H)},count:function(_){var O=0;return K(_,function(){O++}),O},toArray:function(_){return K(_,function(O){return O})||[]},only:function(_){if(!Q(_))throw Error("React.Children.only expected to receive a single React element child.");return _}};return _e.Activity=v,_e.Children=ee,_e.Component=E,_e.Fragment=a,_e.Profiler=l,_e.PureComponent=A,_e.StrictMode=o,_e.Suspense=h,_e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=B,_e.__COMPILER_RUNTIME={__proto__:null,c:function(_){return B.H.useMemoCache(_)}},_e.cache=function(_){return function(){return _.apply(null,arguments)}},_e.cacheSignal=function(){return null},_e.cloneElement=function(_,O,H){if(_==null)throw Error("The argument must be a React element, bLine truncated
* @license React
* scheduler.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var b1;function LN(){return b1||(b1=1,(function(e){function n(M,K){var re=M.length;M.push(K);e:for(;0<re;){var oe=re-1>>>1,ee=M[oe];if(0<l(ee,K))M[oe]=K,M[re]=ee,re=oe;else break e}}function a(M){return M.length===0?null:M[0]}function o(M){if(M.length===0)return null;var K=M[0],re=M.pop();if(re!==K){M[0]=re;e:for(var oe=0,ee=M.length,_=ee>>>1;oe<_;){var O=2*(oe+1)-1,H=M[O],I=O+1,V=M[I];if(0>l(H,re))I<ee&&0>l(V,H)?(M[oe]=V,M[I]=re,oe=I):(M[oe]=H,M[O]=re,oe=O);else if(I<ee&&0>l(V,re))M[oe]=V,M[I]=re,oe=I;else break e}}return K}function l(M,K){var re=M.sortIndex-K.sortIndex;return re!==0?re:M.id-K.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var d=Date,m=d.now();e.unstable_now=function(){return d.now()-m}}var h=[],p=[],y=1,v=null,x=3,S=!1,j=!1,C=!1,N=!1,E=typeof setTimeout=="function"?setTimeout:null,k=typeof clearTimeout=="function"?clearTimeout:null,A=typeof setImmediate<"u"?setImmediate:null;function R(M){for(var K=a(p);K!==null;){if(K.callback===null)o(p);else if(K.startTime<=M)o(p),K.sortIndex=K.expirationTime,n(h,K);else break;K=a(p)}}function L(M){if(C=!1,R(M),!j)if(a(h)!==null)j=!0,z||(z=!0,fe());else{var K=a(p);K!==null&&he(L,K.startTime-M)}}var z=!1,B=-1,U=5,q=-1;function Z(){return N?!0:!(e.unstable_now()-q<U)}function Q(){if(N=!1,z){var M=e.unstable_now();q=M;var K=!0;try{e:{j=!1,C&&(C=!1,k(B),B=-1),S=!0;var re=x;try{t:{for(R(M),v=a(h);v!==null&&!(v.expirationTime>M&&Z());){var oe=v.callback;if(typeof oe=="function"){v.callback=null,x=v.priorityLevel;var ee=oe(v.expirationTime<=M);if(M=e.unstable_now(),typeof ee=="function"){v.callback=ee,R(M),K=!0;break t}v===a(h)&&o(h),R(M)}else o(h);v=a(h)}if(v!==null)K=!0;else{var _=a(p);_!==null&&he(L,_.startTime-M),K=!1}}break e}finally{v=null,x=re,S=!1}K=void 0}}finally{K?fe():z=!1}}}var fe;if(typeof A=="function")fe=function(){A(Q)};else if(typeof MessageChannel<"u"){var de=new MessageChannel,ce=de.port2;de.port1.onmessage=Q,fe=function(){ce.postMessage(null)}}else fe=function(){E(Q,0)};function he(M,K){B=E(function(){M(e.unstable_now())},K)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(M){M.callback=null},e.unstable_forceFrameRate=function(M){0>M||125<M?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):U=0<M?Math.floor(1e3/M):5},e.unstable_getCurrentPriorityLevel=function(){return x},e.unstable_next=function(M){switch(x){case 1:case 2:case 3:var K=3;break;default:K=x}var re=x;x=K;try{return M()}finally{x=re}},e.unstable_requestPaint=function(){N=!0},e.unstable_runWithPriority=function(M,K){switch(M){case 1:case 2:case 3:case 4:case 5:break;default:M=3}var re=x;x=M;try{return K()}finally{x=re}},e.unstable_scheduleCallback=function(M,K,re){var oe=e.unstable_now();switch(typeof re=="object"&&re!==null?(re=re.delay,re=typeof re=="number"&&0<re?oe+re:oe):re=oe,M){case 1:var ee=-1;break;case 2:ee=250;break;case 5:ee=1073741823;break;case 4:ee=1e4;break;default:ee=5e3}return ee=re+ee,M={id:y++,callback:K,priorityLevel:M,startTime:re,expirationTime:ee,sortIndex:-1},re>oe?(M.sortIndex=re,n(p,M),a(h)===null&&M===a(p)&&(C?(k(B),B=-1):C=!0,he(L,re-oe))):(M.sortIndex=ee,n(h,M),j||S||(j=!0,z||(z=!0,fe()))),M},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function(M){var K=x;return function(){var re=x;x=K;try{return M.apply(this,arguments)}finally{x=re}}}})(Om)),Om}var y1;function zN(){return y1||(y1=1,Mm.exports=LN()),Mm.exports}var Dm={exports:{}},Gt={};/**
* @license React
* react-dom.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var x1;function PN(){if(x1)return Gt;x1=1;var e=Cu();function n(h){var p="https://react.dev/errors/"+h;if(1<arguments.length){p+="?args[]="+encodeURIComponent(arguments[1]);for(var y=2;y<arguments.length;y++)p+="&args[]="+encodeURIComponent(arguments[y])}return"Minified React error #"+h+"; visit "+p+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(){}var o={d:{f:a,r:function(){throw Error(n(522))},D:a,C:a,L:a,m:a,X:a,S:a,M:a},p:0,findDOMNode:null},l=Symbol.for("react.portal");function i(h,p,y){var v=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:l,key:v==null?null:""+v,children:h,containerInfo:p,implementation:y}}var d=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function m(h,p){if(h==="font")return"";if(typeof p=="string")return p==="use-credentials"?p:""}return Gt.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=o,Gt.createPortal=function(h,p){var y=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!p||p.nodeType!==1&&p.nodeType!==9&&p.nodeType!==11)throw Error(n(299));return i(h,p,null,y)},Gt.flushSync=function(h){var p=d.T,y=o.p;try{if(d.T=null,o.p=2,h)return h()}finally{d.T=p,o.p=y,o.d.f()}},Gt.preconnect=function(h,p){typeof h=="string"&&(p?(p=p.crossOrigin,p=typeof p=="string"?p==="use-credentials"?p:"":void 0):p=null,o.d.C(h,p))},Gt.prefetchDNS=function(h){typeof h=="string"&&o.d.D(h)},Gt.preinit=function(h,p){if(typeof h=="string"&&p&&typeof p.as=="string"){var y=p.as,v=m(y,p.crossOrigin),x=typeof p.integrity=="string"?p.integrity:void 0,S=typeof p.fetchPriority=="string"?p.fetchPriority:void 0;y==="style"?o.d.S(h,typeof p.precedence=="string"?p.precedence:void 0,{crossOrigin:v,integrity:x,fetchPriority:S}):y==="script"&&o.d.X(h,{crossOrigin:v,integrity:x,fetchPriority:S,nonce:typeof p.nonce=="string"?p.nonce:void 0})}},Gt.preinitModule=function(h,p){if(typeof h=="string")if(typeof p=="object"&&p!==null){if(p.as==null||p.as==="script"){var y=m(p.as,p.crossOrigin);o.d.M(h,{crossOrigin:y,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0})}}else p==null&&o.d.M(h)},Gt.preload=function(h,p){if(typeof h=="string"&&typeof p=="object"&&p!==null&&typeof p.as=="string"){var y=p.as,v=m(y,p.crossOrigin);o.d.L(h,y,{crossOrigin:v,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0,type:typeof p.type=="string"?p.type:void 0,fetchPriority:typeof p.fetchPriority=="string"?p.fetchPriority:void 0,referrerPolicy:typeof p.referrerPolicy=="string"?p.referrerPolicy:void 0,imageSrcSet:typeof p.imageSrcSet=="string"?p.imageSrcSet:void 0,imageSizes:typeof p.imageSizes=="string"?p.imageSizes:void 0,media:typeof p.media=="string"?p.media:void 0})}},Gt.preloadModule=function(h,p){if(typeof h=="string")if(p){var y=m(p.as,p.crossOrigin);o.d.m(h,{as:typeof p.as=="string"&&p.as!=="script"?p.as:void 0,crossOrigin:y,integrity:typeof p.integrity=="string"?p.integrity:void 0})}else o.d.m(h)},Gt.requestFormReset=function(h){o.d.r(h)},Gt.unstable_batchedUpdates=function(h,p){return h(p)},Gt.useFormState=function(h,p,y){return d.H.useFormState(h,p,y)},Gt.useFormStatus=function(){return d.H.useHostTransitionStatus()},Gt.version="19.2.6",Gt}var S1;function Zx(){if(S1)return Dm.exports;S1=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(n){console.error(n)}}return e(),Dm.exports=PN(),Dm.exports}/**
* @license React
* react-dom-client.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var w1;function BN(){if(w1)return kl;w1=1;var e=zN(),n=Cu(),a=Zx();function o(t){var r="https://react.dev/errors/"+t;if(1<arguments.length){r+="?args[]="+encodeURIComponent(arguments[1]);for(var s=2;s<arguments.length;s++)r+="&args[]="+encodeURIComponent(arguments[s])}return"Minified React error #"+t+"; visit "+r+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function l(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)}function i(t){var r=t,s=t;if(t.alternate)for(;r.return;)r=r.return;else{t=r;do r=t,(r.flags&4098)!==0&&(s=r.return),t=r.return;while(t)}return r.tag===3?s:null}function d(t){if(t.tag===13){var r=t.memoizedState;if(r===null&&(t=t.alternate,t!==null&&(r=t.memoizedState)),r!==null)return r.dehydrated}return null}function m(t){if(t.tag===31){var r=t.memoizedState;if(r===null&&(t=t.alternate,t!==null&&(r=t.memoizedState)),r!==null)return r.dehydrated}return null}function h(t){if(i(t)!==t)throw Error(o(188))}function p(t){var r=t.alternate;if(!r){if(r=i(t),r===null)throw Error(o(188));return r!==t?null:t}for(var s=t,u=r;;){var g=s.return;if(g===null)break;var b=g.alternate;if(b===null){if(u=g.return,u!==null){s=u;continue}break}if(g.child===b.child){for(b=g.child;b;){if(b===s)return h(g),t;if(b===u)return h(g),r;b=b.sibling}throw Error(o(188))}if(s.return!==u.return)s=g,u=b;else{for(var w=!1,T=g.child;T;){if(T===s){w=!0,s=g,u=b;break}if(T===u){w=!0,u=g,s=b;break}T=T.sibling}if(!w){for(T=b.child;T;){if(T===s){w=!0,s=b,u=g;break}if(T===u){w=!0,u=b,s=g;break}T=T.sibling}if(!w)throw Error(o(189))}}if(s.alternate!==u)throw Error(o(190))}if(s.tag!==3)throw Error(o(188));return s.stateNode.current===s?t:r}function y(t){var r=t.tag;if(r===5||r===26||r===27||r===6)return t;for(t=t.child;t!==null;){if(r=y(t),r!==null)return r;t=t.sibling}return null}var v=Object.assign,x=Symbol.for("react.element"),S=Symbol.for("react.transitional.element"),j=Symbol.for("react.portal"),C=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),E=Symbol.for("react.profiler"),k=Symbol.for("react.consumer"),A=Symbol.for("react.context"),R=Symbol.for("react.forward_ref"),L=Symbol.for("react.suspense"),z=Symbol.for("react.suspense_list"),B=Symbol.for("react.memo"),U=Symbol.for("react.lazy"),q=Symbol.for("react.activity"),Z=Symbol.for("react.memo_cache_sentinel"),Q=Symbol.iterator;function fe(t){return t===null||typeof t!="object"?null:(t=Q&&t[Q]||t["@@iterator"],typeof t=="function"?t:null)}var de=Symbol.for("react.client.reference");function ce(t){if(t==null)return null;if(typeof t=="function")return t.$$typeof===de?null:t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case C:return"Fragment";case E:return"Profiler";case N:return"StrictMode";case L:return"Suspense";case z:return"SuspenseList";case q:return"Activity"}if(typeof t=="object")switch(t.$$typeof){case j:return"Portal";case A:return t.displayName||"Context";case k:return(t._context.displayName||"Context")+".Consumer";case R:var r=t.render;return t=t.displayName,t||(t=r.displayName||r.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case B:return r=t.displayName||null,r!==null?r:ce(t.type)||"Memo";case U:r=t._payload,t=t._init;try{return ce(t(r))}catch{}}return null}var he=Array.isArray,M=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,re={pending:!1,data:null,method:null,action:null},oe=[],ee=-1;function _(t){return{current:t}}function O(t){0>ee||(t.current=oe[ee],oe[ee]=null,ee--)}function H(t,r){ee++,oe[ee]=t.current,t.current=r}var I=_(null),V=_(null),ne=_(null),J=_(null);function me(t,r){switch(H(ne,r),H(V,t),H(I,null),r.nodeType){case 9:case 11:t=(t=r.documentElement)&&(t=t.namespaceURI)?zy(t):0;break;default:if(t=r.tagName,r=r.namespaceURI)r=zy(r),t=Py(r,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}O(I),H(I,t)}function pe(){O(I),O(V),O(ne)}function G(t){t.memoizedState!==null&&H(J,t);var r=I.current,s=Py(r,t.type);r!==s&&(H(V,t),H(I,s))}function se(t){V.current===t&&(O(I),O(V)),J.current===t&&(O(J),wl._currentValue=re)}var ge,je;function Ae(t){if(ge===void 0)try{throw Error()}catch(s){var r=s.stack.trim().match(/\n( *(at )?)/);ge=r&&r[1]||"",je=-1<s.stack.indexOf(`
at`)?" (<anonymous>)":-1<s.stack.indexOf("@")?"@unknown:0:0":""}return`
`+ge+t+je}var Qe=!1;function ct(t,r){if(!t||Qe)return"";Qe=!0;var s=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var u={DetermineComponentFrameRoot:function(){try{if(r){var le=function(){throw Error()};if(Object.defineProperty(le.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(le,[])}catch(X){var W=X}Reflect.construct(t,[],le)}else{try{le.call()}catch(X){W=X}t.call(le.prototype)}}else{try{throw Error()}catch(X){W=X}(le=t())&&typeof le.catch=="function"&&le.catch(function(){})}}catch(X){if(X&&W&&typeof X.stack=="string")return[X.stack,W.stack]}return[null,null]}};u.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var g=Object.getOwnPropertyDescriptor(u.DetermineComponentFrameRoot,"name");g&&g.configurable&&Object.defineProperty(u.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var b=u.DetermineComponentFrameRoot(),w=b[0],T=b[1];if(w&&T){var D=w.split(`
`),Y=T.split(`
`);for(g=u=0;u<D.length&&!D[u].includes("DetermineComponentFrameRoot");)u++;for(;g<Y.length&&!Y[g].includes("DetermineComponentFrameRoot");)g++;if(u===D.length||g===Y.length)for(u=D.length-1,g=Y.length-1;1<=u&&0<=g&&D[u]!==Y[g];)g--;for(;1<=u&&0<=g;u--,g--)if(D[u]!==Y[g]){if(u!==1||g!==1)do if(u--,g--,0>g||D[u]!==Y[g]){var te=`
`+D[u].replace(" at new "," at ");return t.displayName&&te.includes("<anonymous>")&&(te=te.replace("<anonymous>",t.displayName)),te}while(1<=u&&0<=g);break}}}finally{Qe=!1,Error.prepareStackTrace=s}return(s=t?t.displayName||t.name:"")?Ae(s):""}function Tt(t,r){switch(t.tag){case 26:case 27:case 5:return Ae(t.type);case 16:return Ae("Lazy");case 13:return t.child!==r&&r!==null?Ae("Suspense Fallback"):Ae("Suspense");case 19:return Ae("SuspenseList");case 0:case 15:return ct(t.type,!1);case 11:return ct(t.type.render,!1);case 1:return ct(t.type,!0);case 31:return Ae("Activity");default:return""}}function Ca(t){try{var r="",s=null;do r+=Tt(t,s),s=t,t=t.return;while(t);return r}catch(u){return`
Error generating stack: `+u.message+`
`+u.stack}}var Rt=Object.prototype.hasOwnProperty,Os=e.unstable_scheduleCallback,Ds=e.unstable_cancelCallback,Yt=e.unstable_shouldYield,$r=e.unstable_requestPaint,Wt=e.unstable_now,gd=e.unstable_getCurrentPriorityLevel,ja=e.unstable_ImmediatePriority,xi=e.unstable_UserBlockingPriority,Ea=e.unstable_NormalPriority,Ls=e.unstable_LowPriority,dr=e.unstable_IdlePriority,Si=e.log,Ir=e.unstable_setDisableYieldValue,Na=null,qt=null;function $n(t){if(typeof Si=="function"&&Ir(t),qt&&typeof qt.setStrictMode=="function")try{qt.setStrictMode(Na,t)}catch{}}var Ht=Math.clz32?Math.clz32:Xn,vd=Math.log,zs=Math.LN2;function Xn(t){return t>>>=0,t===0?32:31-(vd(t)/zs|0)|0}var fo=256,mo=262144,ka=4194304;function Zn(t){var r=t&42;if(r!==0)return r;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function Te(t,r,s){var u=t.pendingLanes;if(u===0)return 0;var g=0,b=t.suspendedLanes,w=t.pingedLanes;t=t.warmLanes;var T=u&134217727;return T!==0?(u=T&~b,u!==0?g=Zn(u):(w&=T,w!==0?g=Zn(w):s||(s=T&~t,s!==0&&(g=Zn(s))))):(T=u&~b,T!==0?g=Zn(T):w!==0?g=Zn(w):s||(s=u&~t,s!==0&&(g=Zn(s)))),g===0?0:r!==0&&r!==g&&(r&b)===0&&(b=g&-g,s=r&-r,b>=s||b===32&&(s&4194048)!==0)?r:g}function ut(t,r){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&r)===0}function At(t,r){switch(t){case 1:case 2:case 4:case 8:case 64:return r+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var t=ka;return ka<<=1,(ka&62914560)===0&&(ka=4194304),t}function Ur(t){for(var r=[],s=0;31>s;s++)r.push(t);return r}function mt(t,r){t.pendingLanes|=r,r!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function Zt(t,r,s,u,g,b){var w=t.pendingLanes;t.pendingLanes=s,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=s,t.entangledLanes&=s,t.errorRecoveryDisabledLanes&=s,t.shellSuspendCounter=0;var T=t.entanglements,D=t.expirationTimes,Y=t.hiddenUpdates;for(s=w&~s;0<s;){var te=31-Ht(s),le=1<<te;T[te]=0,D[te]=-1;var W=Y[te];if(W!==null)for(Y[te]=null,te=0;te<W.length;te++){var X=W[te];X!==null&&(X.lane&=-536870913)}s&=~le}u!==0&&Ta(t,u,0),b!==0&&g===0&&t.tag!==0&&(t.suspendedLanes|=b&~(w&~r))}function Ta(t,r,s){t.pendingLanes|=r,t.suspendedLanes&=~r;var u=31-Ht(r);t.entangledLanes|=r,t.entanglements[u]=t.entanglements[u]|1073741824|s&261930}function Qt(t,r){var s=t.entangledLanes|=r;for(t=t.entanglements;s;){var u=31-Ht(s),g=1<<u;g&r|t[u]&r&&(t[u]|=r),s&=~g}}function Jt(t,r){var s=r&-r;return s=(s&42)!==0?1:po(s),(s&(t.suspendedLanes|r))!==0?0:s}function po(t){switch(t){case 2:t=1;break;case 8:t=4;break;case 32:t=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:t=128;break;case 268435456:t=134217728;break;default:t=0}return t}function In(t){return t&=-t,2<t?8<t?(t&134217727)!==0?32:268435456:8:2}function bd(){var t=K.p;return t!==0?t:(t=window.event,t===void 0?32:s1(t.type))}function wg(t,r){var s=K.p;try{return K.p=t,r()}finally{K.p=s}}var Hr=Math.random().toString(36).slice(2),Lt="__reactFiber$"+Hr,en="__reactProps$"+Hr,ho="__reactContainer$"+Hr,yd="__reactEvents$"+Hr,b5="__reactListeners$"+Hr,y5="__reactHandles$"+Hr,Cg="__reactResources$"+Hr,Ps="__reactMarker$"+Hr;function xd(t){delete t[Lt],delete t[en],delete t[yd],delete t[b5],delete t[y5]}function go(t){var r=t[Lt];if(r)return r;for(var s=t.parentNode;s;){if(r=s[ho]||s[Lt]){if(s=r.alternate,r.child!==null||s!==null&&s.child!==null)for(t=Gy(t);t!==null;){if(s=t[Lt])return s;t=Gy(t)}return r}t=s,s=t.parentNode}return null}function vo(t){if(t=t[Lt]||t[ho]){var r=t.tag;if(r===5||r===6||r===13||r===31||r===26||r===27||r===3)return t}return null}function Bs(t){var r=t.tag;if(r===5||r===26||r===27||r===6)return t.stateNode;throw Error(o(33))}function bo(t){var r=t[Cg];return r||(r=t[Cg]={hoistableStyles:new Map,hoistableScripts:new Map}),r}function _t(t){t[Ps]=!0}var jg=new Set,Eg={};function Ra(t,r){yo(t,r),yo(t+"Capture",r)}function yo(t,r){for(Eg[t]=r,t=0;t<r.length;t++)jg.add(r[t])}var x5=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\ Line truncated
`).replace(ZE,"")}function Dy(t,r){return r=Oy(r),Oy(t)===r}function et(t,r,s,u,g,b){switch(s){case"children":typeof u=="string"?r==="body"||r==="textarea"&&u===""||So(t,u):(typeof u=="number"||typeof u=="bigint")&&r!=="body"&&So(t,""+u);break;case"className":Ci(t,"class",u);break;case"tabIndex":Ci(t,"tabindex",u);break;case"dir":case"role":case"viewBox":case"width":case"height":Ci(t,s,u);break;case"style":Dg(t,u,b);break;case"data":if(r!=="object"){Ci(t,"data",u);break}case"src":case"href":if(u===""&&(r!=="a"||s!=="href")){t.removeAttribute(s);break}if(u==null||typeof u=="function"||typeof u=="symbol"||typeof u=="boolean"){t.removeAttribute(s);break}u=Ei(""+u),t.setAttribute(s,u);break;case"action":case"formAction":if(typeof u=="function"){t.setAttribute(s,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof b=="function"&&(s==="formAction"?(r!=="input"&&et(t,r,"name",g.name,g,null),et(t,r,"formEncType",g.formEncType,g,null),et(t,r,"formMethod",g.formMethod,g,null),et(t,r,"formTarget",g.formTarget,g,null)):(et(t,r,"encType",g.encType,g,null),et(t,r,"method",g.method,g,null),et(t,r,"target",g.target,g,null)));if(u==null||typeof u=="symbol"||typeof u=="boolean"){t.removeAttribute(s);break}u=Ei(""+u),t.setAttribute(s,u);break;case"onClick":u!=null&&(t.onclick=mr);break;case"onScroll":u!=null&&Pe("scroll",t);break;case"onScrollEnd":u!=null&&Pe("scrollend",t);break;case"dangerouslySetInnerHTML":if(u!=null){if(typeof u!="object"||!("__html"in u))throw Error(o(61));if(s=u.__html,s!=null){if(g.children!=null)throw Error(o(60));t.innerHTML=s}}break;case"multiple":t.multiple=u&&typeof u!="function"&&typeof u!="symbol";break;case"muted":t.muted=u&&typeof u!="function"&&typeof u!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(u==null||typeof u=="function"||typeof u=="boolean"||typeof u=="symbol"){t.removeAttribute("xlink:href");break}s=Ei(""+u),t.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",s);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":u!=null&&typeof u!="function"&&typeof u!="symbol"?t.setAttribute(s,""+u):t.removeAttribute(s);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":u&&typeof u!="function"&&typeof u!="symbol"?t.setAttribute(s,""):t.removeAttribute(s);break;case"capture":case"download":u===!0?t.setAttribute(s,""):u!==!1&&u!=null&&typeof u!="function"&&typeof u!="symbol"?t.setAttribute(s,u):t.removeAttribute(s);break;case"cols":case"rows":case"size":case"span":u!=null&&typeof u!="function"&&typeof u!="symbol"&&!isNaN(u)&&1<=u?t.setAttribute(s,u):t.removeAttribute(s);break;case"rowSpan":case"start":u==null||typeof u=="function"||typeof u=="symbol"||isNaN(u)?t.removeAttribute(s):t.setAttribute(s,u);break;case"popover":Pe("beforetoggle",t),Pe("toggle",t),wi(t,"popover",u);break;case"xlinkActuate":fr(t,"http://www.w3.org/1999/xlink","xlink:actuate",u);break;case"xlinkArcrole":fr(t,"http://www.w3.org/1999/xlink","xlink:arcrole",u);break;case"xlinkRole":fr(t,"http://www.w3.org/1999/xlink","xlink:role",u);break;case"xlinkShow":fr(t,"http://www.w3.org/1999/xlink","xlink:show",u);break;case"xlinkTitle":fr(t,"http://www.w3.org/1999/xlink","xlink:title",u);break;case"xlinkType":fr(t,"http://www.w3.org/1999/xlink","xlink:type",u);break;case"xmlBase":fr(t,"http://www.w3.org/XML/1998/namespace","xml:base",u);break;case"xmlLang":fr(t,"http://www.w3.org/XML/1998/namespace","xml:lang",u);break;case"xmlSpace":fr(t,"http://www.w3.org/XML/1998/namespace","xml:space",u);break;case"is":wi(t,"is",u);break;case"innerText":case"textContent":break;default:(!(2<s.length)||s[0]!=="o"&&s[0]!=="O"||s[1]!=="n"&&s[1]!=="N")&&(s=E5.get(s)||s,wi(t,s,u))}}function dm(t,r,s,u,g,b){switch(s){case"style":Dg(t,u,b);break;case"dangerouslySetInnerHTML":if(u!=null){if(typeof u!="object"||!("__html"in u))throw Error(o(61));if(s=u.__html,s!=null){if(g.children!=null)throw Error(o(60));t.innerHTML=s}}break;case"children":typeof u=="string"?So(t,u):(typeof u=="number"||typeof u=="bigint")&&So(t,""+u);break;case"onScroll":u!=null&&Pe("scroll",t);break;case"onScrollEnd":u!=null&&Pe("scrollend",t);break;case"onClick":u!=null&&(t.onclick=mr);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"inne Line truncated
* react-router v7.15.1
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/var j1="popstate";function E1(e){return typeof e=="object"&&e!=null&&"pathname"in e&&"search"in e&&"hash"in e&&"state"in e&&"key"in e}function UN(e={}){function n(o,l){var p;let i=(p=l.state)==null?void 0:p.masked,{pathname:d,search:m,hash:h}=i||o.location;return pp("",{pathname:d,search:m,hash:h},l.state&&l.state.usr||null,l.state&&l.state.key||"default",i?{pathname:o.location.pathname,search:o.location.search,hash:o.location.hash}:void 0)}function a(o,l){return typeof l=="string"?l:Il(l)}return VN(n,a,null,e)}function ft(e,n){if(e===!1||e===null||typeof e>"u")throw new Error(n)}function Pn(e,n){if(!e){typeof console<"u"&&console.warn(n);try{throw new Error(n)}catch{}}}function HN(){return Math.random().toString(36).substring(2,10)}function N1(e,n){return{usr:e.state,key:e.key,idx:n,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function pp(e,n,a=null,o,l){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof n=="string"?ws(n):n,state:a,key:n&&n.key||o||HN(),mask:l}}function Il({pathname:e="/",search:n="",hash:a=""}){return n&&n!=="?"&&(e+=n.charAt(0)==="?"?n:"?"+n),a&&a!=="#"&&(e+=a.charAt(0)==="#"?a:"#"+a),e}function ws(e){let n={};if(e){let a=e.indexOf("#");a>=0&&(n.hash=e.substring(a),e=e.substring(0,a));let o=e.indexOf("?");o>=0&&(n.search=e.substring(o),e=e.substring(0,o)),e&&(n.pathname=e)}return n}function VN(e,n,a,o={}){let{window:l=document.defaultView,v5Compat:i=!1}=o,d=l.history,m="POP",h=null,p=y();p==null&&(p=0,d.replaceState({...d.state,idx:p},""));function y(){return(d.state||{idx:null}).idx}function v(){m="POP";let N=y(),E=N==null?null:N-p;p=N,h&&h({action:m,location:C.location,delta:E})}function x(N,E){m="PUSH";let k=E1(N)?N:pp(C.location,N,E);p=y()+1;let A=N1(k,p),R=C.createHref(k.mask||k);try{d.pushState(A,"",R)}catch(L){if(L instanceof DOMException&&L.name==="DataCloneError")throw L;l.location.assign(R)}i&&h&&h({action:m,location:C.location,delta:1})}function S(N,E){m="REPLACE";let k=E1(N)?N:pp(C.location,N,E);p=y();let A=N1(k,p),R=C.createHref(k.mask||k);d.replaceState(A,"",R),i&&h&&h({action:m,location:C.location,delta:0})}function j(N){return GN(N)}let C={get action(){return m},get location(){return e(l,d)},listen(N){if(h)throw new Error("A history only accepts one active listener");return l.addEventListener(j1,v),h=N,()=>{l.removeEventListener(j1,v),h=null}},createHref(N){return n(l,N)},createURL:j,encodeLocation(N){let E=j(N);return{pathname:E.pathname,search:E.search,hash:E.hash}},push:x,replace:S,go(N){return d.go(N)}};return C}function GN(e,n=!1){let a="http://localhost";typeof window<"u"&&(a=window.location.origin!=="null"?window.location.origin:window.location.href),ft(a,"No window.location.(origin|href) available to create URL");let o=typeof e=="string"?e:Il(e);return o=o.replace(/ $/,"%20"),!n&&o.startsWith("//")&&(o=a+o),new URL(o,a)}function Qx(e,n,a="/"){return FN(e,n,a,!1)}function FN(e,n,a,o,l){let i=typeof n=="string"?ws(n):n,d=Or(i.pathname||"/",a);if(d==null)return null;let m=YN(e),h=null,p=a3(d);for(let y=0;h==null&&y<m.length;++y)h=n3(m[y],p,o);return h}function YN(e){let n=Jx(e);return WN(n),n}function Jx(e,n=[],a=[],o="",l=!1){let i=(d,m,h=l,p)=>{let y={relativePath:p===void 0?d.path||"":p,caseSensitive:d.caseSensitive===!0,childrenIndex:m,route:d};if(y.relativePath.startsWith("/")){if(!y.relativePath.startsWith(o)&&h)return;ft(y.relativePath.startsWith(o),`Absolute route path "${y.relativePath}" nested under path "${o}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),y.relativePath=y.relativePath.slice(o.length)}let v=Fn([o,y.relativePath]),x=a.concat(y);d.children&&d.children.length>0&&(ft(d.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${v}".`),Jx(d.children,n,x,v,h)),!(d.path==null&&!d.index)&&n.push({path:v,score:e3(v,d.index),routesMeta:x})};return e.forEach((d,m)=>{var h;if(d.path===""||!((h=d.path)!=null&&h.includes("?")))i(d,m);else for(let p of e0(d.path))i(d,m,!0,p)}),n}function e0(e){let n=e.split("/");if(n.length===0)return[];let[a,...o]=n,l=a.endsWith("?"),i=a.replace(/\?$/,"");if(o.length===0)return l?[i,""]:[i];let d=e0(o.join("/")),m=[];return m.push(...d.map(h=>h===""?i:[i,h].join("/"))),l&&m.push(...d),m.map(h=>e.startsWith("/")&&h===""?"/":h)}function WN(e){e.sort((n,a)=>n.score!==a.score?a.score-n.score:t3(n.routesMeta.map(o=>o.childrenIndex),a.routesMeta.map(o=>o.childrenIndex)))}var qN=/^:[\w-]+$/,KN=3,XN=2,ZN=1,QN=10,JN=-2,k1=e=>e==="*";function e3(e,n){let a=e.split("/"),o=a.length;return a.some(k1)&&(o+=JN),n&&(o+=XN),a.filter(l=>!k1(l)).reduce((l,i)=>l+(qN.test(i)?KN:i===""?ZN:QN),o)}function t3(e,n){return e.length===n.length&&e.slice(0,-1).every((o,l)=>o===n[l])?e[e.length-1]-n[n.length-1]:0}function n3(e,n,a=!1){let{routesMeta:o}=e,l={},i="/",d=[];for(let m=0;m<o.length;++m){let h=o[m],p=m===o.length-1,y=i==="/"?n:n.slice(i.length)||"/",v=au({path:h.relativePath,caseSensit Line truncated
Please change the parent <Route path="${E}"> to <Route path="${E==="/"?"*":`${E}/*`}">.`)}let y=Sn(),v;if(n){let E=typeof n=="string"?ws(n):n;ft(h==="/"||((N=E.pathname)==null?void 0:N.startsWith(h)),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${h}" but pathname "${E.pathname}" was given in the \`location\` prop.`),v=E}else v=y;let x=v.pathname||"/",S=x;if(h!=="/"){let E=h.replace(/^\//,"").split("/");S="/"+x.replace(/^\//,"").split("/").slice(E.length).join("/")}let j=a&&a.state.matches.length?a.state.matches.map(E=>Object.assign(E,{route:a.manifest[E.route.id]||E.route})):Qx(e,{pathname:S});Pn(p||j!=null,`No routes matched location "${v.pathname}${v.search}${v.hash}" `),Pn(j==null||j[j.length-1].route.element!==void 0||j[j.length-1].route.Component!==void 0||j[j.length-1].route.lazy!==void 0,`Matched leaf route at location "${v.pathname}${v.search}${v.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let C=_3(j&&j.map(E=>Object.assign({},E,{params:Object.assign({},d,E.params),pathname:Fn([h,o.encodeLocation?o.encodeLocation(E.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:E.pathname]),pathnameBase:E.pathnameBase==="/"?h:Fn([h,o.encodeLocation?o.encodeLocation(E.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:E.pathnameBase])})),l,a);return n&&C?f.createElement(Zl.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",mask:void 0,...v},navigationType:"POP"}},C):C}function k3(){let e=z3(),n=f3(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),a=e instanceof Error?e.stack:null,o="rgba(200,200,200, 0.5)",l={padding:"0.5rem",backgroundColor:o},i={padding:"2px 4px",backgroundColor:o},d=null;return console.error("Error handled by React Router default ErrorBoundary:",e),d=f.createElement(f.Fragment,null,f.createElement("p",null,"💿 Hey developer 👋"),f.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",f.createElement("code",{style:i},"ErrorBoundary")," or"," ",f.createElement("code",{style:i},"errorElement")," prop on your route.")),f.createElement(f.Fragment,null,f.createElement("h2",null,"Unexpected Application Error!"),f.createElement("h3",{style:{fontStyle:"italic"}},n),a?f.createElement("pre",{style:l},a):null,d)}var T3=f.createElement(k3,null),d0=class extends f.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,n){return n.location!==e.location||n.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:n.error,location:n.location,revalidation:e.revalidation||n.revalidation}}componentDidCatch(e,n){this.props.onError?this.props.onError(e,n):console.error("React Router caught the following error during render",e)}render(){let e=this.state.error;if(this.context&&typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){const a=S3(e.digest);a&&(e=a)}let n=e!==void 0?f.createElement(qn.Provider,{value:this.props.routeContext},f.createElement(ah.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?f.createElement(R3,{error:e},n):n}};d0.contextType=o0;var zm=new WeakMap;function R3({children:e,error:n}){let{basename:a}=f.useContext(xn);if(typeof n=="object"&&n&&"digest"in n&&typeof n.digest=="string"){let o=x3(n.digest);if(o){let l=zm.get(n);if(l)throw l;let i=r0(o.location,a);if(n0&&!zm.get(n))if(i.isExternal||o.reloadDocument)window.location.href=i.absoluteURL||i.to;else{const d=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:o.replace}));throw zm.set(n,d),d}return f.createElement("meta",{httpEquiv:"refresh",content:`0;url=${i.absoluteURL||i.to}`})}}return e}function A3({routeContext:e,match:n,children:a}){let o=f.useContext(Cs);return o&&o.static&&o.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=n.route.id),f.createElement(qn.Provider,{value:e},a)}function _3(e,n=[],a){let o=a==null?void 0:a.state;if(e==null){if(!o)return null;if(o.errors)e=o.matches;else if(n.length===0&&!o.initialized&&o.matches.length>0)e=o.matches;else return null}let l=e,i=o==null?void 0:o.errors;if(i!=null){let y=l.findIndex(v=>v.route.id&&(i==null?void 0:i[v.route.id])!==void 0);ft(y>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(i).join(",")}`),l=l.slice(0,Math.min(l.length,y+1))}let d=!1,m=-1;if(a&&o){d=o.renderFallback;for(let y=0;y<l.length;y++){let v=l[y];if((v.route.HyLine truncated
.`.concat(c6,` {
overflow: hidden `).concat(o,`;
padding-right: `).concat(m,"px ").concat(o,`;
}
body[`).concat(us,`] {
overflow: hidden `).concat(o,`;
overscroll-behavior: contain;
`).concat([n&&"position: relative ".concat(o,";"),a==="margin"&&`
padding-left: `.concat(l,`px;
padding-top: `).concat(i,`px;
padding-right: `).concat(d,`px;
margin-left:0;
margin-top:0;
margin-right: `).concat(m,"px ").concat(o,`;
`),a==="padding"&&"padding-right: ".concat(m,"px ").concat(o,";")].filter(Boolean).join(""),`
}
.`).concat(Qc,` {
right: `).concat(m,"px ").concat(o,`;
}
.`).concat(Jc,` {
margin-right: `).concat(m,"px ").concat(o,`;
}
.`).concat(Qc," .").concat(Qc,` {
right: 0 `).concat(o,`;
}
.`).concat(Jc," .").concat(Jc,` {
margin-right: 0 `).concat(o,`;
}
body[`).concat(us,`] {
`).concat(u6,": ").concat(m,`px;
}
`)},cx=function(){var e=parseInt(document.body.getAttribute(us)||"0",10);return isFinite(e)?e:0},R6=function(){f.useEffect(function(){return document.body.setAttribute(us,(cx()+1).toString()),function(){var e=cx()-1;e<=0?document.body.removeAttribute(us):document.body.setAttribute(us,e.toString())}},[])},A6=function(e){var n=e.noRelative,a=e.noImportant,o=e.gapMode,l=o===void 0?"margin":o;R6();var i=f.useMemo(function(){return N6(l)},[l]);return f.createElement(k6,{styles:T6(i,!n,l,a?"":"!important")})},Ep=!1;if(typeof window<"u")try{var Uc=Object.defineProperty({},"passive",{get:function(){return Ep=!0,!0}});window.addEventListener("test",Uc,Uc),window.removeEventListener("test",Uc,Uc)}catch{Ep=!1}var es=Ep?{passive:!1}:!1,_6=function(e){return e.tagName==="TEXTAREA"},P2=function(e,n){if(!(e instanceof Element))return!1;var a=window.getComputedStyle(e);return a[n]!=="hidden"&&!(a.overflowY===a.overflowX&&!_6(e)&&a[n]==="visible")},M6=function(e){return P2(e,"overflowY")},O6=function(e){return P2(e,"overflowX")},ux=function(e,n){var a=n.ownerDocument,o=n;do{typeof ShadowRoot<"u"&&o instanceof ShadowRoot&&(o=o.host);var l=B2(e,o);if(l){var i=$2(e,o),d=i[1],m=i[2];if(d>m)return!0}o=o.parentNode}while(o&&o!==a.body);return!1},D6=function(e){var n=e.scrollTop,a=e.scrollHeight,o=e.clientHeight;return[n,a,o]},L6=function(e){var n=e.scrollLeft,a=e.scrollWidth,o=e.clientWidth;return[n,a,o]},B2=function(e,n){return e==="v"?M6(n):O6(n)},$2=function(e,n){return e==="v"?D6(n):L6(n)},z6=function(e,n){return e==="h"&&n==="rtl"?-1:1},P6=function(e,n,a,o,l){var i=z6(e,window.getComputedStyle(n).direction),d=i*o,m=a.target,h=n.contains(m),p=!1,y=d>0,v=0,x=0;do{if(!m)break;var S=$2(e,m),j=S[0],C=S[1],N=S[2],E=C-N-i*j;(j||E)&&B2(e,m)&&(v+=E,x+=j);var k=m.parentNode;m=k&&k.nodeType===Node.DOCUMENT_FRAGMENT_NODE?k.host:k}while(!h&&m!==document.body||h&&(n.contains(m)||n===m));return(y&&Math.abs(v)<1||!y&&Math.abs(x)<1)&&(p=!0),p},Hc=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},dx=function(e){return[e.deltaX,e.deltaY]},fx=function(e){return e&&"current"in e?e.current:e},B6=function(e,n){return e[0]===n[0]&&e[1]===n[1]},$6=function(e){return`
.block-interactivity-`.concat(e,` {pointer-events: none;}
.allow-interactivity-`).concat(e,` {pointer-events: all;}
`)},I6=0,ts=[];function U6(e){var n=f.useRef([]),a=f.useRef([0,0]),o=f.useRef(),l=f.useState(I6++)[0],i=f.useState(z2)[0],d=f.useRef(e);f.useEffect(function(){d.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(l));var C=i6([e.lockRef.current],(e.shards||[]).map(fx),!0).filter(Boolean);return C.forEach(function(N){return N.classList.add("allow-interactivity-".concat(l))}),function(){document.body.classList.remove("block-interactivity-".concat(l)),C.forEach(function(N){return N.classList.remove("allow-interactivity-".concat(l))})}}},[e.inert,e.lockRef.current,e.shards]);var m=f.useCallback(function(C,N){if("touches"in C&&C.touches.length===2||C.type==="wheel"&&C.ctrlKey)return!d.current.allowPinchZoom;var E=Hc(C),k=a.current,A="deltaX"in C?C.deltaX:k[0]-E[0],R="deltaY"in C?C.deltaY:k[1]-E[1],L,z=C.target,B=Math.abs(A)>Math.abs(R)?"h":"v";if("touches"in C&&B==="h"&&z.type==="range")return!1;var U=window.getSelection(),q=U&&U.anchorNode,Z=q?q===z||q.contains(z):!1;if(Z)return!1;var Q=ux(B,z);if(!Q)return!0;if(Q?L=B:(L=B==="v"?"h":"v",Q=ux(B,z)),!Q)return!1;if(!o.current&&"changedTouches"in C&&(A||R)&&(o.current=L),!L)return!0;var fe=o.current||L;return P6(fe,N,C,fe==="h"?A:R)},[]),h=f.useCallback(function(C){var N=C;if(!(!ts.length||ts[ts.length-1]!==i)){var E="deltaY"in N?dx(N):Hc(N),k=n.current.filter(function(L){return L.name===N.type&&(L.target===N.target||N.target===L.shadowParent)&&B6(L.delta,E)})[0];if(k&&k.should){N.cancelable&&N.preventDefault();return}if(!k){var A=(d.current.shards||[]).map(fx).filter(Boolean).filter(function(L){return L.contains(N.target)}),R=A.length>0?m(N,A[0]):!d.current.noIsolation;R&&N.cancelable&&N.preventDefault()}}},[]),p=f.useCallback(function(C,N,E,k){var A={name:C,delta:N,target:E,should:k,shadowParent:H6(E)};n.current.push(A),setTimeout(function(){n.current=n.current.filter(function(R){return R!==A})},1)},[]),y=f.useCallback(function(C){a.current=Hc(C),o.current=void 0},[]),v=f.useCallback(function(C){p(C.type,dx(C),C.target,m(C,e.lockRef.current))},[]),x=f.useCallback(function(C){p(C.type,Hc(C),C.target,m(C,e.lockRef.current))},[]);f.useEffect(function(){return ts.push(i),e.setCallbacks({onScrollCapture:v,onWheelCapture:v,onTouchMoveCapture:x}),document.addEventListener("wheel",h,es),document.addEventListener("touchmove",h,es),document.addEventListener("touchstart",y,es),function(){ts=ts.filter(function(C){return C!==i}),document.removeEventListener("wheel",h,es),document.removeEventListener("touchmove",h,es),document.removeEventListener("touchstart",y,es)}},[]);var S=e.removeScrollBar,j=e.inert;return f.createElement(f.Fragment,null,j?f.createElement(i,{styles:$6(l)}):null,S?f.createElement(A6,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function H6(e){for(var n=null;e!==null;)e instanceof ShadowRoot&&(n=e.host,e=e.host),e=e.parentNode;return n}const V6=v6(L2,U6);var si=f.forwardRef(function(e,n){return f.createElement(Fu,or({},e,{ref:n,sideCar:V6}))});si.classNames=Fu.classNames;var Np=["Enter"," "],G6=["ArrowDown","PageUp","Home"],I2=["ArrowUp","PageDown","End"],F6=[...G6,...I2],Y6={ltr:[...Np,"ArrowRight"],rtl:[...Np,"ArrowLeft"]},W6={ltr:["ArrowLeft"],rtl:["ArrowRight"]},li="Menu",[Gl,q6,K6]=jh(li),[io,U2]=uk(li,[K6,ba,Vu]),Yu=ba(),H2=Vu(),[X6,co]=io(li),[Z6,ii]=io(li),V2=e=>{const{__scopeMenu:n,open:a=!1,children:o,dir:l,onOpenChange:i,modal:d=!0}=e,m=Yu(n),[h,p]=f.useState(null),y=f.useRef(!1),v=Ot(i),x=ei(l);return f.useEffect(()=>{const S=()=>{y.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},j=()=>y.current=!1;return document.addEventListener("keydown",S,{capture:!0}),()=>{document.removeEventListener("keydown",S,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),c.jsx(Iu,{...m,children:c.jsx(X6,{scope:n,open:a,onOpenChange:v,content:h,onContentChange:p,children:c.jsx(Z6,{scope:n,onClose:f.useCallback(()=>v(!1),[v]),isUsingKeyboardRef:y,dir:x,modal:d,children:o})})})};V2.displayName=li;var Q6="MenuAnchor",Oh=f.forwardRef((e,n)=>{const{__scopeMenu:a,...o}=e,l=Yu(a);return c.jsx(ri,{...l,...o,ref:n})});Oh.displayName=Q6;var Dh="MenuPortal",[J6,G2]=io(Dh,{forceMount:void 0}),F2=e=>{const{__scopeMenu:n,forceMount:a,children:o,container:l}=e,i=co(Dh,n);return c.jsx(J6,{scope:n,forceMount:a,children:c.jsx(Ut,{present:a||i.open,children:c.jsx(As,{asChild:!0,container:l,children:o})})})};F2.displayName=Dh;var zn="MenuContent",[eR,Lh]=io(zn),Y2=f.forwardRef((e,n)=>{const a=G2(zn,e.__scopeMenu),{forceMount:o=a.forceMount,...l}=e,i=co(zn,e.__scopeMenu),d=ii(zn,e.__scopeMenu);return c.jsx(Gl.Provider,{scope:e.__scopeMenu,children:c.jsx(Ut,{present:o||i.open,children:c.jsx(Gl.Slot,{scope:e.__scopeMenu,children:d.modal?c.jsx(tR,{...l,ref:n}):c.jsx(nR,{...l,ref:n})})})})}),tR=f.forwardRef((e,n)=>{const a=co(zn,e.__scopeMenu),o=f.useRe Line truncated
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const OS=(...e)=>e.filter((n,a,o)=>!!n&&n.trim()!==""&&o.indexOf(n)===a).join(" ").trim();/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const JR=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const eA=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,a,o)=>o?o.toUpperCase():a.toLowerCase());/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const px=e=>{const n=eA(e);return n.charAt(0).toUpperCase()+n.slice(1)};/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/var Qm={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const tA=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},nA=f.createContext({}),rA=()=>f.useContext(nA),aA=f.forwardRef(({color:e,size:n,strokeWidth:a,absoluteStrokeWidth:o,className:l="",children:i,iconNode:d,...m},h)=>{const{size:p=24,strokeWidth:y=2,absoluteStrokeWidth:v=!1,color:x="currentColor",className:S=""}=rA()??{},j=o??v?Number(a??y)*24/Number(n??p):a??y;return f.createElement("svg",{ref:h,...Qm,width:n??p??Qm.width,height:n??p??Qm.height,stroke:e??x,strokeWidth:j,className:OS("lucide",S,l),...!i&&!tA(m)&&{"aria-hidden":"true"},...m},[...d.map(([C,N])=>f.createElement(C,N)),...Array.isArray(i)?i:[i]])});/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const ya=(e,n)=>{const a=f.forwardRef(({className:o,...l},i)=>f.createElement(aA,{ref:i,iconNode:n,className:OS(`lucide-${JR(px(e))}`,`lucide-${e}`,o),...l}));return a.displayName=px(e),a};/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const oA=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],DS=ya("check",oA);/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const sA=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],LS=ya("chevron-down",sA);/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const lA=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],iA=ya("chevron-right",lA);/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const cA=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],uA=ya("chevron-up",cA);/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const dA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],fA=ya("circle",dA);/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const mA=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],pA=ya("panel-left",mA);/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const hA=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],gA=ya("search",hA);/**
* @license lucide-react v1.16.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const vA=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],zS=ya("x",vA),Ih=XR,Uh=ZR,bA=f.forwardRef(({className:e,inset:n,children:a,...o},l)=>c.jsxs(_S,{ref:l,className:ie("flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",n&&"pl-8",e),...o,children:[a,c.jsx(iA,{className:"ml-auto"})]}));bA.displayName=_S.displayName;const yA=f.forwardRef(({className:e,...n},a)=>c.jsx(MS,{ref:a,className:ie("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",e),...n}));yA.displayName=MS.displayName;const Ku=f.forwardRef(({className:e,sideOffset:n=4,...a},o)=>c.jsx(QR,{children:c.jsx(jS,{ref:o,sideOffset:n,className:ie("z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",e),...a})}));Ku.displayName=jS.displayName;const Yl=f.forwardRef(({className:e,inset:n,...a},o)=>c.jsx(NS,{ref:o,className:ie("relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",n&&"pl-8",e),...a}));Yl.displayName=NS.displayName;const xA=f.forwardRef(({className:e,children:n,checked:a,...o},l)=>c.jsxs(kS,{ref:l,className:ie("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:a,...o,children:[c.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:c.jsx(RS,{children:c.jsx(DS,{className:"h-4 w-4"})})}),n]}));xA.displayName=kS.displayName;const SA=f.forwardRef(({className:e,children:n,...a},o)=>c.jsxs(TS,{ref:o,className:ie("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...a,children:[c.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:c.jsx(RS,{children:c.jsx(fA,{className:"h-2 w-2 fill-current"})})}),n]}));SA.displayName=TS.displayName;const Hh=f.forwardRef(({className:e,inset:n,...a},o)=>c.jsx(ES,{ref:o,className:ie("px-2 py-1.5 text-sm font-semibold",n&&"pl-8",e),...a}));Hh.displayName=ES.displayName;const hu=f.forwardRef(({className:e,...n},a)=>c.jsx(AS,{ref:a,className:ie("-mx-1 my-1 h-px bg-muted",e),...n}));hu.displayName=AS.displayName;const Jm=768;function wA(){const[e,n]=f.useState(void 0);return f.useEffect(()=>{const a=window.matchMedia(`(max-width: ${Jm-1}px)`),o=()=>{n(window.innerWidth<Jm)};return a.addEventListener("change",o),n(window.innerWidth<Jm),()=>a.removeEventListener("change",o)},[]),!!e}const rt=f.forwardRef(({className:e,type:n,...a},o)=>c.jsx("input",{type:n,className:ie("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:o,...a}));rt.displayName="Input";var CA=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],wn=CA.reduce((e,n)=>{const a=K0(`Primitive.${n}`),o=f.forwardRef((l,i)=>{const{asChild:d,...m}=l,h=d?a:n;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c.jsx(h,{...m,ref:i})});return o.displayName=`Primitive.${n}`,{...e,[n]:o}},{}),jA="Separator",hx="horizontal",EA=["horizontal","vertical"],PS=f.forwardRef((e,n)=>{const{decorative:a,orientation:o=hx,...l}=e,i=NA(o)?o:hx,m=a?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};returnLine truncated
If you want to hide the \`${n.titleName}\`, you can wrap it with our VisuallyHidden component.
For more information, see https://radix-ui.com/primitives/docs/components/${n.docsSlug}`;return f.useEffect(()=>{e&&(document.getElementById(e)||console.error(a))},[a,e]),null},GA="DialogDescriptionWarning",FA=({contentRef:e,descriptionId:n})=>{const o=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${tw(GA).contentName}}.`;return f.useEffect(()=>{var i;const l=(i=e.current)==null?void 0:i.getAttribute("aria-describedby");n&&l&&(document.getElementById(n)||console.warn(o))},[o,e,n]),null},Yh=HS,Wh=FS,ui=YS,di=WS,Zu=KS,Qu=ZS,nw=JS;const YA=Yh,WA=Wh,rw=f.forwardRef(({className:e,...n},a)=>c.jsx(ui,{className:ie("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...n,ref:a}));rw.displayName=ui.displayName;const qA=Ns("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),aw=f.forwardRef(({side:e="right",className:n,children:a,...o},l)=>c.jsxs(WA,{children:[c.jsx(rw,{}),c.jsxs(di,{ref:l,className:ie(qA({side:e}),n),...o,children:[c.jsxs(nw,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[c.jsx(zS,{className:"h-4 w-4"}),c.jsx("span",{className:"sr-only",children:"Close"})]}),a]})]}));aw.displayName=di.displayName;const ow=({className:e,...n})=>c.jsx("div",{className:ie("flex flex-col space-y-2 text-center sm:text-left",e),...n});ow.displayName="SheetHeader";const sw=f.forwardRef(({className:e,...n},a)=>c.jsx(Zu,{ref:a,className:ie("text-lg font-semibold text-foreground",e),...n}));sw.displayName=Zu.displayName;const lw=f.forwardRef(({className:e,...n},a)=>c.jsx(Qu,{ref:a,className:ie("text-sm text-muted-foreground",e),...n}));lw.displayName=Qu.displayName;function Fe({className:e,...n}){return c.jsx("div",{className:ie("animate-pulse rounded-md bg-primary/10",e),...n})}function KA(e,n=[]){let a=[];function o(i,d){const m=f.createContext(d),h=a.length;a=[...a,d];const p=v=>{var E;const{scope:x,children:S,...j}=v,C=((E=x==null?void 0:x[e])==null?void 0:E[h])||m,N=f.useMemo(()=>j,Object.values(j));return c.jsx(C.Provider,{value:N,children:S})};p.displayName=i+"Provider";function y(v,x){var C;const S=((C=x==null?void 0:x[e])==null?void 0:C[h])||m,j=f.useContext(S);if(j)return j;if(d!==void 0)return d;throw new Error(`\`${v}\` must be used within \`${i}\``)}return[p,y]}const l=()=>{const i=a.map(d=>f.createContext(d));return function(m){const h=(m==null?void 0:m[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...m,[e]:h}}),[m,h])}};return l.scopeName=e,[o,XA(l,...n)]}function XA(...e){const n=e[0];if(e.length===1)return n;const a=()=>{const o=e.map(l=>({useScope:l(),scopeName:l.scopeName}));return function(i){const d=o.reduce((m,{useScope:h,scopeName:p})=>{const v=h(i)[`__scope${p}`];return{...m,...v}},{});return f.useMemo(()=>({[`__scope${n.scopeName}`]:d}),[d])}};return a.scopeName=n.scopeName,a}function ZA(e){const n=QA(e),a=f.forwardRef((o,l)=>{const{children:i,...d}=o,m=f.Children.toArray(i),h=m.find(e_);if(h){const p=h.props.children,y=m.map(v=>v===h?f.Children.count(p)>1?f.Children.only(null):f.isValidElement(p)?p.props.children:null:v);return c.jsx(n,{...d,ref:l,children:f.isValidElement(p)?f.cloneElement(p,void 0,y):null})}return c.jsx(n,{...d,ref:l,children:i})});return a.displayName=`${e}.Slot`,a}function QA(e){const n=f.forwardRef((a,o)=>{const{children:l,...i}=a;if(f.isValidElement(l)){const d=n_(l),m=t_(i,l.props);return l.type!==f.Fragment&&(m.ref=o?st(o,d):d),f.cloneElement(l,m)}return f.Children.count(l)>1?f.Children.only(null):null});return n.displayName=`${e}.SlotClone`,n}var iw=Symbol("radix.slottable");function JA(e){const n=({children:a})=>c.jsx(c.Fragment,{children:a});return n.displayName=`${e}.Slottable`,n.__radixId=iw,n}function e_(e){return f.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===iw}function t_(e,n){const a={...n};for(const o in n){const l=e[o],i=n[o];/^on[A-Z]/.test(o)?l&&i?a[o]=(...m)=>{const h=i(...m);return l(...m),h}:l&&(a[o]=l):o==="style"?a[o]={...l,...i}:o==="className"&&(a[o]=[l,i].filter(Boolean).join(" "))}return{...e,...a}}funct Line truncated
* @license React
* use-sync-external-store-shim.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var xx;function rM(){if(xx)return ap;xx=1;var e=Cu();function n(v,x){return v===x&&(v!==0||1/v===1/x)||v!==v&&x!==x}var a=typeof Object.is=="function"?Object.is:n,o=e.useState,l=e.useEffect,i=e.useLayoutEffect,d=e.useDebugValue;function m(v,x){var S=x(),j=o({inst:{value:S,getSnapshot:x}}),C=j[0].inst,N=j[1];return i(function(){C.value=S,C.getSnapshot=x,h(C)&&N({inst:C})},[v,S,x]),l(function(){return h(C)&&N({inst:C}),v(function(){h(C)&&N({inst:C})})},[v]),d(S),S}function h(v){var x=v.getSnapshot;v=v.value;try{var S=x();return!a(v,S)}catch{return!0}}function p(v,x){return x()}var y=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?p:m;return ap.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:y,ap}var Sx;function aM(){return Sx||(Sx=1,rp.exports=rM()),rp.exports}var oM=aM();function sM(){return oM.useSyncExternalStore(lM,()=>!0,()=>!1)}function lM(){return()=>{}}var tg="Avatar",[iM]=tM(tg),[cM,Ww]=iM(tg),qw=f.forwardRef((e,n)=>{const{__scopeAvatar:a,...o}=e,[l,i]=f.useState("idle");return c.jsx(cM,{scope:a,imageLoadingStatus:l,onImageLoadingStatusChange:i,children:c.jsx(wn.span,{...o,ref:n})})});qw.displayName=tg;var Kw="AvatarImage",Xw=f.forwardRef((e,n)=>{const{__scopeAvatar:a,src:o,onLoadingStatusChange:l=()=>{},...i}=e,d=Ww(Kw,a),m=uM(o,i),h=Ot(p=>{l(p),d.onImageLoadingStatusChange(p)});return Ct(()=>{m!=="idle"&&h(m)},[m,h]),m==="loaded"?c.jsx(wn.img,{...i,ref:n,src:o}):null});Xw.displayName=Kw;var Zw="AvatarFallback",Qw=f.forwardRef((e,n)=>{const{__scopeAvatar:a,delayMs:o,...l}=e,i=Ww(Zw,a),[d,m]=f.useState(o===void 0);return f.useEffect(()=>{if(o!==void 0){const h=window.setTimeout(()=>m(!0),o);return()=>window.clearTimeout(h)}},[o]),d&&i.imageLoadingStatus!=="loaded"?c.jsx(wn.span,{...l,ref:n}):null});Qw.displayName=Zw;function wx(e,n){return e?n?(e.src!==n&&(e.src=n),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function uM(e,{referrerPolicy:n,crossOrigin:a}){const o=sM(),l=f.useRef(null),i=o?(l.current||(l.current=new window.Image),l.current):null,[d,m]=f.useState(()=>wx(i,e));return Ct(()=>{m(wx(i,e))},[i,e]),Ct(()=>{const h=v=>()=>{m(v)};if(!i)return;const p=h("loaded"),y=h("error");return i.addEventListener("load",p),i.addEventListener("error",y),n&&(i.referrerPolicy=n),typeof a=="string"&&(i.crossOrigin=a),()=>{i.removeEventListener("load",p),i.removeEventListener("error",y)}},[i,a,n]),d}var Jw=qw,eC=Xw,tC=Qw;const gs=f.forwardRef(({className:e,...n},a)=>c.jsx(Jw,{ref:a,className:ie("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...n}));gs.displayName=Jw.displayName;const vs=f.forwardRef(({className:e,...n},a)=>c.jsx(eC,{ref:a,className:ie("aspect-square h-full w-full",e),...n}));vs.displayName=eC.displayName;const bs=f.forwardRef(({className:e,...n},a)=>c.jsx(tC,{ref:a,className:ie("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...n}));bs.displayName=tC.displayName;const nC=f.createContext(null);function dM({children:e}){const[n,a]=f.useState([]),[o,l]=f.useState(0),[i,d]=f.useState(!0),m=f.useCallback(async()=>{try{const v=await ke.getNotifications();v.data&&(a(v.data.items),l(v.data.unreadCount))}catch{}finally{d(!1)}},[]),h=f.useCallback(async()=>{var v;try{const x=await ke.markNotificationsRead("all");a(S=>S.map(j=>({...j,read:!0}))),l(((v=x.data)==null?void 0:v.unreadCount)??0)}catch{}},[]),p=f.useCallback(async v=>{var x;try{const S=await ke.dismissNotification(v);a(j=>j.filter(C=>C.id!==v)),l(((x=S.data)==null?void 0:x.unreadCount)??0)}catch{}},[]);f.useEffect(()=>{m();const v=setInterval(m,3e4);return()=>clearInterval(v)},[m]);const y=f.useMemo(()=>({items:n,unreadCount:o,loading:i,refresh:m,markAllRead:h,dismiss:p}),[n,o,i,m,h,p]);return c.jsx(nC.Provider,{value:y,children:e})}function fM(){const e=f.useContext(nC);if(!e)throw new Error("useNotifications must be used within NotificationsProvider");return e}const mM=Ns("inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Ll({className:e,variant:n,...a}){return c.jsx("div",{className:ie(mM({variant:n}),e),...a})}function pM(e){const n=hM(e),a=f.forwardRef((o,l)=>{const{children:i,...d}=o,m=f.Children.toArray(i),h=m.find(vM);if(h){const p=h.props.children,y=m.map(v=>v===h?f.Children.count(p)>1?f.Children.only(null):f.isValidElement(p)?p.props.children:null:v);return c.jsx(n,{...d,ref:l,children:f.isValidElement(p)?f.cloneElement(p,void 0,y):null})}return c.jsx(n,{...d,ref:l,children:i})});return a.displayName=`${e}.SLine truncated
--num-groups: ${i.groups.length};
--indicator-opacity: ${i.searchMode?0:1};
--num-skintones: ${Mx};`}),d(()=>{i.customEmoji&&i.database&&B()}),d(()=>{i.customEmoji&&i.customEmoji.length?i.groups!==Zp&&(i.groups=Zp):i.groups!==lp&&(i.currentGroupIndex&&i.currentGroupIndex--,i.groups=lp)}),d(()=>{async function G(){i.databaseLoaded&&(i.currentSkinTone=await i.database.getPreferredSkinTone())}G()}),d(()=>{i.skinTones=Array(Mx).fill().map((G,se)=>rz(i.skinToneEmoji,se))}),d(()=>{i.skinToneButtonText=i.skinTones[i.currentSkinTone]}),d(()=>{i.skinToneButtonLabel=i.i18n.skinToneLabel.replace("{skinTone}",i.i18n.skinTones[i.currentSkinTone])}),d(()=>{async function G(){const{database:se}=i,ge=(await Promise.all(WL.map(je=>se.getEmojiByUnicodeOrName(je)))).filter(Boolean);i.defaultFavoriteEmojis=ge}i.databaseLoaded&&G()});function B(){const{customEmoji:G,database:se}=i,ge=G||mp;se.customEmoji!==ge&&(se.customEmoji=ge)}d(()=>{async function G(){B();const{database:se,defaultFavoriteEmojis:ge,numColumns:je}=i,Ae=await se.getTopFavoriteEmoji(je),Qe=await ce(c5([...Ae,...ge],ct=>ct.unicode||ct.name).slice(0,je));i.currentFavorites=Qe}i.databaseLoaded&&i.defaultFavoriteEmojis&&G()});function U(G){sz(G,l,()=>{{const se=getComputedStyle(a.rootElement),ge=parseInt(se.getPropertyValue("--num-columns"),10),je=se.getPropertyValue("direction")==="rtl";i.numColumns=ge,i.isRtl=je}})}function q(G){Nz(G,l,se=>{for(const{target:ge,isIntersecting:je}of se)ge.classList.toggle("onscreen",je)})}d(()=>{async function G(){const{searchText:se,currentGroup:ge,databaseLoaded:je,customEmoji:Ae}=i;if(!je)i.currentEmojis=[],i.searchMode=!1;else if(se.length>=HL){const Qe=await M(se);i.searchText===se&&(S(Qe),j(!0))}else{const{id:Qe}=ge;if(Qe!==-1||Ae&&Ae.length){const ct=await he(Qe);i.currentGroup.id===Qe&&(S(ct),j(!1))}}}G()});const Z=()=>{tu(()=>uz(a.tabpanelElement))};d(()=>{const{currentEmojis:G,emojiVersion:se}=i,ge=G.filter(je=>je.unicode).filter(je=>Ox(je)&&!Qp.has(je.unicode));if(!se&&ge.length)S(G),tu(()=>Q(ge));else{const je=se?G:G.filter(fe);S(je),Z()}});function Q(G){iz(G,a.baselineEmoji,p)?Z():i.currentEmojis=[...i.currentEmojis]}function fe(G){return!G.unicode||!Ox(G)||Qp.get(G.unicode)}async function de(G){const se=i.emojiVersion||await cp();return G.filter(({version:ge})=>!ge||ge<=se)}async function ce(G){return az(G,i.emojiVersion||await cp())}async function he(G){const se=G===-1?i.customEmoji:await i.database.getEmojiByGroup(G);return ce(await de(se))}async function M(G){return ce(await de(await i.database.getEmojiBySearchQuery(G)))}d(()=>{}),d(()=>{function G(){const{searchMode:ge,currentEmojis:je}=i;if(ge)return[{category:"",emojis:je}];const Ae=new Map;for(const Qe of je){const ct=Qe.category||"";let Tt=Ae.get(ct);Tt||(Tt=[],Ae.set(ct,Tt)),Tt.push(Qe)}return[...Ae.entries()].map(([Qe,ct])=>({category:Qe,emojis:ct})).sort((Qe,ct)=>i.customCategorySorting(Qe.category,ct.category))}const se=G();C(se)}),d(()=>{i.activeSearchItemId=i.activeSearchItem!==-1&&i.currentEmojis[i.activeSearchItem].id}),d(()=>{const{rawSearchText:G}=i;l5(()=>{i.searchText=(G||"").trim(),i.activeSearchItem=-1})});function K(G){if(!i.searchMode||!i.currentEmojis.length)return;const se=ge=>{rr(G),i.activeSearchItem=up(ge,i.activeSearchItem,i.currentEmojis)};switch(G.key){case"ArrowDown":return se(!1);case"ArrowUp":return se(!0);case"Enter":if(i.activeSearchItem===-1)i.activeSearchItem=0;else return rr(G),_(i.currentEmojis[i.activeSearchItem].id)}}function re(G){const{target:se}=G,ge=se.closest(".nav-button");if(!ge)return;const je=parseInt(ge.dataset.groupId,10);a.searchElement.value="",i.rawSearchText="",i.searchText="",i.activeSearchItem=-1,i.currentGroupIndex=i.groups.findIndex(Ae=>Ae.id===je)}function oe(G){const{target:se,key:ge}=G,je=Ae=>{Ae&&(rr(G),Ae.focus())};switch(ge){case"ArrowLeft":return je(se.previousElementSibling);case"ArrowRight":return je(se.nextElementSibling);case"Home":return je(se.parentElement.firstElementChild);case"End":return je(se.parentElement.lastElementChild)}}async function ee(G){const se=await i.database.getEmojiByUnicodeOrName(G),ge=[...i.currentEmojis,...i.currentFavorites].find(Ae=>Ae.id===G),je=ge.unicode&&N(ge,i.currentSkinTone);return await i.database.incrementFavoriteEmojiCount(G),{emoji:se,skinTone:i.currentSkinTone,...je&&{unicode:je},...ge.name&&{name:ge.name}}}async function _(G){const se=ee(G);y("emoji-click-sync",se),y("emoji-click",await se)}function O(G){const{target:se}=G;if(!se.classList.contains("emoji"))return;rr(G);const ge=se.id.substring(4);_(ge)}function H(G){i.currentSkinTone=G,i.skinTonePickerExpanded=!1,h("skintone-button"),y("skin-tone-change",{skinTone:G}),i.database.setPreferredSkinTone(G)}function I(G){const{target:{id:se}}=G,ge=se&&se.match(/^skintone-(\d)/);if(!ge)return;rr(G);const je=parseInt(ge[1],10);H(je)}function V(G){i.skinTonePickerExpanded=!i.skinTonePickerExpanded,i.activeSkinTone=i.currentSkinTone,i.skinTonePickerExpanded&&(rr(G),tu(()=>h("skintone-list")))}d(()=>{i.skinTonePickerExpanded?a.skinToneDropdown.addEventListener("transitionend",()=>{i.s Line truncated
987654321098765432`,className:"min-h-[120px] font-mono text-sm"})]}),c.jsx(yi,{result:a.owners}),c.jsx("div",{className:"mt-auto",children:c.jsx(be,{type:"button",variant:"secondary",disabled:o||!e.ownerUserIds.trim(),onClick:l,children:o?"Checking with Discord…":"Verify owner IDs"})})]})}function BP({onContinue:e}){return c.jsx("div",{className:"mx-auto flex w-full max-w-lg flex-1 flex-col justify-center py-8",children:c.jsxs("div",{className:"rounded-2xl border border-border bg-card px-6 py-10 text-center md:px-10",children:[c.jsx("div",{className:"mx-auto mb-6 flex size-16 items-center justify-center rounded-2xl bg-primary/10 text-primary",children:c.jsx(ye,{icon:Tu,size:40})}),c.jsx("h2",{className:"text-2xl font-semibold tracking-tight",children:"Setup complete"}),c.jsxs("p",{className:"mx-auto mt-3 max-w-sm text-sm leading-relaxed text-muted-foreground",children:["Your configuration has been saved. Restart the server for changes to take effect — stop the running process, then start it again (for example"," ",c.jsx("code",{className:"rounded-md bg-muted px-1.5 py-0.5 font-mono text-xs",children:"npm start"}),")."]}),c.jsx(Ue,{className:"mt-6 text-left",children:c.jsx(He,{children:"After restarting, sign in with Discord to open the dashboard."})}),c.jsx(be,{type:"button",size:"lg",className:"mt-8 min-w-[220px]",onClick:e,children:"Continue to sign in"})]})})}function $P({currentIndex:e,validating:n,saving:a,onBack:o,onNext:l,onFinish:i}){const d=e===fs.length-1;return c.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[c.jsxs(be,{type:"button",variant:"ghost",disabled:e===0||a,onClick:o,children:[c.jsx(ye,{icon:b0,size:18,className:"mr-1"}),"Back"]}),c.jsx("div",{className:"flex flex-1 justify-end gap-2",children:d?c.jsx(be,{type:"button",size:"lg",disabled:a||n,onClick:i,className:"min-w-[200px]",children:a?"Saving…":"Finish setup"}):c.jsxs(be,{type:"button",size:"lg",disabled:n||a,onClick:l,children:["Continue",c.jsx(ye,{icon:ph,size:18,className:"ml-1"})]})})]})}function IP(){const e=crypto.randomUUID().replace(/-/g,""),n=crypto.randomUUID().replace(/-/g,"");return e+n}function UP(e){return e.split(/[\s,]+/).map(n=>n.trim()).filter(Boolean)}function Fx(e){return e==="oauth"?"oauth":e==="owners"?"owners":e}function HP(){const e=oo(),{branding:n}=Ou(),{loading:a,error:o,refresh:l,status:i}=yC(),[d,m]=f.useState(0),[h,p]=f.useState({botToken:"",secretKey:"",clientId:"",clientSecret:"",redirectUri:"",ownerUserIds:""}),[y,v]=f.useState({}),[x,S]=f.useState(!1),[j,C]=f.useState(!1),[N,E]=f.useState(""),[k,A]=f.useState(!1),R=fs[d];f.useEffect(()=>{i!=null&&i.suggestedRedirectUri&&!h.redirectUri&&p(Q=>({...Q,redirectUri:i.suggestedRedirectUri}))},[i==null?void 0:i.suggestedRedirectUri,h.redirectUri]);const L=f.useMemo(()=>({botToken:h.botToken,secretKey:h.secretKey,clientId:h.clientId,clientSecret:h.clientSecret,redirectUri:h.redirectUri,ownerUserIds:UP(h.ownerUserIds)}),[h]);async function z(){S(!0),E("");try{const Q=await ke.validateSetup(L);return v(fe=>{var de;return{...fe,...(de=Q.data)==null?void 0:de.results}}),Q.data}catch(Q){return E(Q instanceof Error?Q.message:"Validation failed"),null}finally{S(!1)}}async function B(){var de,ce;const Q=Fx(R.id),fe=await z();return!!((ce=(de=fe==null?void 0:fe.results)==null?void 0:de[Q])!=null&&ce.ok)}async function U(){const Q=Fx(R.id),fe=y[Q];!(fe!=null&&fe.ok)&&!await B()||m(de=>Math.min(de+1,fs.length-1))}async function q(){C(!0),E("");try{const Q=await z();if(!(Q!=null&&Q.ok)){E("Fix the steps marked with errors before finishing.");return}await ke.completeSetup(L),A(!0)}catch(Q){E(Q instanceof Error?Q.message:"Could not save setup")}finally{C(!1)}}function Z(){const Q={values:h,setValues:p,validation:y,validating:x};switch(R.id){case"botToken":return c.jsx(OP,{...Q,onValidate:()=>void B()});case"secretKey":return c.jsx(DP,{...Q,onGenerate:()=>p(fe=>({...fe,secretKey:IP()})),onValidate:()=>void B()});case"oauth":return c.jsx(LP,{...Q,onValidate:()=>void B()});case"redirectUri":return c.jsx(zP,{values:h,setValues:p,validation:y});case"owners":return c.jsx(PP,{...Q,onValidate:()=>void B()})}}return a?c.jsx("div",{className:"min-h-svh bg-background px-4 py-10",children:c.jsxs("div",{className:"mx-auto max-w-6xl space-y-8",children:[c.jsx(Fe,{className:"h-14 w-64"}),c.jsxs("div",{className:"grid gap-8 lg:grid-cols-[280px_1fr]",children:[c.jsx(Fe,{className:"hidden h-80 lg:block"}),c.jsx(Fe,{className:"h-[520px] rounded-2xl"})]})]})}):c.jsxs(AP,{brandingTitle:n.title,faviconUrl:n.faviconUrl,faviconVersion:n.updatedAt,hasFavicon:n.hasFavicon,children:[o?c.jsx(Ue,{variant:"destructive",className:"mb-6",children:c.jsx(He,{children:o})}):null,N?c.jsx(Ue,{variant:"destructive",className:"mb-6",children:c.jsx(He,{children:N})}):null,k?c.jsx(BP,{onContinue:async()=>{await l(),e("/login",{replace:!0})}}):c.jsxs("div",{className:"grid flex-1 gap-8 lg:grid-cols-[minmax(0,280px)_1fr]",children:[c.jsx(_P,{currentIndex:d,validation:y}) Line truncated
@@ -0,0 +1 @@
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Poppins,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}:root{--background: 240 10% 4%;--foreground: 0 0% 98%;--card: 240 7% 11%;--card-foreground: 0 0% 98%;--popover: 240 8% 10%;--popover-foreground: 0 0% 98%;--primary: 263 70% 58%;--primary-foreground: 0 0% 100%;--secondary: 240 6% 14%;--secondary-foreground: 0 0% 90%;--muted: 240 6% 14%;--muted-foreground: 240 5%Line truncated
+19
View File
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SupportBot Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,500;0,600;0,700;1,400&display=swap"
rel="stylesheet"
/>
<script type="module" crossorigin src="/assets/index-B9Fqpx9K.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-DOri9ZTI.css">
</head>
<body>
<div id="root"></div>
</body>
</html>