From 50665c8edd1aaccf18ab1176f186b3ea65fa2cf5 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Wed, 23 Sep 2026 18:25:28 +0200 Subject: [PATCH] refactor(all): uniformisation --- .editorconfig | 18 +- .env.example | 164 +- .gitignore | 104 +- .prettierignore | 10 +- .prettierrc.json | 12 +- README.en.md | 946 +++--- README.md | 946 +++--- docs/architecture.md | 176 +- eslint.config.js | 42 +- package-lock.json | 2886 ++++++++--------- package.json | 68 +- scripts/deploy-commands.js | 26 +- scripts/generate-changelog.js | 344 +- scripts/init-database.js | 14 +- src/commands/community/fun.js | 214 +- src/commands/community/poll.js | 124 +- src/commands/community/stats.js | 232 +- src/commands/fws/fws.js | 476 +-- src/commands/general/help.js | 50 +- src/commands/general/status.js | 306 +- src/commands/gitea/gitea.js | 148 +- src/commands/gitea/issue.js | 160 +- src/commands/gitea/pr.js | 190 +- src/commands/moderation/ban.js | 112 +- src/commands/moderation/clear.js | 98 +- src/commands/moderation/kick.js | 88 +- src/commands/moderation/mod.js | 110 +- src/commands/moderation/mute.js | 122 +- src/commands/moderation/notify.js | 210 +- src/commands/moderation/role.js | 182 +- src/commands/moderation/warn.js | 106 +- src/commands/tickets/ticket.js | 144 +- src/commands/voice/voice.js | 746 ++--- src/config/constants.js | 136 +- src/config/env.js | 206 +- src/core/client.js | 52 +- src/core/command-loader.js | 56 +- src/core/errors.js | 48 +- src/core/event-loader.js | 58 +- src/core/logger.js | 100 +- src/core/permissions.js | 66 +- src/database/index.js | 126 +- .../migrations/001-initial-schema.sql | 194 +- .../migrations/004-voice-triggers.sql | 28 +- .../repositories/bot-status-repository.js | 84 +- .../repositories/event-log-repository.js | 26 +- .../repositories/moderation-repository.js | 100 +- .../repositories/notification-repository.js | 68 +- src/database/repositories/poll-repository.js | 194 +- .../repositories/settings-repository.js | 66 +- .../repositories/ticket-repository.js | 142 +- src/database/repositories/voice-repository.js | 144 +- .../repositories/voice-trigger-repository.js | 104 +- src/events/client-error.js | 20 +- src/events/client-ready.js | 42 +- src/events/guild-member-add.js | 40 +- src/events/guild-member-remove.js | 26 +- src/events/interaction-create.js | 176 +- src/events/shard-disconnect.js | 22 +- src/events/voice-state-update.js | 64 +- src/index.js | 70 +- src/services/gitea/gitea-client.js | 138 +- src/services/gitea/gitea-embeds.js | 194 +- src/services/gitea/gitea-modals.js | 304 +- src/services/gitea/pending-actions.js | 64 +- src/services/members/member-service.js | 230 +- src/services/moderation/moderation-service.js | 264 +- .../notifications/gitea-notifications.js | 62 +- .../notifications/notification-service.js | 122 +- src/services/polls/poll-service.js | 438 +-- src/services/status/bot-status-service.js | 628 ++-- src/services/tickets/ticket-service.js | 590 ++-- src/services/voice/voice-service.js | 2002 ++++++------ src/ui/buttons.js | 198 +- src/ui/embeds.js | 110 +- src/utils/cooldown.js | 36 +- src/utils/retry.js | 38 +- src/webhooks/gitea-webhook.js | 138 +- src/webhooks/server.js | 98 +- tests/bot-status.test.js | 444 +-- tests/database.test.js | 64 +- tests/docs.test.js | 100 +- tests/modules.test.js | 216 +- tests/notifications.test.js | 176 +- tests/pending-actions.test.js | 66 +- tests/permissions.test.js | 80 +- tests/poll-service.test.js | 160 +- tests/repositories.test.js | 378 +-- tests/voice.test.js | 1060 +++--- 89 files changed, 10215 insertions(+), 10215 deletions(-) diff --git a/.editorconfig b/.editorconfig index 86a63dc..fc99473 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,9 +1,9 @@ -root = true - -[*] -charset = utf-8 -end_of_line = lf -indent_style = space -indent_size = 2 -insert_final_newline = true -trim_trailing_whitespace = true +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true diff --git a/.env.example b/.env.example index 24bf3e3..1af6ff3 100644 --- a/.env.example +++ b/.env.example @@ -1,82 +1,82 @@ -# ============================================================================= -# FWS-Bot — environment configuration example -# Copy this file to `.env` and fill in the values. Never commit `.env`. -# ============================================================================= - -# --- Runtime ----------------------------------------------------------------- -# development | production | test -NODE_ENV=development -# debug | info | warn | error -LOG_LEVEL=info -LOG_DIR=./logs -# Number of days functional/technical logs are kept (M11-T08) -LOG_RETENTION_DAYS=30 - -# --- Discord application (M2-T01) ------------------------------------------- -# Developer Portal > Bot > Token -DISCORD_TOKEN= -# Developer Portal > General Information > Application ID -DISCORD_CLIENT_ID= -# FWS server ID (slash commands are registered on this guild) -DISCORD_GUILD_ID= - -# --- FWS roles (M3-T01) — Discord role IDs ---------------------------------- -ROLE_OWNER_ID= -ROLE_DEV_ID= -ROLE_STAFF_ID= -# Role given to new members on join (M7-T03) -ROLE_MEMBER_ID= - -# --- Discord channels (M0-T04 / M9-T01) — channel IDs ----------------------- -CHANNEL_WELCOME_ID= -CHANNEL_RULES_ID= -CHANNEL_ANNOUNCEMENTS_ID= -CHANNEL_LOGS_ID= -CHANNEL_MOD_LOGS_ID= -CHANNEL_TICKETS_LOGS_ID= -CHANNEL_NOTIF_ISSUES_ID= -CHANNEL_NOTIF_PULL_REQUESTS_ID= -CHANNEL_NOTIF_COMMITS_ID= -CHANNEL_NOTIF_RELEASES_ID= -CHANNEL_NOTIF_ERRORS_ID= -# Category under which private ticket channels are created (M6) -CATEGORY_TICKETS_ID= - -# --- Salons vocaux temporaires (M14) ---------------------------------------- -# Salon vocal « rejoindre pour créer » : y entrer crée un salon temporaire -CHANNEL_VOICE_TRIGGER_ID= -# Catégorie d'accueil des salons vocaux créés (facultatif) -CATEGORY_VOICE_ID= -# Délai avant qu'un salon généré devenu vide soit supprimé, en ms (0 = immédiat) -VOICE_EMPTY_GRACE_MS=5000 - -# --- Statuts du bot (M15) ----------------------------------------------------- -# Rythme par défaut de la rotation, en secondes (modifiable à chaud par /status interval) -BOT_STATUS_INTERVAL_SECONDS=60 - -# --- Gitea (M5-T01) ---------------------------------------------------------- -GITEA_URL=https://gitea.nocode-var.tech -# Token with least privilege (read:repository, write:issue). Never log it. -GITEA_TOKEN= -GITEA_OWNER=FWS -GITEA_REPO=FWS-Arch -GITEA_TIMEOUT_MS=10000 -GITEA_MAX_RETRIES=2 - -# --- Gitea webhooks (M9-T02) ------------------------------------------------- -WEBHOOK_ENABLED=false -WEBHOOK_HOST=0.0.0.0 -WEBHOOK_PORT=3000 -WEBHOOK_PATH=/webhooks/gitea -# Shared secret configured in Gitea > Settings > Webhooks -GITEA_WEBHOOK_SECRET= - -# --- SQLite (M1-T05) --------------------------------------------------------- -DATABASE_PATH=./data/fws-bot.sqlite -BACKUP_DIR=./data/backups - -# --- FWS links (M0-T06 / M4-T04) --------------------------------------------- -FWS_WEBSITE_URL= -FWS_DOCS_URL= -FWS_DISCORD_INVITE_URL= -FWS_ARCH_REPO_URL= +# ============================================================================= +# FWS-Bot — environment configuration example +# Copy this file to `.env` and fill in the values. Never commit `.env`. +# ============================================================================= + +# --- Runtime ----------------------------------------------------------------- +# development | production | test +NODE_ENV=development +# debug | info | warn | error +LOG_LEVEL=info +LOG_DIR=./logs +# Number of days functional/technical logs are kept (M11-T08) +LOG_RETENTION_DAYS=30 + +# --- Discord application (M2-T01) ------------------------------------------- +# Developer Portal > Bot > Token +DISCORD_TOKEN= +# Developer Portal > General Information > Application ID +DISCORD_CLIENT_ID= +# FWS server ID (slash commands are registered on this guild) +DISCORD_GUILD_ID= + +# --- FWS roles (M3-T01) — Discord role IDs ---------------------------------- +ROLE_OWNER_ID= +ROLE_DEV_ID= +ROLE_STAFF_ID= +# Role given to new members on join (M7-T03) +ROLE_MEMBER_ID= + +# --- Discord channels (M0-T04 / M9-T01) — channel IDs ----------------------- +CHANNEL_WELCOME_ID= +CHANNEL_RULES_ID= +CHANNEL_ANNOUNCEMENTS_ID= +CHANNEL_LOGS_ID= +CHANNEL_MOD_LOGS_ID= +CHANNEL_TICKETS_LOGS_ID= +CHANNEL_NOTIF_ISSUES_ID= +CHANNEL_NOTIF_PULL_REQUESTS_ID= +CHANNEL_NOTIF_COMMITS_ID= +CHANNEL_NOTIF_RELEASES_ID= +CHANNEL_NOTIF_ERRORS_ID= +# Category under which private ticket channels are created (M6) +CATEGORY_TICKETS_ID= + +# --- Salons vocaux temporaires (M14) ---------------------------------------- +# Salon vocal « rejoindre pour créer » : y entrer crée un salon temporaire +CHANNEL_VOICE_TRIGGER_ID= +# Catégorie d'accueil des salons vocaux créés (facultatif) +CATEGORY_VOICE_ID= +# Délai avant qu'un salon généré devenu vide soit supprimé, en ms (0 = immédiat) +VOICE_EMPTY_GRACE_MS=5000 + +# --- Statuts du bot (M15) ----------------------------------------------------- +# Rythme par défaut de la rotation, en secondes (modifiable à chaud par /status interval) +BOT_STATUS_INTERVAL_SECONDS=60 + +# --- Gitea (M5-T01) ---------------------------------------------------------- +GITEA_URL=https://gitea.nocode-var.tech +# Token with least privilege (read:repository, write:issue). Never log it. +GITEA_TOKEN= +GITEA_OWNER=FWS +GITEA_REPO=FWS-Arch +GITEA_TIMEOUT_MS=10000 +GITEA_MAX_RETRIES=2 + +# --- Gitea webhooks (M9-T02) ------------------------------------------------- +WEBHOOK_ENABLED=false +WEBHOOK_HOST=0.0.0.0 +WEBHOOK_PORT=3000 +WEBHOOK_PATH=/webhooks/gitea +# Shared secret configured in Gitea > Settings > Webhooks +GITEA_WEBHOOK_SECRET= + +# --- SQLite (M1-T05) --------------------------------------------------------- +DATABASE_PATH=./data/fws-bot.sqlite +BACKUP_DIR=./data/backups + +# --- FWS links (M0-T06 / M4-T04) --------------------------------------------- +FWS_WEBSITE_URL= +FWS_DOCS_URL= +FWS_DISCORD_INVITE_URL= +FWS_ARCH_REPO_URL= diff --git a/.gitignore b/.gitignore index b4a70f0..cafe903 100644 --- a/.gitignore +++ b/.gitignore @@ -1,52 +1,52 @@ -# Dependencies -node_modules/ - -# Environment and secrets -.env -.env.* -!.env.example - -# Development assistant data (never committed) -.freebuff/ -.cursor/ - -# SQLite databases and backups -data/* -!data/.gitkeep -*.sqlite -*.sqlite3 -*.db -*.db-journal -*-wal -*-shm - -# Logs -logs/* -!logs/.gitkeep -*.log -npm-debug.log* - -# Build and coverage -dist/ -build/ -coverage/ -.cache/ - -# Compiled artefacts of the other toolchains used across FWS projects -target/ -__pycache__/ -*.pyc -*.pyo -*.o -*.so -*.exe -*.dll - -# Editors and OS -# `.vscode/extensions.json` stays tracked on purpose: it holds the recommended extensions -# shared by the project. Everything else in the folder is personal. -.vscode/* -!.vscode/extensions.json -.idea/ -.DS_Store -Thumbs.db +# Dependencies +node_modules/ + +# Environment and secrets +.env +.env.* +!.env.example + +# Development assistant data (never committed) +.freebuff/ +.cursor/ + +# SQLite databases and backups +data/* +!data/.gitkeep +*.sqlite +*.sqlite3 +*.db +*.db-journal +*-wal +*-shm + +# Logs +logs/* +!logs/.gitkeep +*.log +npm-debug.log* + +# Build and coverage +dist/ +build/ +coverage/ +.cache/ + +# Compiled artefacts of the other toolchains used across FWS projects +target/ +__pycache__/ +*.pyc +*.pyo +*.o +*.so +*.exe +*.dll + +# Editors and OS +# `.vscode/extensions.json` stays tracked on purpose: it holds the recommended extensions +# shared by the project. Everything else in the folder is personal. +.vscode/* +!.vscode/extensions.json +.idea/ +.DS_Store +Thumbs.db diff --git a/.prettierignore b/.prettierignore index 40c1490..0824eca 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,5 +1,5 @@ -node_modules/ -data/ -logs/ -package-lock.json -README.md +node_modules/ +data/ +logs/ +package-lock.json +README.md diff --git a/.prettierrc.json b/.prettierrc.json index 0f8f410..d4b7487 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,6 +1,6 @@ -{ - "singleQuote": true, - "trailingComma": "all", - "printWidth": 110, - "semi": true -} +{ + "singleQuote": true, + "trailingComma": "all", + "printWidth": 110, + "semi": true +} diff --git a/README.en.md b/README.en.md index 06ceed7..ea7fd09 100644 --- a/README.en.md +++ b/README.en.md @@ -1,473 +1,473 @@ -# FWS-Bot - -> Discord bot for the open source **FWS** organisation — community support, tickets, moderation, Gitea integration and statistics for **FWS Arch** (an Arch Linux fork with a friendly layer on top). - -🌍 [Version française](README.md) · **English** - -Status: **working**. The 19 commands are implemented (support, private tickets, moderation, Gitea, polls, statistics, bot statuses, voice channel manager), together with member welcome and the Gitea webhook delivery. - -This project follows the [FWS organisation conventions](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md): English commit messages in the Conventional Commits format, `type/description` branches, reviewed pull requests merged with squash, SemVer and a `CHANGELOG.md` generated from the commits. - ---- - -## 1. Tech stack - -Deliberate choices: **a single runtime dependency** (discord.js), no native module to compile, and the test runner built into Node. - -| Tech | Version | Purpose | -| ------------------ | --------------------- | ------------------------------------------------------------------------- | -| **Node.js** | ≥ 22.13.0 (ESM) | Runtime. Required for `node:sqlite`, `process.loadEnvFile`, `--watch` | -| **discord.js** | ^14.21.0 | Discord API: slash commands, embeds, buttons, intents | -| **`node:sqlite`** | native module | SQLite database (WAL, foreign keys) — no `better-sqlite3`, no compilation | -| **native `fetch`** | — | Gitea REST client (with `AbortSignal.timeout`) | -| **`node:http`** | — | Gitea webhook server (no Express) | -| **`node:crypto`** | — | HMAC-SHA256 signature of the webhooks | -| **`node:test`** | — | Built-in unit tests (`node --test`) | -| **ESLint** | ^9.30.0 (flat config) | Linting | -| **Prettier** | ^3.6.2 | Formatting | - -## 2. Requirements - -- Node.js ≥ 22.13 (`node -v` to check) and npm -- A Discord application (free) with a bot token -- (Optional) a Gitea instance for issues/pull requests and webhooks - -## 3. Quick start with a test token - -### 3.1 Create the Discord application - -1. Open the [Discord Developer Portal](https://discord.com/developers/applications) → **New Application**. -2. **Bot** tab → **Reset Token** → copy the token: that is your `DISCORD_TOKEN` (never share it, never commit it). -3. Still in **Bot** → **Privileged Gateway Intents** → enable **Server Members Intent** (needed to welcome new members; `Message Content` is not required). -4. **General Information** tab → copy the **Application ID**: that is your `DISCORD_CLIENT_ID`. - -### 3.2 Invite the bot to a test server - -Replace `CLIENT_ID` with your Application ID: - -```text -https://discord.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot+applications.commands&permissions=1099812662294 -``` - -That URL pre-checks every permission the commands use: View Channels, Send Messages, Manage Messages, Embed Links, Read Message History, Kick Members, Ban Members, Manage Roles, Moderate Members (timeout), plus the voice channel ones: Manage Channels, Connect, Speak, Mute Members, Deafen Members, Move Members. You can also use **OAuth2 → URL Generator** with the `bot` + `applications.commands` scopes. - -Create (or reuse) a test server you own: that is what grants the bot the **Owner** level. - -### 3.3 Collect the Discord IDs - -On Discord: **Settings → Advanced → Developer Mode** on, then right-click a server / channel / role → **Copy ID**. - -| Variable | Where to find it | -| ----------------------------------------------------------------- | ------------------------------------------- | -| `DISCORD_GUILD_ID` | Right-click the test server | -| `ROLE_OWNER_ID`, `ROLE_DEV_ID`, `ROLE_STAFF_ID`, `ROLE_MEMBER_ID` | Server settings → Roles (create them first) | -| `CHANNEL_WELCOME_ID`, `CHANNEL_LOGS_ID`, etc. | Right-click each channel | - -> Without configured roles everyone counts as **User** (except the server owner, who is Owner). - -### 3.4 Run the bot - -```bash -# 1. Dependencies -npm install - -# 2. Configuration: copy .env.example to .env and fill it in -# Minimum required: DISCORD_TOKEN, DISCORD_CLIENT_ID, DISCORD_GUILD_ID -cp .env.example .env - -# 3. Create the SQLite database and apply the migrations -npm run db:init - -# 4. Register the slash commands on the server (instant, per guild) -npm run deploy:commands - -# 5. Start with automatic reload -npm run dev -``` - -The logs should show `Connected as `. Type `/help` on the server: you should see the commands your role can use. - -Without a `.env` the bot refuses to start (`assertRequiredEnv` checks the token, client ID and guild ID). - -## 4. Configuration — every variable (`.env`) - -Full template: [`.env.example`](.env.example). Default values in brackets. - -### Runtime - -| Variable | Default | Description | -| ----------------------------- | ------------- | ------------------------------------------------------------------------------- | -| `NODE_ENV` | `development` | `development` \| `production` \| `test` | -| `LOG_LEVEL` | `info` | `debug` \| `info` \| `warn` \| `error` | -| `LOG_DIR` | `./logs` | Directory of the daily JSON logs | -| `LOG_RETENTION_DAYS` | `30` | Retention window (purges `event_logs`) | -| `VOICE_EMPTY_GRACE_MS` | `5000` | Delay before a generated voice channel left empty is deleted (`0` = immediate) | -| `BOT_STATUS_INTERVAL_SECONDS` | `60` | Default rotation speed of the bot statuses (changeable with `/status interval`) | - -### Discord application - -| Variable | Description | -| ------------------- | ------------------------------------------------------------ | -| `DISCORD_TOKEN` | **Required.** Bot token (Developer Portal → Bot) | -| `DISCORD_CLIENT_ID` | **Required.** Application ID | -| `DISCORD_GUILD_ID` | **Required.** Server where the slash commands are registered | - -### FWS roles (Discord role IDs) - -| Variable | Matching level | -| ---------------- | ------------------------------------------ | -| `ROLE_OWNER_ID` | Owner — full access | -| `ROLE_DEV_ID` | Dev — FWS Arch configuration, Gitea writes | -| `ROLE_STAFF_ID` | Staff — moderation, support, tickets | -| `ROLE_MEMBER_ID` | Initial role given to new members | - -### Discord channels (IDs) - -| Variable | Usage | -| -------------------------------- | --------------------------------------------------------------------------- | -| `CHANNEL_WELCOME_ID` | Welcome messages | -| `CHANNEL_RULES_ID` | Rules (link sent to newcomers) | -| `CHANNEL_ANNOUNCEMENTS_ID` | FWS announcements | -| `CHANNEL_LOGS_ID` | Functional logs | -| `CHANNEL_MOD_LOGS_ID` | Moderation logs | -| `CHANNEL_TICKETS_LOGS_ID` | Ticket opening/closing journal | -| `CHANNEL_NOTIF_ISSUES_ID` | Issue notifications | -| `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Pull request notifications | -| `CHANNEL_NOTIF_COMMITS_ID` | Commit notifications | -| `CHANNEL_NOTIF_RELEASES_ID` | Release notifications | -| `CHANNEL_NOTIF_ERRORS_ID` | Errors and incidents | -| `CATEGORY_TICKETS_ID` | Category where the private ticket channels are created | -| `CHANNEL_VOICE_TRIGGER_ID` | Trigger voice channel (fallback: `/voice setup` manages a list of triggers) | -| `CATEGORY_VOICE_ID` | Home category of the generated voice channels (optional) | - -### Gitea - -| Variable | Default | Description | -| ------------------- | ------- | ---------------------------------------------------------------------- | -| `GITEA_URL` | — | Instance URL (without a trailing `/`) | -| `GITEA_TOKEN` | — | Least privilege token (`read:repository`, `write:issue`). Never logged | -| `GITEA_OWNER` | — | Repository owner (e.g. `FWS`) | -| `GITEA_REPO` | — | Target repository (e.g. `FWS-Arch`) | -| `GITEA_TIMEOUT_MS` | `10000` | Request timeout | -| `GITEA_MAX_RETRIES` | `2` | Retries on transient errors (429, 5xx, timeout) | - -### Gitea webhooks - -| Variable | Default | Description | -| ---------------------- | ----------------- | ---------------------------------------------------- | -| `WEBHOOK_ENABLED` | `false` | Starts the receiving HTTP server | -| `WEBHOOK_HOST` | `0.0.0.0` | Listening interface | -| `WEBHOOK_PORT` | `3000` | Listening port | -| `WEBHOOK_PATH` | `/webhooks/gitea` | Path to configure in Gitea | -| `GITEA_WEBHOOK_SECRET` | — | Shared secret (HMAC-SHA256), set in Gitea → Webhooks | - -### SQLite and links - -| Variable | Default | Description | -| -------------------------------------------------------------------------------- | ----------------------- | -------------------------------------------------------------------------------- | -| `DATABASE_PATH` | `./data/fws-bot.sqlite` | Database file (excluded from git) | -| `BACKUP_DIR` | `./data/backups` | Backup directory | -| `FWS_WEBSITE_URL`, `FWS_DOCS_URL`, `FWS_DISCORD_INVITE_URL`, `FWS_ARCH_REPO_URL` | — | Official links shown by `/fws info` and `/fws links` (empty buttons are omitted) | - -## 5. Slash commands - -19 commands are registered. Every command carries an **FWS access level** checked server-side before running, and the moderation commands additionally check the matching **Discord permission** (`DefaultMemberPermissions`). - -### Access levels - -Resolved from the roles configured in `.env` (highest to lowest): - -| Level | Who | -| ----------- | ------------------------------- | -| `OWNER` (3) | Owner role, or the server owner | -| `DEV` (2) | Dev role | -| `STAFF` (1) | Staff role | -| `USER` (0) | Every member | - -### General and FWS - -| Command | Options | Access | State | Description | -| --------------------------------------- | --------------------------------- | --------------------------- | ----- | -------------------------------------------------------------------------------------- | -| `/help` | — | User | ✅ | Lists the commands your role can use (ephemeral reply) | -| `/fws info` | — | User | ✅ | Presents FWS and FWS Arch (text overridable through `guild_settings`) + official links | -| `/fws links` | — | User | ✅ | Resources: website, docs, repository, Gitea, Discord | -| `/fws version` | — | User | ✅ | Latest Gitea release (tag, date, author) + button to the notes | -| `/fws status` | — | User | ✅ | Service status: Gitea API, webhooks, SQLite, Discord latency, uptime | -| `/fws changelog` | `version` (optional) | User | ✅ | Release notes (latest by default, clear message when the tag does not exist) | -| `/status add` | `text` (128 chars), `type`, `url` | **Staff** + _Manage Server_ | ✅ | Adds a status to the rotation; the first one is shown right away | -| `/status list` | — | **Staff** + _Manage Server_ | ✅ | Stored statuses: number, type, state, rotation speed | -| `/status remove` · `enable` · `disable` | `id` | **Staff** + _Manage Server_ | ✅ | Removes a status, puts it back in rotation or pauses it | -| `/status interval` | `seconds` (5–86 400) | **Staff** + _Manage Server_ | ✅ | Rotation speed, applied without a restart | -| `/status clear` | — | **Staff** + _Manage Server_ | ✅ | Empties the list and returns to the default line | - -### Gitea — issues and pull requests - -| Command | Options | Access | State | Description | -| ----------------- | ------------------------------------------- | ------------------- | ----- | ------------------------------------------------------ | -| `/issue create` | — (modal: title + description) | User (configurable) | ✅ | Creates a Gitea issue and returns its link | -| `/issue view` | `number` | User | ✅ | Title, author, state, labels, link of an issue | -| `/issue list` | — | User | ✅ | Open issues (last 15) | -| `/pr create` | `head`, `base` + modal (title, description) | **Dev** | ✅ | Creates a Gitea pull request | -| `/pr view` | `number` | User | ✅ | Title, author, state, branches, link of a pull request | -| `/pr list` | — | User | ✅ | Open pull requests (last 15) | -| `/gitea activity` | — | User | ✅ | Latest commits + open issues and pull requests | -| `/gitea release` | — | User | ✅ | FWS Arch releases (last 5) | - -> The Gitea client (`src/services/gitea/gitea-client.js`): REST with token, timeout, exponential retry on transient errors. The forms (`/issue create`, `/pr create`) go through a **modal**; the branch options are kept in memory for a few minutes (`pending-actions.js`). Any failure (missing token, 404, 5xx) becomes an explicit ephemeral message, never a raw error. - -### Support tickets - -Tickets are private channels created under `CATEGORY_TICKETS_ID`. One open ticket per member and per category (SQL constraint). - -| Command | Options | Access | State | Description | -| ---------------- | ------------------------------ | -------------------------------- | ----- | ------------------------------------------------------------------------------------ | -| `/ticket create` | `category` (required) | User (depending on the category) | ✅ | Creates a private channel under `CATEGORY_TICKETS_ID` | -| `/ticket close` | `reason` (optional, 500 chars) | Author, Staff | ✅ | Closes, logs and then deletes the channel (10 s) — also through the **Close** button | -| `/ticket claim` | — | **Staff** | ✅ | Takes the ticket over (**Claim** button) | -| `/ticket add` | `user` | **Staff** | ✅ | Adds a participant to the private channel | - -Available categories and who can use them: - -| Category | Visible to | -| ------------------------- | ----------------- | -| Aide et support | Staff, Owner | -| Bug | Staff, Dev, Owner | -| Question de développement | Dev, Owner | -| Signalement | Staff, Owner | -| Demande interne | Owner | - -### Temporary voice channels - -A server can declare **as many trigger channels as it needs** — one per theme (`Dev`, `SIO`, …) — each with its own home category (`/voice setup`): joining a trigger creates a private voice channel **at the bottom of that trigger's category**, moves the member in and hands over ownership. The channel is then managed from the **control panel** posted in its chat (_Rename_, _Limit_, _Lock_, _Claim_, _Delete_ buttons and the _Permit_, _Reject_, _Transfer_ menus) or with `/voice`. The number of simultaneous channels is **unlimited**, and a member keeps one channel **per trigger**: joining the same trigger again simply moves them back into the channel they already own. - -As soon as **nobody** is left in a generated channel, it is deleted: the delay (5 s by default) lets it survive a quick hop to another channel — tunable with `VOICE_EMPTY_GRACE_MS`, `0` deletes it immediately. A periodic sweep (at startup, then every minute) catches the cases where a Discord event was missed or a deletion was refused, so a generated channel cannot stay empty: either it is deleted, or the attempt is retried. - -| Command | Options | Access | Description | -| ---------------------------------------- | ------------------------------------------------------------ | --------------------- | ------------------------------------------------------------------------------------------- | -| `/voice setup` | `trigger`, `label`, `category`, `template`, `limit`, `panel` | **Staff** | Adds (or updates) a trigger channel; without `category`, the trigger's own category is used | -| `/voice config` · `/voice triggers list` | — | User · **Staff** | Declared triggers: category, template, limit, state and live channels | -| `/voice triggers disable` · `enable` | `trigger` | **Staff** | Pauses a trigger (its configuration is kept, joining it creates nothing) · resumes it | -| `/voice triggers remove` | `trigger` | **Staff** | Deletes a trigger declared from Discord | -| `/voice panel` | `trigger` (default: all) | **Staff** | Re-posts the explanation panel in the trigger channels | -| `/voice name` | `name` (100 chars) | Owner | Renames the channel | -| `/voice limit` | `limit` (0–99, 0 = unlimited) | Owner | Number of spots | -| `/voice lock` · `/voice unlock` | — | Owner | Refuses · allows everyone to join | -| `/voice permit` | `user` | Owner | Allows a member to join the channel | -| `/voice reject` | `user` | Owner | Denies access (and kicks them out if they are inside) | -| `/voice kick` | `user` | Owner | Kicks a member out of the channel | -| `/voice transfer` | `user` | Owner | Transfers ownership (the new owner must already be inside) | -| `/voice claim` | — | Member of the channel | Claims a channel whose owner left | -| `/voice delete` | `channel` (staff) | Owner, Staff | Deletes the channel immediately | -| `/voice info` | `channel` (staff) | User | Owner, state, limit, members, age | - -> Name template: `{user}` is replaced by the member's display name (default `🔊 Salon de {user}`). Staff can always act on any temporary channel. The owner receives `Manage Channel` + `Move Members` on their own channel only. -> -> `CHANNEL_VOICE_TRIGGER_ID` / `CATEGORY_VOICE_ID` remain a **fallback**: a server whose `.env` declares a trigger works without `/voice setup`, but a trigger coming from the environment can only be paused (`/voice triggers disable`), not deleted from Discord. Changing a trigger's category does not move the channels already created. - -### Moderation - -Every command checks the FWS level **and** the matching Discord permission. The bot refuses to act on a member whose highest role is equal or higher than the caller's (`canActOn`), and never acts on the server owner. - -| Command | Options | Discord permission | State | Description | -| ---------------- | ----------------------------------------- | ------------------ | ----- | ------------------------------------------------------------------ | -| `/warn` | `user`, `reason` (required) | Moderate Members | ✅ | Warns, notifies the member by DM and records the action | -| `/mute` | `user`, `minutes` (1–40320), `reason` | Moderate Members | ✅ | Temporary timeout (28 days max) + DM notification | -| `/kick` | `user`, `reason` | Kick Members | ✅ | Kicks from the server and logs the action | -| `/ban` | `user`, `reason`, `delete_days` (0–7) | Ban Members | ✅ | Bans (even if the member already left), optional message purge | -| `/clear` | `amount` (1–100) | Manage Messages | ✅ | Deletes the last N messages (those older than 14 days are skipped) | -| `/mod logs` | `user` (filter) | Moderate Members | ✅ | History read from `moderation_actions` (last 15, ephemeral) | -| `/role set` | `user`, `role`, `action` (`add`/`remove`) | Manage Roles | ✅ | Adds or removes a role (both hierarchies checked) | -| `/notify set` | `type`, `channel` | Manage Server | ✅ | Notification channel specific to this server (SQLite) | -| `/notify remove` | `type` | Manage Server | ✅ | Returns to the default channel (environment variables) | -| `/notify list` | — | Manage Server | ✅ | Current configuration of every type | - -> Every successful action is recorded in `moderation_actions` **and** posted in `CHANNEL_MOD_LOGS_ID` (member, moderator, reason, duration). - -### Community and statistics - -| Command | Options | Access | State | Description | -| ---------------- | --------------------------------------------------------------------- | --------- | ----- | ---------------------------------------------------------------- | -| `/poll create` | `question`, `choices` (separated by « ; », 2–10), `minutes` (1–10080) | **Staff** | ✅ | Poll voted with buttons, live results | -| `/poll close` | `id` | **Staff** | ✅ | Closes it, shows the winning choice and freezes the message | -| `/stats discord` | — | User | ✅ | Members, channels, roles, boosts, server age, latency | -| `/stats gitea` | — | User | ✅ | Recent commits, open issues and pull requests, latest release | -| `/stats fws` | — | User | ✅ | Local indicators (tickets, polls, moderation) + FWS Arch version | -| `/fun coinflip` | — | User | ✅ | Heads or tails | -| `/fun dice` | `sides` (2–1000, 6 by default) | User | ✅ | Dice roll | -| `/fun 8ball` | `question` | User | ✅ | Magic eight ball (12 answers) | -| `/fun choose` | `options` (separated by « ; », 2–10) | User | ✅ | Random pick | - -Legend: ✅ working · expected errors are returned as ephemeral messages (`UserFacingError`), everything else is logged and replaced by a generic message. - -## 6. Automations - -- **Welcome** (`src/events/guild-member-add.js`): assigns `ROLE_MEMBER_ID` (skipped when that role sits above the bot's), posts a welcome embed in `CHANNEL_WELCOME_ID` pointing at `CHANNEL_RULES_ID`, and sends a DM with the official links (silent when DMs are closed). -- **Departures** (`src/events/guild-member-remove.js`): embed in `CHANNEL_LOGS_ID` (falls back to `CHANNEL_MOD_LOGS_ID`) with the member count, time on the server and account age. -- **Notifications** (`src/services/notifications/notification-service.js`): routing per type — per-guild override in SQLite (`notification_channels`, configured with `/notify set`), otherwise the matching environment variable. A type without a channel is simply ignored (`debug` log). -- **Gitea webhooks**: native HTTP server (`WEBHOOK_ENABLED=true`). Verifies the **HMAC-SHA256** signature (`x-gitea-signature`) in constant time, rejects bodies over 1 MB and invalid JSON, deduplicates redeliveries through `webhook_deliveries`, then posts the embeds through the notification service: `issues` → issues, `pull_request` → PR, `push` → commits, `create`/`delete` → refs, `release` → releases. -- **Polls** (`src/services/polls/poll-service.js`): one vote per member and per poll (changeable, one click moves the vote), the message is refreshed on every vote, and a scheduler closes expired polls automatically (checked every 30 s) even after a restart. -- **Bot statuses** (`src/services/status/bot-status-service.js`): the presence shown under the bot name is a **list stored in the database** (`bot_statuses`), editable live with `/status` (add, remove, pause, speed). The rotation starts over from the first enabled status each cycle and the delay is re-read on every turn, so `/status interval` applies without restarting the bot. Empty list → default line “les commandes avec /help” instead of a hard-coded status. -- **Voice channels** (`src/events/voice-state-update.js`): joining **one of the trigger channels** creates a temporary channel at the bottom of that trigger's category and moves the member in (or moves them back into the one they already own for that trigger); as soon as the last member leaves, the channel is deleted after a short grace period (`VOICE_EMPTY_GRACE_MS`, 5 s by default) that leaves time to switch channels without losing theirs. The deletion only forgets the database row once the channel is really gone: an API error keeps it registered so the attempt can be retried. `sweepVoiceChannels()` forgets vanished channels and deletes the empty ones — at startup, then every minute through `startVoiceJanitor()`, which guarantees a generated channel never survives empty after a missed event or a failed API call. - -## 7. Architecture - -Full details: [`docs/architecture.md`](docs/architecture.md). - -```text -src/ -├── index.js # Entry point: env, DB, client, loaders, webhooks, clean shutdown -├── config/ # env.js (.env reading/validation) · constants.js (colors, levels, categories) -├── core/ # client.js · command-loader.js · event-loader.js -│ # permissions.js (levels + hierarchy) · logger.js · errors.js -├── commands// # fws, gitea, tickets, moderation, community, general -├── events/ # interaction-create (commands, buttons, modals), ready, member add/remove, -│ # voice state (voice channels), errors, shard -├── services/ -│ ├── gitea/ # gitea-client.js (REST + retry) · gitea-embeds.js · gitea-modals.js · pending-actions.js -│ ├── members/ # member-service.js (welcome, initial role, departures) -│ ├── moderation/ # moderation-service.js (hierarchy, sanctions, journal) -│ ├── notifications/ # notification-service.js (routing) · gitea-notifications.js (webhook mapping) -│ ├── polls/ # poll-service.js (creation, votes, closing, scheduler) -│ ├── status/ # bot-status-service.js (bot statuses, validation, rotation) -│ ├── tickets/ # ticket-service.js (private channels, lifecycle) -│ └── voice/ # voice-service.js (several triggers, temporary channels, panel) -├── database/ # index.js (connection + SQL migrations) · migrations/ · repositories/ -├── webhooks/ # server.js (node:http) · gitea-webhook.js (signature + dispatch) -├── ui/ # embeds.js (visual identity) · buttons.js (links, tickets, polls) -└── utils/ # retry.js (exponential backoff) · cooldown.js -``` - -Automatic loading: any command under `src/commands/**` and any event under `src/events/*` is picked up at startup. - -**Command contract** (`access` checked in `interaction-create.js`, a `UserFacingError` is shown as-is, any other error is logged and replaced by a generic message): - -```js -export const access = ACCESS_LEVELS.STAFF; // minimum level -export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optional, per subcommand -export const data = new SlashCommandBuilder(); /* ... */ -export async function execute(interaction) {} -``` - -**Intents used**: `Guilds`, `GuildMembers` _(privileged — enable it in the portal)_, `GuildModeration`, `GuildMessages`, `GuildVoiceStates`. `MessageContent` is deliberately not requested. - -### Message tone and vocabulary - -Every text shown in Discord follows the same rules, listed at the top of `src/ui/embeds.js` (single source of truth): - -- **Informal “tu”**, short sentences, active voice; never a reproach, irony or shouting capitals. -- The **title** states the outcome, the **description** says what to do next; one emoji per title, never decorative inside the body. -- **No gendered agreement** on a person: “tu es propriétaire”, “cette personne”, “l'équipe”, “ce membre” — no “il / elle”, no “cher / chère”, no inclusive dots. -- An **error** explains the cause, recalls the rule and offers the way out; a success thanks and gives the next step (`/ban` points at `/mod logs`, `/ticket create` recalls that the owner can close). -- Shared titles: `✅ C'est fait`, `❌ Oups`, `⚠️ Attention`, `💡 Bon à savoir` (`TONE` in `src/ui/embeds.js`). Lists always prefixed with `•` (`bullets()`), closing advice line added by `withHint()`. -- Same vocabulary everywhere: **équipe** (staff), **membre**, **salon**, **ticket**, **motif** (never “raison” as a label), voice **déclencheur**. - -## 8. Database (SQLite) - -- Engine: `node:sqlite` (`DatabaseSync`), **WAL** mode, foreign keys enabled. -- Migrations: numbered SQL files in `src/database/migrations/`, applied in a transaction and tracked in `schema_migrations` (`npm run db:init`). -- Tables: `guild_settings` (per-guild settings), `notification_channels`, `ticket_categories`, `tickets` (one open ticket per author and category), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (voice triggers and their category), `voice_channels` (owner, lock, limit), `bot_statuses` (bot statuses, global — unique text), `event_logs`, `webhook_deliveries`. -- Data access: one repository per domain (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-repository.js`) — SQL queries never leave that layer. -- Migrations `002-ticket-and-poll-details.sql` (claim tracking `claimed_at` and closing `close_reason`), `003-voice-channels.sql` (temporary voice channels), `004-voice-triggers.sql` (several voice triggers per server) and `005-bot-statuses.sql` (bot statuses edited from a command) complete the initial schema. -- The database holds real data: it is **excluded from git** (`.gitignore`) and must be backed up (`BACKUP_DIR`). - -## 9. Logs - -- **JSON** format, one line per entry, one file per day: `logs/YYYY-MM-DD.log` + console. -- Levels filtered by `LOG_LEVEL`; errors and warnings go to stderr. -- **Secret masking**: the Discord token, Gitea token and webhook secret are replaced with `***` in every logged line. -- Functional retention: `LOG_RETENTION_DAYS` (purges `event_logs`). - -## 10. npm scripts - -| Script | Purpose | -| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `npm start` | Starts the bot (`node src/index.js`) | -| `npm run dev` | Starts with automatic reload (`node --watch`) | -| `npm run deploy:commands` | Registers the slash commands on `DISCORD_GUILD_ID` (run it again after adding or changing a command) | -| `npm run db:init` | Creates the SQLite database and applies the migrations | -| `npm run lint` / `npm run lint:fix` | ESLint (check / fix) | -| `npm run format` / `npm run format:check` | Prettier (format / check) | -| `npm run changelog` | Regenerates `CHANGELOG.md` from the Conventional Commits (see §12) | -| `npm run changelog:check` | Fails with exit code 1 when `CHANGELOG.md` is out of date | -| `npm test` | `node:test` unit tests: `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs` | - -When something goes wrong: run `npm run deploy:commands` after any command change, check that the **Server Members** intent is enabled, and that the bot has the permissions listed in 3.2 on its target channels. - -## 11. Security - -- Permissions are checked **server-side** (FWS level + Discord permissions + role hierarchy): the client is never trusted. -- No action is possible on a role or member positioned above the caller. -- Secrets are never committed (`.env` is ignored) nor logged in plain text (automatic masking). -- Gitea webhooks: mandatory HMAC-SHA256 signature, constant-time comparison, 1 MB body limit, duplicate protection on the delivery ID. -- Least privilege tokens; rate limits respected (timeout + controlled retry on transient errors only). -- User input is validated (`setMinValue`/`setMaxValue`/`setMaxLength` on every option). - -## 12. Versioning and releases - -- **SemVer** (`MAJOR.MINOR.PATCH`): `MAJOR` = breaking change, `MINOR` = backwards-compatible feature, `PATCH` = fix. Current version: see `version` in [`package.json`](package.json) (before `1.0.0` anything may change — a breaking change only bumps `MINOR`, as SemVer §4 states). -- **`CHANGELOG.md` is generated** from the Conventional Commits: `npm run changelog` (`feat:` feeds _Features_, `fix:` feeds _Bug Fixes_, the other types go to _Other changes_). The script also prints the **suggested next version**; `npm run changelog:check` fails when the file is out of date. -- Tags are picked up automatically: every `vX.Y.Z` tag found in the history opens its own section in the changelog, newer commits stay under `[Unreleased]`. -- Generating it is part of the definition of done: the file is never edited by hand. - -## 13. Contributing - -The rules shared by every FWS repository live in the [organisation `.profile`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md). Summary as applied here: - -### Commits - -- Messages in **English**, **Conventional Commits** format: `(): `. -- Allowed types: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`. -- Short imperative title; a **body** is added only to explain the _why_ (context, decision, trade-off). - -### Branches and pull requests - -1. Create a `type/description` branch **from `main`** (e.g. `feat/ticket-service`, `fix/voice-cleanup`). -2. Commit following the conventions above. -3. Open a **pull request** with a clear title and description, referencing the issue (`Fixes #123`). -4. **At least one reviewer** approves; the tests must pass. -5. Merge with **squash**: 1 PR = 1 clean commit on `main`. - -### Work organisation - -- Project **Kanban** board: _Backlog / To do_, _In progress_, _In review_, _Done_. One card = one unit of work = one branch + one pull request; a card only moves to _Done_ once its pull request is merged. -- Every bug or request goes through an **issue** (clear title + precise description) with a recommended label: `bug`, `enhancement`, `question`, `good first issue`, `help wanted`. Templates are provided in [`.gitea/ISSUE_TEMPLATE/`](.gitea/ISSUE_TEMPLATE) and [`.gitea/PULL_REQUEST_TEMPLATE.md`](.gitea/PULL_REQUEST_TEMPLATE.md). -- A bug report includes the **reproduction steps**, the **expected** vs **observed** behaviour, the **environment** and useful **logs**. - -### Code and documentation - -- Files in **kebab-case**, identifiers **in English**, comments **in English** explaining the _why_ (the non-obvious: trade-offs, edge cases, references). -- Check the stack and the dependencies already present before adding a new one (a single runtime dependency here: `discord.js`). -- Before proposing: `npm run lint`, `npm run format:check`, `npm test` and `npm run changelog` must pass. -- **Bilingual** documentation: [`README.md`](README.md) (FR) and [`README.en.md`](README.en.md) (EN) stay in sync; a test enforces it. -- Instructions for AI agents: [`AGENTS.md`](AGENTS.md), updated together with the conventions. - -## 14. Production checklist - -- [ ] Rename the repository to `fws-discordbot` on Gitea (the organisation `fws-*` convention) -- [ ] Create the Kanban board (_Backlog / To do_, _In progress_, _In review_, _Done_) -- [ ] Fill in the bot statuses (`/status add`, `/status interval`) — the rotation is stored in the database -- [ ] Register the slash commands on the FWS server (`npm run deploy:commands`) -- [ ] Create and configure the Owner, Dev, Staff and User roles (IDs in `.env`) -- [ ] Set the channels: welcome, tickets, notifications, logs -- [ ] Configure each trigger voice channel (`/voice setup`) and check automatic creation/deletion -- [ ] Enable the **Server Members** intent in the developer portal -- [ ] Configure Gitea: least privilege token + webhook with a secret -- [ ] Protect and back up the SQLite database -- [ ] Test the critical paths: end-to-end ticket, warning, poll, Gitea webhook -- [ ] Test the API limits and the error paths -- [ ] Check the embeds on desktop and mobile -- [ ] Fill in the official links and the screenshots (`assets/screenshots/`) -- [ ] Publish the first version `0.1.0` (tag `v0.1.0` then `npm run changelog`) - -## 15. Resources - -- FWS organisation: `[link to add]` -- FWS Discord server: `[link to add]` -- FWS Arch repository: `[link to add]` -- Gitea instance: `[link to add]` -- FWS documentation: `[link to add]` -- Technical documentation: [`docs/architecture.md`](docs/architecture.md) -- Organisation conventions: [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md) -- Changelog: [`CHANGELOG.md`](CHANGELOG.md) _(generated)_ -- Instructions for AI agents: [`AGENTS.md`](AGENTS.md) -- French version of this document: [`README.md`](README.md) +# FWS-Bot + +> Discord bot for the open source **FWS** organisation — community support, tickets, moderation, Gitea integration and statistics for **FWS Arch** (an Arch Linux fork with a friendly layer on top). + +🌍 [Version française](README.md) · **English** + +Status: **working**. The 19 commands are implemented (support, private tickets, moderation, Gitea, polls, statistics, bot statuses, voice channel manager), together with member welcome and the Gitea webhook delivery. + +This project follows the [FWS organisation conventions](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md): English commit messages in the Conventional Commits format, `type/description` branches, reviewed pull requests merged with squash, SemVer and a `CHANGELOG.md` generated from the commits. + +--- + +## 1. Tech stack + +Deliberate choices: **a single runtime dependency** (discord.js), no native module to compile, and the test runner built into Node. + +| Tech | Version | Purpose | +| ------------------ | --------------------- | ------------------------------------------------------------------------- | +| **Node.js** | ≥ 22.13.0 (ESM) | Runtime. Required for `node:sqlite`, `process.loadEnvFile`, `--watch` | +| **discord.js** | ^14.21.0 | Discord API: slash commands, embeds, buttons, intents | +| **`node:sqlite`** | native module | SQLite database (WAL, foreign keys) — no `better-sqlite3`, no compilation | +| **native `fetch`** | — | Gitea REST client (with `AbortSignal.timeout`) | +| **`node:http`** | — | Gitea webhook server (no Express) | +| **`node:crypto`** | — | HMAC-SHA256 signature of the webhooks | +| **`node:test`** | — | Built-in unit tests (`node --test`) | +| **ESLint** | ^9.30.0 (flat config) | Linting | +| **Prettier** | ^3.6.2 | Formatting | + +## 2. Requirements + +- Node.js ≥ 22.13 (`node -v` to check) and npm +- A Discord application (free) with a bot token +- (Optional) a Gitea instance for issues/pull requests and webhooks + +## 3. Quick start with a test token + +### 3.1 Create the Discord application + +1. Open the [Discord Developer Portal](https://discord.com/developers/applications) → **New Application**. +2. **Bot** tab → **Reset Token** → copy the token: that is your `DISCORD_TOKEN` (never share it, never commit it). +3. Still in **Bot** → **Privileged Gateway Intents** → enable **Server Members Intent** (needed to welcome new members; `Message Content` is not required). +4. **General Information** tab → copy the **Application ID**: that is your `DISCORD_CLIENT_ID`. + +### 3.2 Invite the bot to a test server + +Replace `CLIENT_ID` with your Application ID: + +```text +https://discord.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot+applications.commands&permissions=1099812662294 +``` + +That URL pre-checks every permission the commands use: View Channels, Send Messages, Manage Messages, Embed Links, Read Message History, Kick Members, Ban Members, Manage Roles, Moderate Members (timeout), plus the voice channel ones: Manage Channels, Connect, Speak, Mute Members, Deafen Members, Move Members. You can also use **OAuth2 → URL Generator** with the `bot` + `applications.commands` scopes. + +Create (or reuse) a test server you own: that is what grants the bot the **Owner** level. + +### 3.3 Collect the Discord IDs + +On Discord: **Settings → Advanced → Developer Mode** on, then right-click a server / channel / role → **Copy ID**. + +| Variable | Where to find it | +| ----------------------------------------------------------------- | ------------------------------------------- | +| `DISCORD_GUILD_ID` | Right-click the test server | +| `ROLE_OWNER_ID`, `ROLE_DEV_ID`, `ROLE_STAFF_ID`, `ROLE_MEMBER_ID` | Server settings → Roles (create them first) | +| `CHANNEL_WELCOME_ID`, `CHANNEL_LOGS_ID`, etc. | Right-click each channel | + +> Without configured roles everyone counts as **User** (except the server owner, who is Owner). + +### 3.4 Run the bot + +```bash +# 1. Dependencies +npm install + +# 2. Configuration: copy .env.example to .env and fill it in +# Minimum required: DISCORD_TOKEN, DISCORD_CLIENT_ID, DISCORD_GUILD_ID +cp .env.example .env + +# 3. Create the SQLite database and apply the migrations +npm run db:init + +# 4. Register the slash commands on the server (instant, per guild) +npm run deploy:commands + +# 5. Start with automatic reload +npm run dev +``` + +The logs should show `Connected as `. Type `/help` on the server: you should see the commands your role can use. + +Without a `.env` the bot refuses to start (`assertRequiredEnv` checks the token, client ID and guild ID). + +## 4. Configuration — every variable (`.env`) + +Full template: [`.env.example`](.env.example). Default values in brackets. + +### Runtime + +| Variable | Default | Description | +| ----------------------------- | ------------- | ------------------------------------------------------------------------------- | +| `NODE_ENV` | `development` | `development` \| `production` \| `test` | +| `LOG_LEVEL` | `info` | `debug` \| `info` \| `warn` \| `error` | +| `LOG_DIR` | `./logs` | Directory of the daily JSON logs | +| `LOG_RETENTION_DAYS` | `30` | Retention window (purges `event_logs`) | +| `VOICE_EMPTY_GRACE_MS` | `5000` | Delay before a generated voice channel left empty is deleted (`0` = immediate) | +| `BOT_STATUS_INTERVAL_SECONDS` | `60` | Default rotation speed of the bot statuses (changeable with `/status interval`) | + +### Discord application + +| Variable | Description | +| ------------------- | ------------------------------------------------------------ | +| `DISCORD_TOKEN` | **Required.** Bot token (Developer Portal → Bot) | +| `DISCORD_CLIENT_ID` | **Required.** Application ID | +| `DISCORD_GUILD_ID` | **Required.** Server where the slash commands are registered | + +### FWS roles (Discord role IDs) + +| Variable | Matching level | +| ---------------- | ------------------------------------------ | +| `ROLE_OWNER_ID` | Owner — full access | +| `ROLE_DEV_ID` | Dev — FWS Arch configuration, Gitea writes | +| `ROLE_STAFF_ID` | Staff — moderation, support, tickets | +| `ROLE_MEMBER_ID` | Initial role given to new members | + +### Discord channels (IDs) + +| Variable | Usage | +| -------------------------------- | --------------------------------------------------------------------------- | +| `CHANNEL_WELCOME_ID` | Welcome messages | +| `CHANNEL_RULES_ID` | Rules (link sent to newcomers) | +| `CHANNEL_ANNOUNCEMENTS_ID` | FWS announcements | +| `CHANNEL_LOGS_ID` | Functional logs | +| `CHANNEL_MOD_LOGS_ID` | Moderation logs | +| `CHANNEL_TICKETS_LOGS_ID` | Ticket opening/closing journal | +| `CHANNEL_NOTIF_ISSUES_ID` | Issue notifications | +| `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Pull request notifications | +| `CHANNEL_NOTIF_COMMITS_ID` | Commit notifications | +| `CHANNEL_NOTIF_RELEASES_ID` | Release notifications | +| `CHANNEL_NOTIF_ERRORS_ID` | Errors and incidents | +| `CATEGORY_TICKETS_ID` | Category where the private ticket channels are created | +| `CHANNEL_VOICE_TRIGGER_ID` | Trigger voice channel (fallback: `/voice setup` manages a list of triggers) | +| `CATEGORY_VOICE_ID` | Home category of the generated voice channels (optional) | + +### Gitea + +| Variable | Default | Description | +| ------------------- | ------- | ---------------------------------------------------------------------- | +| `GITEA_URL` | — | Instance URL (without a trailing `/`) | +| `GITEA_TOKEN` | — | Least privilege token (`read:repository`, `write:issue`). Never logged | +| `GITEA_OWNER` | — | Repository owner (e.g. `FWS`) | +| `GITEA_REPO` | — | Target repository (e.g. `FWS-Arch`) | +| `GITEA_TIMEOUT_MS` | `10000` | Request timeout | +| `GITEA_MAX_RETRIES` | `2` | Retries on transient errors (429, 5xx, timeout) | + +### Gitea webhooks + +| Variable | Default | Description | +| ---------------------- | ----------------- | ---------------------------------------------------- | +| `WEBHOOK_ENABLED` | `false` | Starts the receiving HTTP server | +| `WEBHOOK_HOST` | `0.0.0.0` | Listening interface | +| `WEBHOOK_PORT` | `3000` | Listening port | +| `WEBHOOK_PATH` | `/webhooks/gitea` | Path to configure in Gitea | +| `GITEA_WEBHOOK_SECRET` | — | Shared secret (HMAC-SHA256), set in Gitea → Webhooks | + +### SQLite and links + +| Variable | Default | Description | +| -------------------------------------------------------------------------------- | ----------------------- | -------------------------------------------------------------------------------- | +| `DATABASE_PATH` | `./data/fws-bot.sqlite` | Database file (excluded from git) | +| `BACKUP_DIR` | `./data/backups` | Backup directory | +| `FWS_WEBSITE_URL`, `FWS_DOCS_URL`, `FWS_DISCORD_INVITE_URL`, `FWS_ARCH_REPO_URL` | — | Official links shown by `/fws info` and `/fws links` (empty buttons are omitted) | + +## 5. Slash commands + +19 commands are registered. Every command carries an **FWS access level** checked server-side before running, and the moderation commands additionally check the matching **Discord permission** (`DefaultMemberPermissions`). + +### Access levels + +Resolved from the roles configured in `.env` (highest to lowest): + +| Level | Who | +| ----------- | ------------------------------- | +| `OWNER` (3) | Owner role, or the server owner | +| `DEV` (2) | Dev role | +| `STAFF` (1) | Staff role | +| `USER` (0) | Every member | + +### General and FWS + +| Command | Options | Access | State | Description | +| --------------------------------------- | --------------------------------- | --------------------------- | ----- | -------------------------------------------------------------------------------------- | +| `/help` | — | User | ✅ | Lists the commands your role can use (ephemeral reply) | +| `/fws info` | — | User | ✅ | Presents FWS and FWS Arch (text overridable through `guild_settings`) + official links | +| `/fws links` | — | User | ✅ | Resources: website, docs, repository, Gitea, Discord | +| `/fws version` | — | User | ✅ | Latest Gitea release (tag, date, author) + button to the notes | +| `/fws status` | — | User | ✅ | Service status: Gitea API, webhooks, SQLite, Discord latency, uptime | +| `/fws changelog` | `version` (optional) | User | ✅ | Release notes (latest by default, clear message when the tag does not exist) | +| `/status add` | `text` (128 chars), `type`, `url` | **Staff** + _Manage Server_ | ✅ | Adds a status to the rotation; the first one is shown right away | +| `/status list` | — | **Staff** + _Manage Server_ | ✅ | Stored statuses: number, type, state, rotation speed | +| `/status remove` · `enable` · `disable` | `id` | **Staff** + _Manage Server_ | ✅ | Removes a status, puts it back in rotation or pauses it | +| `/status interval` | `seconds` (5–86 400) | **Staff** + _Manage Server_ | ✅ | Rotation speed, applied without a restart | +| `/status clear` | — | **Staff** + _Manage Server_ | ✅ | Empties the list and returns to the default line | + +### Gitea — issues and pull requests + +| Command | Options | Access | State | Description | +| ----------------- | ------------------------------------------- | ------------------- | ----- | ------------------------------------------------------ | +| `/issue create` | — (modal: title + description) | User (configurable) | ✅ | Creates a Gitea issue and returns its link | +| `/issue view` | `number` | User | ✅ | Title, author, state, labels, link of an issue | +| `/issue list` | — | User | ✅ | Open issues (last 15) | +| `/pr create` | `head`, `base` + modal (title, description) | **Dev** | ✅ | Creates a Gitea pull request | +| `/pr view` | `number` | User | ✅ | Title, author, state, branches, link of a pull request | +| `/pr list` | — | User | ✅ | Open pull requests (last 15) | +| `/gitea activity` | — | User | ✅ | Latest commits + open issues and pull requests | +| `/gitea release` | — | User | ✅ | FWS Arch releases (last 5) | + +> The Gitea client (`src/services/gitea/gitea-client.js`): REST with token, timeout, exponential retry on transient errors. The forms (`/issue create`, `/pr create`) go through a **modal**; the branch options are kept in memory for a few minutes (`pending-actions.js`). Any failure (missing token, 404, 5xx) becomes an explicit ephemeral message, never a raw error. + +### Support tickets + +Tickets are private channels created under `CATEGORY_TICKETS_ID`. One open ticket per member and per category (SQL constraint). + +| Command | Options | Access | State | Description | +| ---------------- | ------------------------------ | -------------------------------- | ----- | ------------------------------------------------------------------------------------ | +| `/ticket create` | `category` (required) | User (depending on the category) | ✅ | Creates a private channel under `CATEGORY_TICKETS_ID` | +| `/ticket close` | `reason` (optional, 500 chars) | Author, Staff | ✅ | Closes, logs and then deletes the channel (10 s) — also through the **Close** button | +| `/ticket claim` | — | **Staff** | ✅ | Takes the ticket over (**Claim** button) | +| `/ticket add` | `user` | **Staff** | ✅ | Adds a participant to the private channel | + +Available categories and who can use them: + +| Category | Visible to | +| ------------------------- | ----------------- | +| Aide et support | Staff, Owner | +| Bug | Staff, Dev, Owner | +| Question de développement | Dev, Owner | +| Signalement | Staff, Owner | +| Demande interne | Owner | + +### Temporary voice channels + +A server can declare **as many trigger channels as it needs** — one per theme (`Dev`, `SIO`, …) — each with its own home category (`/voice setup`): joining a trigger creates a private voice channel **at the bottom of that trigger's category**, moves the member in and hands over ownership. The channel is then managed from the **control panel** posted in its chat (_Rename_, _Limit_, _Lock_, _Claim_, _Delete_ buttons and the _Permit_, _Reject_, _Transfer_ menus) or with `/voice`. The number of simultaneous channels is **unlimited**, and a member keeps one channel **per trigger**: joining the same trigger again simply moves them back into the channel they already own. + +As soon as **nobody** is left in a generated channel, it is deleted: the delay (5 s by default) lets it survive a quick hop to another channel — tunable with `VOICE_EMPTY_GRACE_MS`, `0` deletes it immediately. A periodic sweep (at startup, then every minute) catches the cases where a Discord event was missed or a deletion was refused, so a generated channel cannot stay empty: either it is deleted, or the attempt is retried. + +| Command | Options | Access | Description | +| ---------------------------------------- | ------------------------------------------------------------ | --------------------- | ------------------------------------------------------------------------------------------- | +| `/voice setup` | `trigger`, `label`, `category`, `template`, `limit`, `panel` | **Staff** | Adds (or updates) a trigger channel; without `category`, the trigger's own category is used | +| `/voice config` · `/voice triggers list` | — | User · **Staff** | Declared triggers: category, template, limit, state and live channels | +| `/voice triggers disable` · `enable` | `trigger` | **Staff** | Pauses a trigger (its configuration is kept, joining it creates nothing) · resumes it | +| `/voice triggers remove` | `trigger` | **Staff** | Deletes a trigger declared from Discord | +| `/voice panel` | `trigger` (default: all) | **Staff** | Re-posts the explanation panel in the trigger channels | +| `/voice name` | `name` (100 chars) | Owner | Renames the channel | +| `/voice limit` | `limit` (0–99, 0 = unlimited) | Owner | Number of spots | +| `/voice lock` · `/voice unlock` | — | Owner | Refuses · allows everyone to join | +| `/voice permit` | `user` | Owner | Allows a member to join the channel | +| `/voice reject` | `user` | Owner | Denies access (and kicks them out if they are inside) | +| `/voice kick` | `user` | Owner | Kicks a member out of the channel | +| `/voice transfer` | `user` | Owner | Transfers ownership (the new owner must already be inside) | +| `/voice claim` | — | Member of the channel | Claims a channel whose owner left | +| `/voice delete` | `channel` (staff) | Owner, Staff | Deletes the channel immediately | +| `/voice info` | `channel` (staff) | User | Owner, state, limit, members, age | + +> Name template: `{user}` is replaced by the member's display name (default `🔊 Salon de {user}`). Staff can always act on any temporary channel. The owner receives `Manage Channel` + `Move Members` on their own channel only. +> +> `CHANNEL_VOICE_TRIGGER_ID` / `CATEGORY_VOICE_ID` remain a **fallback**: a server whose `.env` declares a trigger works without `/voice setup`, but a trigger coming from the environment can only be paused (`/voice triggers disable`), not deleted from Discord. Changing a trigger's category does not move the channels already created. + +### Moderation + +Every command checks the FWS level **and** the matching Discord permission. The bot refuses to act on a member whose highest role is equal or higher than the caller's (`canActOn`), and never acts on the server owner. + +| Command | Options | Discord permission | State | Description | +| ---------------- | ----------------------------------------- | ------------------ | ----- | ------------------------------------------------------------------ | +| `/warn` | `user`, `reason` (required) | Moderate Members | ✅ | Warns, notifies the member by DM and records the action | +| `/mute` | `user`, `minutes` (1–40320), `reason` | Moderate Members | ✅ | Temporary timeout (28 days max) + DM notification | +| `/kick` | `user`, `reason` | Kick Members | ✅ | Kicks from the server and logs the action | +| `/ban` | `user`, `reason`, `delete_days` (0–7) | Ban Members | ✅ | Bans (even if the member already left), optional message purge | +| `/clear` | `amount` (1–100) | Manage Messages | ✅ | Deletes the last N messages (those older than 14 days are skipped) | +| `/mod logs` | `user` (filter) | Moderate Members | ✅ | History read from `moderation_actions` (last 15, ephemeral) | +| `/role set` | `user`, `role`, `action` (`add`/`remove`) | Manage Roles | ✅ | Adds or removes a role (both hierarchies checked) | +| `/notify set` | `type`, `channel` | Manage Server | ✅ | Notification channel specific to this server (SQLite) | +| `/notify remove` | `type` | Manage Server | ✅ | Returns to the default channel (environment variables) | +| `/notify list` | — | Manage Server | ✅ | Current configuration of every type | + +> Every successful action is recorded in `moderation_actions` **and** posted in `CHANNEL_MOD_LOGS_ID` (member, moderator, reason, duration). + +### Community and statistics + +| Command | Options | Access | State | Description | +| ---------------- | --------------------------------------------------------------------- | --------- | ----- | ---------------------------------------------------------------- | +| `/poll create` | `question`, `choices` (separated by « ; », 2–10), `minutes` (1–10080) | **Staff** | ✅ | Poll voted with buttons, live results | +| `/poll close` | `id` | **Staff** | ✅ | Closes it, shows the winning choice and freezes the message | +| `/stats discord` | — | User | ✅ | Members, channels, roles, boosts, server age, latency | +| `/stats gitea` | — | User | ✅ | Recent commits, open issues and pull requests, latest release | +| `/stats fws` | — | User | ✅ | Local indicators (tickets, polls, moderation) + FWS Arch version | +| `/fun coinflip` | — | User | ✅ | Heads or tails | +| `/fun dice` | `sides` (2–1000, 6 by default) | User | ✅ | Dice roll | +| `/fun 8ball` | `question` | User | ✅ | Magic eight ball (12 answers) | +| `/fun choose` | `options` (separated by « ; », 2–10) | User | ✅ | Random pick | + +Legend: ✅ working · expected errors are returned as ephemeral messages (`UserFacingError`), everything else is logged and replaced by a generic message. + +## 6. Automations + +- **Welcome** (`src/events/guild-member-add.js`): assigns `ROLE_MEMBER_ID` (skipped when that role sits above the bot's), posts a welcome embed in `CHANNEL_WELCOME_ID` pointing at `CHANNEL_RULES_ID`, and sends a DM with the official links (silent when DMs are closed). +- **Departures** (`src/events/guild-member-remove.js`): embed in `CHANNEL_LOGS_ID` (falls back to `CHANNEL_MOD_LOGS_ID`) with the member count, time on the server and account age. +- **Notifications** (`src/services/notifications/notification-service.js`): routing per type — per-guild override in SQLite (`notification_channels`, configured with `/notify set`), otherwise the matching environment variable. A type without a channel is simply ignored (`debug` log). +- **Gitea webhooks**: native HTTP server (`WEBHOOK_ENABLED=true`). Verifies the **HMAC-SHA256** signature (`x-gitea-signature`) in constant time, rejects bodies over 1 MB and invalid JSON, deduplicates redeliveries through `webhook_deliveries`, then posts the embeds through the notification service: `issues` → issues, `pull_request` → PR, `push` → commits, `create`/`delete` → refs, `release` → releases. +- **Polls** (`src/services/polls/poll-service.js`): one vote per member and per poll (changeable, one click moves the vote), the message is refreshed on every vote, and a scheduler closes expired polls automatically (checked every 30 s) even after a restart. +- **Bot statuses** (`src/services/status/bot-status-service.js`): the presence shown under the bot name is a **list stored in the database** (`bot_statuses`), editable live with `/status` (add, remove, pause, speed). The rotation starts over from the first enabled status each cycle and the delay is re-read on every turn, so `/status interval` applies without restarting the bot. Empty list → default line “les commandes avec /help” instead of a hard-coded status. +- **Voice channels** (`src/events/voice-state-update.js`): joining **one of the trigger channels** creates a temporary channel at the bottom of that trigger's category and moves the member in (or moves them back into the one they already own for that trigger); as soon as the last member leaves, the channel is deleted after a short grace period (`VOICE_EMPTY_GRACE_MS`, 5 s by default) that leaves time to switch channels without losing theirs. The deletion only forgets the database row once the channel is really gone: an API error keeps it registered so the attempt can be retried. `sweepVoiceChannels()` forgets vanished channels and deletes the empty ones — at startup, then every minute through `startVoiceJanitor()`, which guarantees a generated channel never survives empty after a missed event or a failed API call. + +## 7. Architecture + +Full details: [`docs/architecture.md`](docs/architecture.md). + +```text +src/ +├── index.js # Entry point: env, DB, client, loaders, webhooks, clean shutdown +├── config/ # env.js (.env reading/validation) · constants.js (colors, levels, categories) +├── core/ # client.js · command-loader.js · event-loader.js +│ # permissions.js (levels + hierarchy) · logger.js · errors.js +├── commands// # fws, gitea, tickets, moderation, community, general +├── events/ # interaction-create (commands, buttons, modals), ready, member add/remove, +│ # voice state (voice channels), errors, shard +├── services/ +│ ├── gitea/ # gitea-client.js (REST + retry) · gitea-embeds.js · gitea-modals.js · pending-actions.js +│ ├── members/ # member-service.js (welcome, initial role, departures) +│ ├── moderation/ # moderation-service.js (hierarchy, sanctions, journal) +│ ├── notifications/ # notification-service.js (routing) · gitea-notifications.js (webhook mapping) +│ ├── polls/ # poll-service.js (creation, votes, closing, scheduler) +│ ├── status/ # bot-status-service.js (bot statuses, validation, rotation) +│ ├── tickets/ # ticket-service.js (private channels, lifecycle) +│ └── voice/ # voice-service.js (several triggers, temporary channels, panel) +├── database/ # index.js (connection + SQL migrations) · migrations/ · repositories/ +├── webhooks/ # server.js (node:http) · gitea-webhook.js (signature + dispatch) +├── ui/ # embeds.js (visual identity) · buttons.js (links, tickets, polls) +└── utils/ # retry.js (exponential backoff) · cooldown.js +``` + +Automatic loading: any command under `src/commands/**` and any event under `src/events/*` is picked up at startup. + +**Command contract** (`access` checked in `interaction-create.js`, a `UserFacingError` is shown as-is, any other error is logged and replaced by a generic message): + +```js +export const access = ACCESS_LEVELS.STAFF; // minimum level +export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optional, per subcommand +export const data = new SlashCommandBuilder(); /* ... */ +export async function execute(interaction) {} +``` + +**Intents used**: `Guilds`, `GuildMembers` _(privileged — enable it in the portal)_, `GuildModeration`, `GuildMessages`, `GuildVoiceStates`. `MessageContent` is deliberately not requested. + +### Message tone and vocabulary + +Every text shown in Discord follows the same rules, listed at the top of `src/ui/embeds.js` (single source of truth): + +- **Informal “tu”**, short sentences, active voice; never a reproach, irony or shouting capitals. +- The **title** states the outcome, the **description** says what to do next; one emoji per title, never decorative inside the body. +- **No gendered agreement** on a person: “tu es propriétaire”, “cette personne”, “l'équipe”, “ce membre” — no “il / elle”, no “cher / chère”, no inclusive dots. +- An **error** explains the cause, recalls the rule and offers the way out; a success thanks and gives the next step (`/ban` points at `/mod logs`, `/ticket create` recalls that the owner can close). +- Shared titles: `✅ C'est fait`, `❌ Oups`, `⚠️ Attention`, `💡 Bon à savoir` (`TONE` in `src/ui/embeds.js`). Lists always prefixed with `•` (`bullets()`), closing advice line added by `withHint()`. +- Same vocabulary everywhere: **équipe** (staff), **membre**, **salon**, **ticket**, **motif** (never “raison” as a label), voice **déclencheur**. + +## 8. Database (SQLite) + +- Engine: `node:sqlite` (`DatabaseSync`), **WAL** mode, foreign keys enabled. +- Migrations: numbered SQL files in `src/database/migrations/`, applied in a transaction and tracked in `schema_migrations` (`npm run db:init`). +- Tables: `guild_settings` (per-guild settings), `notification_channels`, `ticket_categories`, `tickets` (one open ticket per author and category), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (voice triggers and their category), `voice_channels` (owner, lock, limit), `bot_statuses` (bot statuses, global — unique text), `event_logs`, `webhook_deliveries`. +- Data access: one repository per domain (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-repository.js`) — SQL queries never leave that layer. +- Migrations `002-ticket-and-poll-details.sql` (claim tracking `claimed_at` and closing `close_reason`), `003-voice-channels.sql` (temporary voice channels), `004-voice-triggers.sql` (several voice triggers per server) and `005-bot-statuses.sql` (bot statuses edited from a command) complete the initial schema. +- The database holds real data: it is **excluded from git** (`.gitignore`) and must be backed up (`BACKUP_DIR`). + +## 9. Logs + +- **JSON** format, one line per entry, one file per day: `logs/YYYY-MM-DD.log` + console. +- Levels filtered by `LOG_LEVEL`; errors and warnings go to stderr. +- **Secret masking**: the Discord token, Gitea token and webhook secret are replaced with `***` in every logged line. +- Functional retention: `LOG_RETENTION_DAYS` (purges `event_logs`). + +## 10. npm scripts + +| Script | Purpose | +| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `npm start` | Starts the bot (`node src/index.js`) | +| `npm run dev` | Starts with automatic reload (`node --watch`) | +| `npm run deploy:commands` | Registers the slash commands on `DISCORD_GUILD_ID` (run it again after adding or changing a command) | +| `npm run db:init` | Creates the SQLite database and applies the migrations | +| `npm run lint` / `npm run lint:fix` | ESLint (check / fix) | +| `npm run format` / `npm run format:check` | Prettier (format / check) | +| `npm run changelog` | Regenerates `CHANGELOG.md` from the Conventional Commits (see §12) | +| `npm run changelog:check` | Fails with exit code 1 when `CHANGELOG.md` is out of date | +| `npm test` | `node:test` unit tests: `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs` | + +When something goes wrong: run `npm run deploy:commands` after any command change, check that the **Server Members** intent is enabled, and that the bot has the permissions listed in 3.2 on its target channels. + +## 11. Security + +- Permissions are checked **server-side** (FWS level + Discord permissions + role hierarchy): the client is never trusted. +- No action is possible on a role or member positioned above the caller. +- Secrets are never committed (`.env` is ignored) nor logged in plain text (automatic masking). +- Gitea webhooks: mandatory HMAC-SHA256 signature, constant-time comparison, 1 MB body limit, duplicate protection on the delivery ID. +- Least privilege tokens; rate limits respected (timeout + controlled retry on transient errors only). +- User input is validated (`setMinValue`/`setMaxValue`/`setMaxLength` on every option). + +## 12. Versioning and releases + +- **SemVer** (`MAJOR.MINOR.PATCH`): `MAJOR` = breaking change, `MINOR` = backwards-compatible feature, `PATCH` = fix. Current version: see `version` in [`package.json`](package.json) (before `1.0.0` anything may change — a breaking change only bumps `MINOR`, as SemVer §4 states). +- **`CHANGELOG.md` is generated** from the Conventional Commits: `npm run changelog` (`feat:` feeds _Features_, `fix:` feeds _Bug Fixes_, the other types go to _Other changes_). The script also prints the **suggested next version**; `npm run changelog:check` fails when the file is out of date. +- Tags are picked up automatically: every `vX.Y.Z` tag found in the history opens its own section in the changelog, newer commits stay under `[Unreleased]`. +- Generating it is part of the definition of done: the file is never edited by hand. + +## 13. Contributing + +The rules shared by every FWS repository live in the [organisation `.profile`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md). Summary as applied here: + +### Commits + +- Messages in **English**, **Conventional Commits** format: `(): `. +- Allowed types: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`. +- Short imperative title; a **body** is added only to explain the _why_ (context, decision, trade-off). + +### Branches and pull requests + +1. Create a `type/description` branch **from `main`** (e.g. `feat/ticket-service`, `fix/voice-cleanup`). +2. Commit following the conventions above. +3. Open a **pull request** with a clear title and description, referencing the issue (`Fixes #123`). +4. **At least one reviewer** approves; the tests must pass. +5. Merge with **squash**: 1 PR = 1 clean commit on `main`. + +### Work organisation + +- Project **Kanban** board: _Backlog / To do_, _In progress_, _In review_, _Done_. One card = one unit of work = one branch + one pull request; a card only moves to _Done_ once its pull request is merged. +- Every bug or request goes through an **issue** (clear title + precise description) with a recommended label: `bug`, `enhancement`, `question`, `good first issue`, `help wanted`. Templates are provided in [`.gitea/ISSUE_TEMPLATE/`](.gitea/ISSUE_TEMPLATE) and [`.gitea/PULL_REQUEST_TEMPLATE.md`](.gitea/PULL_REQUEST_TEMPLATE.md). +- A bug report includes the **reproduction steps**, the **expected** vs **observed** behaviour, the **environment** and useful **logs**. + +### Code and documentation + +- Files in **kebab-case**, identifiers **in English**, comments **in English** explaining the _why_ (the non-obvious: trade-offs, edge cases, references). +- Check the stack and the dependencies already present before adding a new one (a single runtime dependency here: `discord.js`). +- Before proposing: `npm run lint`, `npm run format:check`, `npm test` and `npm run changelog` must pass. +- **Bilingual** documentation: [`README.md`](README.md) (FR) and [`README.en.md`](README.en.md) (EN) stay in sync; a test enforces it. +- Instructions for AI agents: [`AGENTS.md`](AGENTS.md), updated together with the conventions. + +## 14. Production checklist + +- [ ] Rename the repository to `fws-discordbot` on Gitea (the organisation `fws-*` convention) +- [ ] Create the Kanban board (_Backlog / To do_, _In progress_, _In review_, _Done_) +- [ ] Fill in the bot statuses (`/status add`, `/status interval`) — the rotation is stored in the database +- [ ] Register the slash commands on the FWS server (`npm run deploy:commands`) +- [ ] Create and configure the Owner, Dev, Staff and User roles (IDs in `.env`) +- [ ] Set the channels: welcome, tickets, notifications, logs +- [ ] Configure each trigger voice channel (`/voice setup`) and check automatic creation/deletion +- [ ] Enable the **Server Members** intent in the developer portal +- [ ] Configure Gitea: least privilege token + webhook with a secret +- [ ] Protect and back up the SQLite database +- [ ] Test the critical paths: end-to-end ticket, warning, poll, Gitea webhook +- [ ] Test the API limits and the error paths +- [ ] Check the embeds on desktop and mobile +- [ ] Fill in the official links and the screenshots (`assets/screenshots/`) +- [ ] Publish the first version `0.1.0` (tag `v0.1.0` then `npm run changelog`) + +## 15. Resources + +- FWS organisation: `[link to add]` +- FWS Discord server: `[link to add]` +- FWS Arch repository: `[link to add]` +- Gitea instance: `[link to add]` +- FWS documentation: `[link to add]` +- Technical documentation: [`docs/architecture.md`](docs/architecture.md) +- Organisation conventions: [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md) +- Changelog: [`CHANGELOG.md`](CHANGELOG.md) _(generated)_ +- Instructions for AI agents: [`AGENTS.md`](AGENTS.md) +- French version of this document: [`README.md`](README.md) diff --git a/README.md b/README.md index 889495a..1aca567 100644 --- a/README.md +++ b/README.md @@ -1,473 +1,473 @@ -# FWS-Bot - -> Bot Discord de l'organisation open source **FWS** — assistance communautaire, tickets, modération, intégration Gitea et statistiques pour **FWS Arch** (fork d'Arch Linux avec surcouche conviviale). - -🌍 **Français** · [English version](README.en.md) - -Statut : **fonctionnel**. Les 19 commandes sont implémentées (assistance, tickets privés, modération, Gitea, sondages, statistiques, statuts du bot, gestionnaire de salons vocaux), tout comme l'accueil des membres et la diffusion des webhooks Gitea. - -Projet conforme aux [conventions de l'organisation FWS](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md) : commits en anglais au format Conventional Commits, branche `type/description`, PR relue puis mergée en squash, SemVer et `CHANGELOG.md` généré depuis les commits. - ---- - -## 1. Stack technique - -Choix assumés : **une seule dépendance runtime** (discord.js), aucun module natif à compiler, outil de test intégré à Node. - -| Techno | Version | Rôle | -| --- | --- | --- | -| **Node.js** | ≥ 22.13.0 (ESM) | Runtime. Requis pour `node:sqlite`, `process.loadEnvFile`, `--watch` | -| **discord.js** | ^14.21.0 | API Discord : commandes slash, embeds, boutons, intents | -| **`node:sqlite`** | module natif | Base SQLite (WAL, foreign keys) — pas de `better-sqlite3` ni compilation | -| **`fetch` natif** | — | Client REST Gitea (avec `AbortSignal.timeout`) | -| **`node:http`** | — | Serveur de webhooks Gitea (sans Express) | -| **`node:crypto`** | — | Signature HMAC-SHA256 des webhooks | -| **`node:test`** | — | Tests unitaires intégrés (`node --test`) | -| **ESLint** | ^9.30.0 (flat config) | Lint | -| **Prettier** | ^3.6.2 | Format | - -## 2. Prérequis - -- Node.js ≥ 22.13 (`node -v` pour vérifier) et npm -- Une application Discord (gratuite) avec un token de bot -- (Optionnel) une instance Gitea pour les issues/PR et les webhooks - -## 3. Démarrage rapide avec un token de test - -### 3.1 Créer l'application Discord - -1. Ouvre le [Discord Developer Portal](https://discord.com/developers/applications) → **New Application**. -2. Onglet **Bot** → **Reset Token** → copie le token : c'est ton `DISCORD_TOKEN` (ne le partage jamais, ne le committe jamais). -3. Toujours dans **Bot** → **Privileged Gateway Intents** → active **Server Members Intent** (requis pour l'accueil des nouveaux membres ; `Message Content` n'est pas nécessaire). -4. Onglet **General Information** → copie l'**Application ID** : c'est ton `DISCORD_CLIENT_ID`. - -### 3.2 Inviter le bot sur un serveur de test - -Remplace `CLIENT_ID` par ton Application ID : - -```text -https://discord.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot+applications.commands&permissions=1099812662294 -``` - -Cette URL pré-coche les permissions utilisées par les commandes : Voir les salons, Envoyer des messages, Gérer les messages, Intégrer des liens, Lire l'historique, Expulser, Bannir, Gérer les rôles, Modérer les membres (timeout), ainsi que celles des salons vocaux : Gérer les salons, Se connecter, Parler, Rendre muet, Rendre sourd, Déplacer les membres. Tu peux aussi passer par **OAuth2 → URL Generator** avec les scopes `bot` + `applications.commands`. - -Crée (ou utilise) un serveur de test dont tu es propriétaire : c'est lui qui donne le niveau **Owner** au bot. - -### 3.3 Récupérer les IDs Discord - -Sur Discord : **Paramètres → Avancés → Mode développeur** activé, puis clic droit sur un serveur / salon / rôle → **Copier l'identifiant**. - -| Variable | Où le trouver | -| --- | --- | -| `DISCORD_GUILD_ID` | Clic droit sur le serveur de test | -| `ROLE_OWNER_ID`, `ROLE_DEV_ID`, `ROLE_STAFF_ID`, `ROLE_MEMBER_ID` | Paramètres du serveur → Rôles (crée-les d'abord) | -| `CHANNEL_WELCOME_ID`, `CHANNEL_LOGS_ID`, etc. | Clic droit sur chaque salon | - -> Si les rôles ne sont pas configurés, tout le monde est considéré **User** (sauf le propriétaire du serveur = Owner). - -### 3.4 Lancer le bot - -```bash -# 1. Dépendances -npm install - -# 2. Configuration : copie .env.example vers .env puis remplis-le -# Minimum requis : DISCORD_TOKEN, DISCORD_CLIENT_ID, DISCORD_GUILD_ID -cp .env.example .env - -# 3. Créer la base SQLite et appliquer les migrations -npm run db:init - -# 4. Enregistrer les commandes slash sur le serveur (instantané, par guild) -npm run deploy:commands - -# 5. Démarrer avec rechargement automatique -npm run dev -``` - -Dans les logs tu dois voir `Connected as `. Tape `/help` sur le serveur : tu dois voir la liste des commandes accessibles selon ton rôle. - -Sans `.env`, le bot refuse de démarrer (`assertRequiredEnv` vérifie token, client ID et guild ID). - -## 4. Configuration — toutes les variables (`.env`) - -Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre parenthèses. - -### Runtime - -| Variable | Défaut | Description | -| --- | --- | --- | -| `NODE_ENV` | `development` | `development` \| `production` \| `test` | -| `LOG_LEVEL` | `info` | `debug` \| `info` \| `warn` \| `error` | -| `LOG_DIR` | `./logs` | Dossier des logs JSON journaliers | -| `LOG_RETENTION_DAYS` | `30` | Durée de conservation (purge des `event_logs`) | -| `VOICE_EMPTY_GRACE_MS` | `5000` | Délai avant qu'un salon vocal généré devenu vide soit supprimé (`0` = immédiat) | -| `BOT_STATUS_INTERVAL_SECONDS` | `60` | Rythme par défaut de la rotation des statuts du bot (modifiable par `/status interval`) | - -### Application Discord - -| Variable | Description | -| --- | --- | -| `DISCORD_TOKEN` | **Requis.** Token du bot (Developer Portal → Bot) | -| `DISCORD_CLIENT_ID` | **Requis.** Application ID | -| `DISCORD_GUILD_ID` | **Requis.** Serveur d'enregistrement des commandes slash | - -### Rôles FWS (IDs de rôles Discord) - -| Variable | Niveau correspondant | -| --- | --- | -| `ROLE_OWNER_ID` | Owner — accès complet | -| `ROLE_DEV_ID` | Dev — configuration FWS Arch, écritures Gitea | -| `ROLE_STAFF_ID` | Staff — modération, support, tickets | -| `ROLE_MEMBER_ID` | Rôle initial attribué aux nouveaux membres | - -### Salons Discord (IDs) - -| Variable | Usage | -| --- | --- | -| `CHANNEL_WELCOME_ID` | Messages de bienvenue | -| `CHANNEL_RULES_ID` | Règlement (lien envoyé aux nouveaux) | -| `CHANNEL_ANNOUNCEMENTS_ID` | Annonces FWS | -| `CHANNEL_LOGS_ID` | Logs fonctionnels | -| `CHANNEL_MOD_LOGS_ID` | Logs de modération | -| `CHANNEL_TICKETS_LOGS_ID` | Journal d'ouverture/fermeture des tickets | -| `CHANNEL_NOTIF_ISSUES_ID` | Notifications issues | -| `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Notifications pull requests | -| `CHANNEL_NOTIF_COMMITS_ID` | Notifications commits | -| `CHANNEL_NOTIF_RELEASES_ID` | Notifications releases | -| `CHANNEL_NOTIF_ERRORS_ID` | Erreurs et incidents | -| `CATEGORY_TICKETS_ID` | Catégorie où sont créés les salons de tickets privés | -| `CHANNEL_VOICE_TRIGGER_ID` | Salon vocal déclencheur (repli : `/voice setup` gère une liste de déclencheurs) | -| `CATEGORY_VOICE_ID` | Catégorie d'accueil des salons vocaux créés (facultatif) | - -### Gitea - -| Variable | Défaut | Description | -| --- | --- | --- | -| `GITEA_URL` | — | URL de l'instance (sans `/` final) | -| `GITEA_TOKEN` | — | Token à moindre privilège (`read:repository`, `write:issue`). Jamais loggé | -| `GITEA_OWNER` | — | Propriétaire du dépôt (ex. `FWS`) | -| `GITEA_REPO` | — | Dépôt ciblé (ex. `FWS-Arch`) | -| `GITEA_TIMEOUT_MS` | `10000` | Timeout des requêtes | -| `GITEA_MAX_RETRIES` | `2` | Tentatives sur erreurs transitoires (429, 5xx, timeout) | - -### Webhooks Gitea - -| Variable | Défaut | Description | -| --- | --- | --- | -| `WEBHOOK_ENABLED` | `false` | Démarre le serveur HTTP de réception | -| `WEBHOOK_HOST` | `0.0.0.0` | Interface d'écoute | -| `WEBHOOK_PORT` | `3000` | Port d'écoute | -| `WEBHOOK_PATH` | `/webhooks/gitea` | Chemin à configurer dans Gitea | -| `GITEA_WEBHOOK_SECRET` | — | Secret partagé (HMAC-SHA256), défini dans Gitea → Webhooks | - -### SQLite et liens - -| Variable | Défaut | Description | -| --- | --- | --- | -| `DATABASE_PATH` | `./data/fws-bot.sqlite` | Fichier de base (exclu de git) | -| `BACKUP_DIR` | `./data/backups` | Dossier de sauvegarde | -| `FWS_WEBSITE_URL`, `FWS_DOCS_URL`, `FWS_DISCORD_INVITE_URL`, `FWS_ARCH_REPO_URL` | — | Liens officiels affichés par `/fws info` et `/fws links` (les boutons vides sont omis) | - -## 5. Commandes slash - -19 commandes sont enregistrées. Chaque commande a un **niveau d'accès FWS** vérifié côté serveur avant exécution, et les commandes de modération vérifient en plus les **permissions Discord** (`DefaultMemberPermissions`). - -### Niveaux d'accès - -Résolus depuis les rôles configurés dans `.env` (du plus haut au plus bas) : - -| Niveau | Qui | -| --- | --- | -| `OWNER` (3) | Rôle Owner, ou propriétaire du serveur | -| `DEV` (2) | Rôle Dev | -| `STAFF` (1) | Rôle Staff | -| `USER` (0) | Tous les membres | - -### Générales et FWS - -| Commande | Options | Accès | État | Description | -| --- | --- | --- | --- | --- | -| `/help` | — | User | ✅ | Liste les commandes accessibles selon ton rôle (réponse éphémère) | -| `/fws info` | — | User | ✅ | Présente FWS et FWS Arch (texte surchargeable via `guild_settings`) + liens officiels | -| `/fws links` | — | User | ✅ | Ressources : site, docs, dépôt, Gitea, Discord | -| `/fws version` | — | User | ✅ | Dernière release Gitea (tag, date, auteur) + bouton vers les notes | -| `/fws status` | — | User | ✅ | État des services : API Gitea, webhooks, SQLite, latence Discord, uptime | -| `/fws changelog` | `version` (optionnel) | User | ✅ | Notes de version (dernière par défaut, message clair si le tag n'existe pas) | -| `/status add` | `text` (128 car.), `type`, `url` | **Staff** + *Gérer le serveur* | ✅ | Ajoute un statut à la rotation ; le premier ajouté s'affiche tout de suite | -| `/status list` | — | **Staff** + *Gérer le serveur* | ✅ | Statuts enregistrés : numéro, type, état, rythme de rotation | -| `/status remove` · `enable` · `disable` | `id` | **Staff** + *Gérer le serveur* | ✅ | Retire un statut, le remet en rotation ou le met en pause | -| `/status interval` | `seconds` (5–86 400) | **Staff** + *Gérer le serveur* | ✅ | Rythme de la rotation, appliqué sans redémarrage | -| `/status clear` | — | **Staff** + *Gérer le serveur* | ✅ | Vide la liste et revient à la ligne par défaut | - -### Gitea — issues et pull requests - -| Commande | Options | Accès | État | Description | -| --- | --- | --- | --- | --- | -| `/issue create` | — (modale : titre + description) | User (configurable) | ✅ | Crée une issue Gitea et renvoie son lien | -| `/issue view` | `number` | User | ✅ | Titre, auteur, état, labels, lien d'une issue | -| `/issue list` | — | User | ✅ | Issues ouvertes (15 dernières) | -| `/pr create` | `head`, `base` + modale (titre, description) | **Dev** | ✅ | Crée une pull request Gitea | -| `/pr view` | `number` | User | ✅ | Titre, auteur, état, branches, lien d'une PR | -| `/pr list` | — | User | ✅ | PR ouvertes (15 dernières) | -| `/gitea activity` | — | User | ✅ | Derniers commits + issues et PR ouvertes | -| `/gitea release` | — | User | ✅ | Releases de FWS Arch (5 dernières) | - -> Le client Gitea (`src/services/gitea/gitea-client.js`) : REST avec token, timeout, retry exponentiel sur erreurs transitoires. Les formulaires (`/issue create`, `/pr create`) passent par une **modale** ; les options de branches y sont conservées en mémoire quelques minutes (`pending-actions.js`). Toute panne (token absent, 404, 5xx) devient un message éphémère explicite, jamais une erreur brute. - -### Tickets de support - -Les tickets sont des salons privés créés sous `CATEGORY_TICKETS_ID`. Un seul ticket ouvert par membre et par catégorie (contrainte SQL). - -| Commande | Options | Accès | État | Description | -| --- | --- | --- | --- | --- | -| `/ticket create` | `category` (obligatoire) | User (selon la catégorie) | ✅ | Crée un salon privé sous `CATEGORY_TICKETS_ID` | -| `/ticket close` | `reason` (optionnel, 500 car.) | Auteur, Staff | ✅ | Ferme, journalise puis supprime le salon (10 s) — aussi via le bouton **Fermer** | -| `/ticket claim` | — | **Staff** | ✅ | Prend le ticket en charge (bouton **Prendre en charge**) | -| `/ticket add` | `user` | **Staff** | ✅ | Ajoute un participant au salon privé | - -Catégories disponibles et qui y a accès : - -| Catégorie | Visible par | -| --- | --- | -| Aide et support | Staff, Owner | -| Bug | Staff, Dev, Owner | -| Question de développement | Dev, Owner | -| Signalement | Staff, Owner | -| Demande interne | Owner | - -### Salons vocaux temporaires - -Un serveur peut déclarer **autant de salons déclencheurs que nécessaire** — un par thème (`Dev`, `SIO`, …) — chacun avec sa propre catégorie d'accueil (`/voice setup`) : rejoindre un déclencheur crée un salon vocal privé **en bas de la catégorie de ce déclencheur**, y déplace le membre et lui en donne la propriété. Le salon se gère ensuite depuis le **panneau de contrôle** publié dans son chat (boutons *Renommer*, *Limiter*, *Verrouiller*, *Réclamer*, *Supprimer* et menus *Autoriser*, *Exclure*, *Transférer*) ou avec `/voice`. Le nombre de salons simultanés est **illimité**, et un membre conserve un salon **par déclencheur** : rejoindre à nouveau le même déclencheur le renvoie simplement dans le salon qu'il possède déjà. - -Dès que **plus personne** ne reste dans un salon généré, il est supprimé : le délai (5 s par défaut) le laisse survivre à un passage rapide dans un autre salon — réglable par `VOICE_EMPTY_GRACE_MS`, `0` le supprime immédiatement. Un balayage automatique (au démarrage puis toutes les minutes) rattrape les cas où l'événement Discord a été manqué ou la suppression refusée, si bien qu'un salon généré ne peut pas rester vide : soit il est supprimé, soit la tentative est réessayée. - -| Commande | Options | Accès | Description | -| --- | --- | --- | --- | -| `/voice setup` | `trigger`, `label`, `category`, `template`, `limit`, `panel` | **Staff** | Ajoute (ou met à jour) un salon déclencheur ; sans `category`, celle du salon déclencheur est utilisée | -| `/voice config` · `/voice triggers list` | — | User · **Staff** | Déclencheurs déclarés : catégorie, modèle, limite, état et salons actifs | -| `/voice triggers disable` · `enable` | `trigger` | **Staff** | Désactive un déclencheur (sans perdre sa configuration, y entrer ne crée plus de salon) · le réactive | -| `/voice triggers remove` | `trigger` | **Staff** | Supprime un déclencheur déclaré dans Discord | -| `/voice panel` | `trigger` (défaut : tous) | **Staff** | Republie le panneau d'explication dans les salons déclencheurs | -| `/voice name` | `name` (100 car.) | Propriétaire | Renomme le salon | -| `/voice limit` | `limit` (0–99, 0 = illimité) | Propriétaire | Nombre de places | -| `/voice lock` · `/voice unlock` | — | Propriétaire | Refuse · autorise l'accès de tout le monde | -| `/voice permit` | `user` | Propriétaire | Autorise un membre à rejoindre le salon | -| `/voice reject` | `user` | Propriétaire | Interdit l'accès (et l'éjecte s'il y est déjà) | -| `/voice kick` | `user` | Propriétaire | Éjecte un membre du salon | -| `/voice transfer` | `user` | Propriétaire | Transfère la propriété (le nouveau doit être dans le salon) | -| `/voice claim` | — | Membre du salon | Récupère un salon dont le propriétaire est parti | -| `/voice delete` | `channel` (staff) | Propriétaire, Staff | Supprime immédiatement le salon | -| `/voice info` | `channel` (staff) | User | Propriétaire, état, limite, membres, ancienneté | - -> Modèle de nom : `{user}` est remplacé par le pseudo du membre (défaut `🔊 Salon de {user}`). Le staff peut toujours agir sur n'importe quel salon temporaire. Le propriétaire reçoit `Gérer le salon` + `Déplacer des membres` sur son seul salon. -> -> `CHANNEL_VOICE_TRIGGER_ID` / `CATEGORY_VOICE_ID` restent un **repli** : un serveur dont le `.env` déclare un déclencheur fonctionne sans `/voice setup`, mais ce déclencheur venu de l'environnement ne peut qu'être désactivé (`/voice triggers disable`), pas supprimé depuis Discord. Changer la catégorie d'un déclencheur ne déplace pas les salons déjà créés. - -### Modération - -Chaque commande vérifie le niveau FWS **et** la permission Discord correspondante. Le bot refuse d'agir sur un membre dont le plus haut rôle est égal ou supérieur à celui de l'auteur (`canActOn`), et n'agit jamais sur le propriétaire du serveur. - -| Commande | Options | Permission Discord | État | Description | -| --- | --- | --- | --- | --- | -| `/warn` | `user`, `reason` (obligatoires) | Modérer les membres | ✅ | Avertit, prévient le membre en MP et enregistre l'action | -| `/mute` | `user`, `minutes` (1–40320), `reason` | Modérer les membres | ✅ | Timeout temporaire (28 j max) + notification en MP | -| `/kick` | `user`, `reason` | Expulser | ✅ | Expulse du serveur et journalise l'action | -| `/ban` | `user`, `reason`, `delete_days` (0–7) | Bannir | ✅ | Bannit (même si le membre a déjà quitté), purge optionnelle des messages | -| `/clear` | `amount` (1–100) | Gérer les messages | ✅ | Supprime les N derniers messages (ceux de plus de 14 j sont ignorés) | -| `/mod logs` | `user` (filtre) | Modérer les membres | ✅ | Historique lu depuis `moderation_actions` (15 dernières, éphémère) | -| `/role set` | `user`, `role`, `action` (`add`/`remove`) | Gérer les rôles | ✅ | Attribue ou retire un rôle (double hiérarchie vérifiée) | -| `/notify set` | `type`, `channel` | Gérer le serveur | ✅ | Salon de notification propre à ce serveur (SQLite) | -| `/notify remove` | `type` | Gérer le serveur | ✅ | Revenir au salon par défaut (variables d'environnement) | -| `/notify list` | — | Gérer le serveur | ✅ | Configuration actuelle de chaque type | - -> Chaque action réussie est enregistrée dans `moderation_actions` **et** publiée dans `CHANNEL_MOD_LOGS_ID` (cible, modérateur, raison, durée). - -### Communauté et statistiques - -| Commande | Options | Accès | État | Description | -| --- | --- | --- | --- | --- | -| `/poll create` | `question`, `choices` (« ; » séparés, 2–10), `minutes` (1–10080) | **Staff** | ✅ | Sondage voté par boutons, résultats en direct | -| `/poll close` | `id` | **Staff** | ✅ | Clôture, affiche le résultat gagnant et fige le message | -| `/stats discord` | — | User | ✅ | Membres, salons, rôles, boosts, âge du serveur, latence | -| `/stats gitea` | — | User | ✅ | Commits récents, issues et PR ouvertes, dernière release | -| `/stats fws` | — | User | ✅ | Indicateurs locaux (tickets, sondages, modération) + version FWS Arch | -| `/fun coinflip` | — | User | ✅ | Pile ou face | -| `/fun dice` | `sides` (2–1000, 6 par défaut) | User | ✅ | Lancer de dé | -| `/fun 8ball` | `question` | User | ✅ | Boule magique (12 réponses) | -| `/fun choose` | `options` (« ; » séparés, 2–10) | User | ✅ | Choix aléatoire argumenté | - -Légende : ✅ fonctionnel · les erreurs attendues sont renvoyées en message éphémère (`UserFacingError`), les autres sont loggées et remplacées par un message générique. - -## 6. Automatisations - -- **Accueil** (`src/events/guild-member-add.js`) : attribution du rôle `ROLE_MEMBER_ID` (ignorée si le rôle est au-dessus de celui du bot), embed de bienvenue dans `CHANNEL_WELCOME_ID` avec renvoi vers `CHANNEL_RULES_ID`, et message privé contenant les liens officiels (silencieux si les MP sont fermés). -- **Départs** (`src/events/guild-member-remove.js`) : embed dans `CHANNEL_LOGS_ID` (repli sur `CHANNEL_MOD_LOGS_ID`) avec effectif, ancienneté et âge du compte. -- **Notifications** (`src/services/notifications/notification-service.js`) : routage par type — override par serveur en SQLite (`notification_channels`, configuré via `/notify set`), sinon la variable d'environnement correspondante. Un type sans salon est simplement ignoré (log en `debug`). -- **Webhooks Gitea** : serveur HTTP natif (`WEBHOOK_ENABLED=true`). Vérifie la signature **HMAC-SHA256** (`x-gitea-signature`) en temps constant, rejette les corps > 1 Mo et les JSON invalides, déduplique les redeliveries via `webhook_deliveries`, puis publie les embeds via le service de notifications : `issues` → issues, `pull_request` → PR, `push` → commits, `create`/`delete` → références, `release` → releases. -- **Sondages** (`src/services/polls/poll-service.js`) : un vote par membre et par sondage (modifiable, un clic change le vote), message rafraîchi à chaque vote, et un ordonnanceur ferme automatiquement les sondages arrivés à échéance (vérification toutes les 30 s) même après un redémarrage. -- **Statuts du bot** (`src/services/status/bot-status-service.js`) : la présence affichée sous le nom du bot est une **liste enregistrée en base** (`bot_statuses`), éditable à chaud avec `/status` (ajout, retrait, pause, rythme). La rotation repart du premier statut activé à chaque cycle et le rythme est relu à chaque tour, donc `/status interval` s'applique sans redémarrer le bot. Liste vide → ligne par défaut « les commandes avec /help » plutôt qu'un statut figé. -- **Salons vocaux** (`src/events/voice-state-update.js`) : entrer dans **l'un des salons déclencheurs** crée un salon temporaire en bas de la catégorie de ce déclencheur et y déplace le membre (ou le renvoie dans celui qu'il possède déjà pour ce déclencheur) ; dès que le dernier membre part, le salon est supprimé après un court délai de grâce (`VOICE_EMPTY_GRACE_MS`, 5 s par défaut) qui laisse le temps de changer de salon sans perdre le sien. La suppression n'oublie la ligne en base que lorsque le salon a réellement disparu : une erreur d'API laisse le salon enregistré pour être réessayé. `sweepVoiceChannels()` oublie les salons disparus et supprime les vides — au démarrage, puis toutes les minutes via `startVoiceJanitor()`, ce qui garantit qu'un salon généré ne survit pas vide après un événement manqué ou un échec d'API. - -## 7. Architecture - -Détails complets : [`docs/architecture.md`](docs/architecture.md). - -```text -src/ -├── index.js # Point d'entrée : env, DB, client, loaders, webhooks, shutdown propre -├── config/ # env.js (lecture/validation .env) · constants.js (couleurs, niveaux, catégories) -├── core/ # client.js · command-loader.js · event-loader.js -│ # permissions.js (niveaux + hiérarchie) · logger.js · errors.js -├── commands// # fws, gitea, tickets, moderation, community, general -├── events/ # interaction-create (commandes, boutons, modales), ready, member add/remove, -│ # voice state (salons vocaux), errors, shard -├── services/ -│ ├── gitea/ # gitea-client.js (REST + retry) · gitea-embeds.js · gitea-modals.js · pending-actions.js -│ ├── members/ # member-service.js (accueil, rôle initial, départs) -│ ├── moderation/ # moderation-service.js (hiérarchie, sanctions, journal) -│ ├── notifications/ # notification-service.js (routage) · gitea-notifications.js (mapping webhooks) -│ ├── polls/ # poll-service.js (création, votes, clôture, ordonnanceur) -│ ├── status/ # bot-status-service.js (statuts du bot, validation, rotation) -│ ├── tickets/ # ticket-service.js (salons privés, cycle de vie) -│ └── voice/ # voice-service.js (déclencheurs multiples, salons temporaires, panneau) -├── database/ # index.js (connexion + migrations SQL) · migrations/ · repositories/ -├── webhooks/ # server.js (node:http) · gitea-webhook.js (signature + dispatch) -├── ui/ # embeds.js (identité visuelle) · buttons.js (liens, tickets, sondages) -└── utils/ # retry.js (backoff exponentiel) · cooldown.js -``` - -Chargement automatique : toute commande dans `src/commands/**` et tout événement dans `src/events/*` sont pris en compte au démarrage. - -**Contrat d'une commande** (`access` vérifié dans `interaction-create.js`, une `UserFacingError` est affichée telle quelle, toute autre erreur est loggée et remplacée par un message générique) : - -```js -export const access = ACCESS_LEVELS.STAFF; // niveau minimum -export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optionnel, par sous-commande -export const data = new SlashCommandBuilder() /* ... */; -export async function execute(interaction) {} -``` - -**Intents utilisés** : `Guilds`, `GuildMembers` *(privilégié — à activer dans le portail)*, `GuildModeration`, `GuildMessages`, `GuildVoiceStates`. `MessageContent` n'est volontairement pas demandé. - -### Ton et vocabulaire des messages - -Tous les textes visibles dans Discord suivent les mêmes règles, rappelées en tête de `src/ui/embeds.js` (source unique de vérité) : - -- **Tutoiement**, phrases courtes, voix active ; jamais de reproche, d'ironie ni de majuscules hurlantes. -- Le **titre** annonce le résultat, la **description** dit quoi faire ensuite ; un seul emoji par titre, jamais décoratif dans le corps. -- **Aucun accord genré** sur une personne : « tu es propriétaire », « cette personne », « l'équipe », « ce membre » — pas de « il / elle », de « cher / chère », ni d'écriture inclusive à points. -- Une **erreur** explique la cause, rappelle la règle et propose la sortie de secours ; un succès remercie et précise la suite (`/ban` renvoie vers `/mod logs`, `/ticket create` rappelle que la personne propriétaire peut fermer). -- Titres partagés : `✅ C'est fait`, `❌ Oups`, `⚠️ Attention`, `💡 Bon à savoir` (`TONE` dans `src/ui/embeds.js`). Listes toujours préfixées de `•` (`bullets()`), dernière ligne de conseil ajoutée par `withHint()`. -- Même vocabulaire partout : **équipe** (staff), **membre**, **salon**, **ticket**, **motif** (jamais « raison » comme libellé), **déclencheur** vocal. - -## 8. Base de données (SQLite) - -- Moteur : `node:sqlite` (`DatabaseSync`), mode **WAL**, foreign keys activées. -- Migrations : fichiers SQL numérotés dans `src/database/migrations/`, appliqués en transaction et tracés dans `schema_migrations` (`npm run db:init`). -- Tables : `guild_settings` (paramètres par serveur), `notification_channels`, `ticket_categories`, `tickets` (unicité ticket ouvert/auteur/catégorie), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (déclencheurs vocaux et leur catégorie), `voice_channels` (propriétaire, verrouillage, limite), `bot_statuses` (statuts du bot, globaux — unicité du texte), `event_logs`, `webhook_deliveries`. -- Accès données : un repository par domaine (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-repository.js`) — les requêtes SQL ne sortent jamais de cette couche. -- Les migrations `002-ticket-and-poll-details.sql` (traçabilité de prise en charge `claimed_at` et de fermeture `close_reason`), `003-voice-channels.sql` (salons vocaux temporaires), `004-voice-triggers.sql` (plusieurs déclencheurs vocaux par serveur) et `005-bot-statuses.sql` (statuts du bot édités en commande) complètent le schéma initial. -- La base contient des données réelles : elle est **exclue de git** (`.gitignore`) et doit être sauvegardée (`BACKUP_DIR`). - -## 9. Logs - -- Format **JSON**, une ligne par entrée, fichier par jour : `logs/AAAA-MM-JJ.log` + console. -- Niveaux filtrés par `LOG_LEVEL` ; erreurs et warnings sur stderr. -- **Masquage des secrets** : token Discord, token Gitea et secret webhook sont remplacés par `***` dans chaque ligne loggée. -- Rétention fonctionnelle : `LOG_RETENTION_DAYS` (purge des `event_logs`). - -## 10. Scripts npm - -| Script | Rôle | -| --- | --- | -| `npm start` | Démarre le bot (`node src/index.js`) | -| `npm run dev` | Démarre avec rechargement automatique (`node --watch`) | -| `npm run deploy:commands` | Enregistre les commandes slash sur le serveur `DISCORD_GUILD_ID` (à relancer après ajout/modification d'une commande) | -| `npm run db:init` | Crée la base SQLite et applique les migrations | -| `npm run lint` / `npm run lint:fix` | ESLint (vérifier / corriger) | -| `npm run format` / `npm run format:check` | Prettier (formater / vérifier) | -| `npm run changelog` | Regénère `CHANGELOG.md` depuis les commits Conventional Commits (voir §12) | -| `npm run changelog:check` | Vérifie que `CHANGELOG.md` est à jour (code de sortie 1 sinon) | -| `npm test` | Tests unitaires `node:test` : `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs` | - -En cas de souci : `npm run deploy:commands` après chaque changement de commandes, vérifie que l'intent **Server Members** est activé, et que le bot a bien les permissions listées en 3.2 sur ses salons cibles. - -## 11. Sécurité - -- Permissions vérifiées **côté serveur** (niveau FWS + permissions Discord + hiérarchie des rôles) : jamais confiance au client. -- Aucune action possible sur un rôle/membre positionné au-dessus de l'auteur. -- Secrets jamais committés (`.env` ignoré) ni loggés en clair (masquage automatique). -- Webhooks Gitea : signature HMAC-SHA256 obligatoire, comparaison à temps constant, corps limité à 1 Mo, anti-doublon sur l'ID de delivery. -- Tokens à moindre privilège ; rate limits respectés (timeout + retry contrôlé sur erreurs transitoires uniquement). -- Entrées utilisateur validées (`setMinValue`/`setMaxValue`/`setMaxLength` sur toutes les options). - -## 12. Versionnage et releases - -- **SemVer** (`MAJEUR.MINEUR.PATCH`) : `MAJEUR` = changement incompatible, `MINEUR` = fonctionnalité rétrocompatible, `PATCH` = correction. Version courante : voir `version` dans [`package.json`](package.json) (avant `1.0.0`, tout peut changer — un changement incompatible ne fait monter que le `MINEUR`, conformément au §4 de SemVer). -- **`CHANGELOG.md` est généré** depuis les commits Conventional Commits : `npm run changelog` (les `feat:` alimentent *Features*, les `fix:` *Bug Fixes*, les autres types *Other changes*). Le script affiche aussi la **version suivante suggérée** ; `npm run changelog:check` échoue si le fichier n'est pas à jour. -- Les tags sont repris automatiquement : chaque tag `vX.Y.Z` trouvé dans l'historique ouvre sa propre section dans le changelog, les commits plus récents restent sous `[Unreleased]`. -- La génération fait partie de la définition de « terminé » : le fichier ne se modifie pas à la main. - -## 13. Contribution - -Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de l'organisation](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md). Résumé appliqué ici : - -### Commits - -- Messages en **anglais**, format **Conventional Commits** : `(): `. -- Types autorisés : `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`. -- Titre court et impératif ; un **corps** est ajouté seulement pour expliquer le *pourquoi* (contexte, décision, compromis). - -### Branches et pull requests - -1. Créer une branche `type/description` **depuis `main`** (ex. `feat/ticket-service`, `fix/voice-cleanup`). -2. Commiter selon les conventions ci-dessus. -3. Ouvrir une **pull request** avec un titre et une description clairs, en référençant l'issue (`Fixes #123`). -4. **Au moins un reviewer** valide ; les tests doivent passer. -5. Merger en **squash** : 1 PR = 1 commit propre sur `main`. - -### Organisation du travail - -- Tableau **Kanban** du projet : *Backlog / À faire*, *En cours*, *En revue*, *Terminé*. Une carte = une unité de travail = une branche + une PR ; une carte ne passe en *Terminé* qu'une fois la PR mergée. -- Toute anomalie ou demande passe par une **issue** (titre clair + description précise) avec un label recommandé : `bug`, `enhancement`, `question`, `good first issue`, `help wanted`. Les modèles sont fournis dans [`.gitea/ISSUE_TEMPLATE/`](.gitea/ISSUE_TEMPLATE) et [`.gitea/PULL_REQUEST_TEMPLATE.md`](.gitea/PULL_REQUEST_TEMPLATE.md). -- Un bug se décrit avec les **étapes de reproduction**, le **comportement attendu** vs **observé**, l'**environnement** et les **logs** utiles. - -### Code et documentation - -- Fichiers en **kebab-case**, identifiants **en anglais**, commentaires **en anglais** expliquant le *pourquoi* (le non-évident : compromis, cas limites, références). -- Vérifier la stack et les dépendances déjà présentes avant d'en ajouter une nouvelle (une seule dépendance runtime ici : `discord.js`). -- Avant de proposer : `npm run lint`, `npm run format:check`, `npm test` et `npm run changelog` doivent passer. -- Documentation **bilingue** : [`README.md`](README.md) (FR) et [`README.en.md`](README.en.md) (EN) restent synchronisés ; un test le vérifie. -- Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md), à mettre à jour avec les conventions. - -## 14. Checklist de mise en production - -- [ ] Renommer le dépôt en `fws-discordbot` côté Gitea (convention `fws-*` de l'organisation) -- [ ] Créer le tableau Kanban (*Backlog / À faire*, *En cours*, *En revue*, *Terminé*) -- [ ] Renseigner les statuts du bot (`/status add`, `/status interval`) — la rotation est enregistrée en base -- [ ] Enregistrer les commandes slash sur le serveur FWS (`npm run deploy:commands`) -- [ ] Créer et configurer les rôles Owner, Dev, Staff, User (IDs dans `.env`) -- [ ] Définir les salons : bienvenue, tickets, notifications, logs -- [ ] Configurer chaque salon vocal déclencheur (`/voice setup`) et vérifier création/suppression automatique -- [ ] Activer l'intent **Server Members** dans le portail développeur -- [ ] Configurer Gitea : token à moindre privilège + webhook avec secret -- [ ] Protéger et sauvegarder la base SQLite -- [ ] Tester les parcours critiques : ticket de bout en bout, avertissement, sondage, webhook Gitea -- [ ] Tester les limites API et les chemins d'erreur -- [ ] Vérifier les embeds sur ordinateur et mobile -- [ ] Renseigner les liens officiels et les captures (`assets/screenshots/`) -- [ ] Publier la première version `0.1.0` (tag `v0.1.0` puis `npm run changelog`) - -## 15. Ressources - -- Organisation FWS : `[lien à ajouter]` -- Serveur Discord FWS : `[lien à ajouter]` -- Dépôt FWS Arch : `[lien à ajouter]` -- Instance Gitea : `[lien à ajouter]` -- Documentation FWS : `[lien à ajouter]` -- Documentation technique : [`docs/architecture.md`](docs/architecture.md) -- Conventions de l'organisation : [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md) -- Journal des modifications : [`CHANGELOG.md`](CHANGELOG.md) *(généré)* -- Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md) -- Version anglaise de ce document : [`README.en.md`](README.en.md) +# FWS-Bot + +> Bot Discord de l'organisation open source **FWS** — assistance communautaire, tickets, modération, intégration Gitea et statistiques pour **FWS Arch** (fork d'Arch Linux avec surcouche conviviale). + +🌍 **Français** · [English version](README.en.md) + +Statut : **fonctionnel**. Les 19 commandes sont implémentées (assistance, tickets privés, modération, Gitea, sondages, statistiques, statuts du bot, gestionnaire de salons vocaux), tout comme l'accueil des membres et la diffusion des webhooks Gitea. + +Projet conforme aux [conventions de l'organisation FWS](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md) : commits en anglais au format Conventional Commits, branche `type/description`, PR relue puis mergée en squash, SemVer et `CHANGELOG.md` généré depuis les commits. + +--- + +## 1. Stack technique + +Choix assumés : **une seule dépendance runtime** (discord.js), aucun module natif à compiler, outil de test intégré à Node. + +| Techno | Version | Rôle | +| --- | --- | --- | +| **Node.js** | ≥ 22.13.0 (ESM) | Runtime. Requis pour `node:sqlite`, `process.loadEnvFile`, `--watch` | +| **discord.js** | ^14.21.0 | API Discord : commandes slash, embeds, boutons, intents | +| **`node:sqlite`** | module natif | Base SQLite (WAL, foreign keys) — pas de `better-sqlite3` ni compilation | +| **`fetch` natif** | — | Client REST Gitea (avec `AbortSignal.timeout`) | +| **`node:http`** | — | Serveur de webhooks Gitea (sans Express) | +| **`node:crypto`** | — | Signature HMAC-SHA256 des webhooks | +| **`node:test`** | — | Tests unitaires intégrés (`node --test`) | +| **ESLint** | ^9.30.0 (flat config) | Lint | +| **Prettier** | ^3.6.2 | Format | + +## 2. Prérequis + +- Node.js ≥ 22.13 (`node -v` pour vérifier) et npm +- Une application Discord (gratuite) avec un token de bot +- (Optionnel) une instance Gitea pour les issues/PR et les webhooks + +## 3. Démarrage rapide avec un token de test + +### 3.1 Créer l'application Discord + +1. Ouvre le [Discord Developer Portal](https://discord.com/developers/applications) → **New Application**. +2. Onglet **Bot** → **Reset Token** → copie le token : c'est ton `DISCORD_TOKEN` (ne le partage jamais, ne le committe jamais). +3. Toujours dans **Bot** → **Privileged Gateway Intents** → active **Server Members Intent** (requis pour l'accueil des nouveaux membres ; `Message Content` n'est pas nécessaire). +4. Onglet **General Information** → copie l'**Application ID** : c'est ton `DISCORD_CLIENT_ID`. + +### 3.2 Inviter le bot sur un serveur de test + +Remplace `CLIENT_ID` par ton Application ID : + +```text +https://discord.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot+applications.commands&permissions=1099812662294 +``` + +Cette URL pré-coche les permissions utilisées par les commandes : Voir les salons, Envoyer des messages, Gérer les messages, Intégrer des liens, Lire l'historique, Expulser, Bannir, Gérer les rôles, Modérer les membres (timeout), ainsi que celles des salons vocaux : Gérer les salons, Se connecter, Parler, Rendre muet, Rendre sourd, Déplacer les membres. Tu peux aussi passer par **OAuth2 → URL Generator** avec les scopes `bot` + `applications.commands`. + +Crée (ou utilise) un serveur de test dont tu es propriétaire : c'est lui qui donne le niveau **Owner** au bot. + +### 3.3 Récupérer les IDs Discord + +Sur Discord : **Paramètres → Avancés → Mode développeur** activé, puis clic droit sur un serveur / salon / rôle → **Copier l'identifiant**. + +| Variable | Où le trouver | +| --- | --- | +| `DISCORD_GUILD_ID` | Clic droit sur le serveur de test | +| `ROLE_OWNER_ID`, `ROLE_DEV_ID`, `ROLE_STAFF_ID`, `ROLE_MEMBER_ID` | Paramètres du serveur → Rôles (crée-les d'abord) | +| `CHANNEL_WELCOME_ID`, `CHANNEL_LOGS_ID`, etc. | Clic droit sur chaque salon | + +> Si les rôles ne sont pas configurés, tout le monde est considéré **User** (sauf le propriétaire du serveur = Owner). + +### 3.4 Lancer le bot + +```bash +# 1. Dépendances +npm install + +# 2. Configuration : copie .env.example vers .env puis remplis-le +# Minimum requis : DISCORD_TOKEN, DISCORD_CLIENT_ID, DISCORD_GUILD_ID +cp .env.example .env + +# 3. Créer la base SQLite et appliquer les migrations +npm run db:init + +# 4. Enregistrer les commandes slash sur le serveur (instantané, par guild) +npm run deploy:commands + +# 5. Démarrer avec rechargement automatique +npm run dev +``` + +Dans les logs tu dois voir `Connected as `. Tape `/help` sur le serveur : tu dois voir la liste des commandes accessibles selon ton rôle. + +Sans `.env`, le bot refuse de démarrer (`assertRequiredEnv` vérifie token, client ID et guild ID). + +## 4. Configuration — toutes les variables (`.env`) + +Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre parenthèses. + +### Runtime + +| Variable | Défaut | Description | +| --- | --- | --- | +| `NODE_ENV` | `development` | `development` \| `production` \| `test` | +| `LOG_LEVEL` | `info` | `debug` \| `info` \| `warn` \| `error` | +| `LOG_DIR` | `./logs` | Dossier des logs JSON journaliers | +| `LOG_RETENTION_DAYS` | `30` | Durée de conservation (purge des `event_logs`) | +| `VOICE_EMPTY_GRACE_MS` | `5000` | Délai avant qu'un salon vocal généré devenu vide soit supprimé (`0` = immédiat) | +| `BOT_STATUS_INTERVAL_SECONDS` | `60` | Rythme par défaut de la rotation des statuts du bot (modifiable par `/status interval`) | + +### Application Discord + +| Variable | Description | +| --- | --- | +| `DISCORD_TOKEN` | **Requis.** Token du bot (Developer Portal → Bot) | +| `DISCORD_CLIENT_ID` | **Requis.** Application ID | +| `DISCORD_GUILD_ID` | **Requis.** Serveur d'enregistrement des commandes slash | + +### Rôles FWS (IDs de rôles Discord) + +| Variable | Niveau correspondant | +| --- | --- | +| `ROLE_OWNER_ID` | Owner — accès complet | +| `ROLE_DEV_ID` | Dev — configuration FWS Arch, écritures Gitea | +| `ROLE_STAFF_ID` | Staff — modération, support, tickets | +| `ROLE_MEMBER_ID` | Rôle initial attribué aux nouveaux membres | + +### Salons Discord (IDs) + +| Variable | Usage | +| --- | --- | +| `CHANNEL_WELCOME_ID` | Messages de bienvenue | +| `CHANNEL_RULES_ID` | Règlement (lien envoyé aux nouveaux) | +| `CHANNEL_ANNOUNCEMENTS_ID` | Annonces FWS | +| `CHANNEL_LOGS_ID` | Logs fonctionnels | +| `CHANNEL_MOD_LOGS_ID` | Logs de modération | +| `CHANNEL_TICKETS_LOGS_ID` | Journal d'ouverture/fermeture des tickets | +| `CHANNEL_NOTIF_ISSUES_ID` | Notifications issues | +| `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Notifications pull requests | +| `CHANNEL_NOTIF_COMMITS_ID` | Notifications commits | +| `CHANNEL_NOTIF_RELEASES_ID` | Notifications releases | +| `CHANNEL_NOTIF_ERRORS_ID` | Erreurs et incidents | +| `CATEGORY_TICKETS_ID` | Catégorie où sont créés les salons de tickets privés | +| `CHANNEL_VOICE_TRIGGER_ID` | Salon vocal déclencheur (repli : `/voice setup` gère une liste de déclencheurs) | +| `CATEGORY_VOICE_ID` | Catégorie d'accueil des salons vocaux créés (facultatif) | + +### Gitea + +| Variable | Défaut | Description | +| --- | --- | --- | +| `GITEA_URL` | — | URL de l'instance (sans `/` final) | +| `GITEA_TOKEN` | — | Token à moindre privilège (`read:repository`, `write:issue`). Jamais loggé | +| `GITEA_OWNER` | — | Propriétaire du dépôt (ex. `FWS`) | +| `GITEA_REPO` | — | Dépôt ciblé (ex. `FWS-Arch`) | +| `GITEA_TIMEOUT_MS` | `10000` | Timeout des requêtes | +| `GITEA_MAX_RETRIES` | `2` | Tentatives sur erreurs transitoires (429, 5xx, timeout) | + +### Webhooks Gitea + +| Variable | Défaut | Description | +| --- | --- | --- | +| `WEBHOOK_ENABLED` | `false` | Démarre le serveur HTTP de réception | +| `WEBHOOK_HOST` | `0.0.0.0` | Interface d'écoute | +| `WEBHOOK_PORT` | `3000` | Port d'écoute | +| `WEBHOOK_PATH` | `/webhooks/gitea` | Chemin à configurer dans Gitea | +| `GITEA_WEBHOOK_SECRET` | — | Secret partagé (HMAC-SHA256), défini dans Gitea → Webhooks | + +### SQLite et liens + +| Variable | Défaut | Description | +| --- | --- | --- | +| `DATABASE_PATH` | `./data/fws-bot.sqlite` | Fichier de base (exclu de git) | +| `BACKUP_DIR` | `./data/backups` | Dossier de sauvegarde | +| `FWS_WEBSITE_URL`, `FWS_DOCS_URL`, `FWS_DISCORD_INVITE_URL`, `FWS_ARCH_REPO_URL` | — | Liens officiels affichés par `/fws info` et `/fws links` (les boutons vides sont omis) | + +## 5. Commandes slash + +19 commandes sont enregistrées. Chaque commande a un **niveau d'accès FWS** vérifié côté serveur avant exécution, et les commandes de modération vérifient en plus les **permissions Discord** (`DefaultMemberPermissions`). + +### Niveaux d'accès + +Résolus depuis les rôles configurés dans `.env` (du plus haut au plus bas) : + +| Niveau | Qui | +| --- | --- | +| `OWNER` (3) | Rôle Owner, ou propriétaire du serveur | +| `DEV` (2) | Rôle Dev | +| `STAFF` (1) | Rôle Staff | +| `USER` (0) | Tous les membres | + +### Générales et FWS + +| Commande | Options | Accès | État | Description | +| --- | --- | --- | --- | --- | +| `/help` | — | User | ✅ | Liste les commandes accessibles selon ton rôle (réponse éphémère) | +| `/fws info` | — | User | ✅ | Présente FWS et FWS Arch (texte surchargeable via `guild_settings`) + liens officiels | +| `/fws links` | — | User | ✅ | Ressources : site, docs, dépôt, Gitea, Discord | +| `/fws version` | — | User | ✅ | Dernière release Gitea (tag, date, auteur) + bouton vers les notes | +| `/fws status` | — | User | ✅ | État des services : API Gitea, webhooks, SQLite, latence Discord, uptime | +| `/fws changelog` | `version` (optionnel) | User | ✅ | Notes de version (dernière par défaut, message clair si le tag n'existe pas) | +| `/status add` | `text` (128 car.), `type`, `url` | **Staff** + *Gérer le serveur* | ✅ | Ajoute un statut à la rotation ; le premier ajouté s'affiche tout de suite | +| `/status list` | — | **Staff** + *Gérer le serveur* | ✅ | Statuts enregistrés : numéro, type, état, rythme de rotation | +| `/status remove` · `enable` · `disable` | `id` | **Staff** + *Gérer le serveur* | ✅ | Retire un statut, le remet en rotation ou le met en pause | +| `/status interval` | `seconds` (5–86 400) | **Staff** + *Gérer le serveur* | ✅ | Rythme de la rotation, appliqué sans redémarrage | +| `/status clear` | — | **Staff** + *Gérer le serveur* | ✅ | Vide la liste et revient à la ligne par défaut | + +### Gitea — issues et pull requests + +| Commande | Options | Accès | État | Description | +| --- | --- | --- | --- | --- | +| `/issue create` | — (modale : titre + description) | User (configurable) | ✅ | Crée une issue Gitea et renvoie son lien | +| `/issue view` | `number` | User | ✅ | Titre, auteur, état, labels, lien d'une issue | +| `/issue list` | — | User | ✅ | Issues ouvertes (15 dernières) | +| `/pr create` | `head`, `base` + modale (titre, description) | **Dev** | ✅ | Crée une pull request Gitea | +| `/pr view` | `number` | User | ✅ | Titre, auteur, état, branches, lien d'une PR | +| `/pr list` | — | User | ✅ | PR ouvertes (15 dernières) | +| `/gitea activity` | — | User | ✅ | Derniers commits + issues et PR ouvertes | +| `/gitea release` | — | User | ✅ | Releases de FWS Arch (5 dernières) | + +> Le client Gitea (`src/services/gitea/gitea-client.js`) : REST avec token, timeout, retry exponentiel sur erreurs transitoires. Les formulaires (`/issue create`, `/pr create`) passent par une **modale** ; les options de branches y sont conservées en mémoire quelques minutes (`pending-actions.js`). Toute panne (token absent, 404, 5xx) devient un message éphémère explicite, jamais une erreur brute. + +### Tickets de support + +Les tickets sont des salons privés créés sous `CATEGORY_TICKETS_ID`. Un seul ticket ouvert par membre et par catégorie (contrainte SQL). + +| Commande | Options | Accès | État | Description | +| --- | --- | --- | --- | --- | +| `/ticket create` | `category` (obligatoire) | User (selon la catégorie) | ✅ | Crée un salon privé sous `CATEGORY_TICKETS_ID` | +| `/ticket close` | `reason` (optionnel, 500 car.) | Auteur, Staff | ✅ | Ferme, journalise puis supprime le salon (10 s) — aussi via le bouton **Fermer** | +| `/ticket claim` | — | **Staff** | ✅ | Prend le ticket en charge (bouton **Prendre en charge**) | +| `/ticket add` | `user` | **Staff** | ✅ | Ajoute un participant au salon privé | + +Catégories disponibles et qui y a accès : + +| Catégorie | Visible par | +| --- | --- | +| Aide et support | Staff, Owner | +| Bug | Staff, Dev, Owner | +| Question de développement | Dev, Owner | +| Signalement | Staff, Owner | +| Demande interne | Owner | + +### Salons vocaux temporaires + +Un serveur peut déclarer **autant de salons déclencheurs que nécessaire** — un par thème (`Dev`, `SIO`, …) — chacun avec sa propre catégorie d'accueil (`/voice setup`) : rejoindre un déclencheur crée un salon vocal privé **en bas de la catégorie de ce déclencheur**, y déplace le membre et lui en donne la propriété. Le salon se gère ensuite depuis le **panneau de contrôle** publié dans son chat (boutons *Renommer*, *Limiter*, *Verrouiller*, *Réclamer*, *Supprimer* et menus *Autoriser*, *Exclure*, *Transférer*) ou avec `/voice`. Le nombre de salons simultanés est **illimité**, et un membre conserve un salon **par déclencheur** : rejoindre à nouveau le même déclencheur le renvoie simplement dans le salon qu'il possède déjà. + +Dès que **plus personne** ne reste dans un salon généré, il est supprimé : le délai (5 s par défaut) le laisse survivre à un passage rapide dans un autre salon — réglable par `VOICE_EMPTY_GRACE_MS`, `0` le supprime immédiatement. Un balayage automatique (au démarrage puis toutes les minutes) rattrape les cas où l'événement Discord a été manqué ou la suppression refusée, si bien qu'un salon généré ne peut pas rester vide : soit il est supprimé, soit la tentative est réessayée. + +| Commande | Options | Accès | Description | +| --- | --- | --- | --- | +| `/voice setup` | `trigger`, `label`, `category`, `template`, `limit`, `panel` | **Staff** | Ajoute (ou met à jour) un salon déclencheur ; sans `category`, celle du salon déclencheur est utilisée | +| `/voice config` · `/voice triggers list` | — | User · **Staff** | Déclencheurs déclarés : catégorie, modèle, limite, état et salons actifs | +| `/voice triggers disable` · `enable` | `trigger` | **Staff** | Désactive un déclencheur (sans perdre sa configuration, y entrer ne crée plus de salon) · le réactive | +| `/voice triggers remove` | `trigger` | **Staff** | Supprime un déclencheur déclaré dans Discord | +| `/voice panel` | `trigger` (défaut : tous) | **Staff** | Republie le panneau d'explication dans les salons déclencheurs | +| `/voice name` | `name` (100 car.) | Propriétaire | Renomme le salon | +| `/voice limit` | `limit` (0–99, 0 = illimité) | Propriétaire | Nombre de places | +| `/voice lock` · `/voice unlock` | — | Propriétaire | Refuse · autorise l'accès de tout le monde | +| `/voice permit` | `user` | Propriétaire | Autorise un membre à rejoindre le salon | +| `/voice reject` | `user` | Propriétaire | Interdit l'accès (et l'éjecte s'il y est déjà) | +| `/voice kick` | `user` | Propriétaire | Éjecte un membre du salon | +| `/voice transfer` | `user` | Propriétaire | Transfère la propriété (le nouveau doit être dans le salon) | +| `/voice claim` | — | Membre du salon | Récupère un salon dont le propriétaire est parti | +| `/voice delete` | `channel` (staff) | Propriétaire, Staff | Supprime immédiatement le salon | +| `/voice info` | `channel` (staff) | User | Propriétaire, état, limite, membres, ancienneté | + +> Modèle de nom : `{user}` est remplacé par le pseudo du membre (défaut `🔊 Salon de {user}`). Le staff peut toujours agir sur n'importe quel salon temporaire. Le propriétaire reçoit `Gérer le salon` + `Déplacer des membres` sur son seul salon. +> +> `CHANNEL_VOICE_TRIGGER_ID` / `CATEGORY_VOICE_ID` restent un **repli** : un serveur dont le `.env` déclare un déclencheur fonctionne sans `/voice setup`, mais ce déclencheur venu de l'environnement ne peut qu'être désactivé (`/voice triggers disable`), pas supprimé depuis Discord. Changer la catégorie d'un déclencheur ne déplace pas les salons déjà créés. + +### Modération + +Chaque commande vérifie le niveau FWS **et** la permission Discord correspondante. Le bot refuse d'agir sur un membre dont le plus haut rôle est égal ou supérieur à celui de l'auteur (`canActOn`), et n'agit jamais sur le propriétaire du serveur. + +| Commande | Options | Permission Discord | État | Description | +| --- | --- | --- | --- | --- | +| `/warn` | `user`, `reason` (obligatoires) | Modérer les membres | ✅ | Avertit, prévient le membre en MP et enregistre l'action | +| `/mute` | `user`, `minutes` (1–40320), `reason` | Modérer les membres | ✅ | Timeout temporaire (28 j max) + notification en MP | +| `/kick` | `user`, `reason` | Expulser | ✅ | Expulse du serveur et journalise l'action | +| `/ban` | `user`, `reason`, `delete_days` (0–7) | Bannir | ✅ | Bannit (même si le membre a déjà quitté), purge optionnelle des messages | +| `/clear` | `amount` (1–100) | Gérer les messages | ✅ | Supprime les N derniers messages (ceux de plus de 14 j sont ignorés) | +| `/mod logs` | `user` (filtre) | Modérer les membres | ✅ | Historique lu depuis `moderation_actions` (15 dernières, éphémère) | +| `/role set` | `user`, `role`, `action` (`add`/`remove`) | Gérer les rôles | ✅ | Attribue ou retire un rôle (double hiérarchie vérifiée) | +| `/notify set` | `type`, `channel` | Gérer le serveur | ✅ | Salon de notification propre à ce serveur (SQLite) | +| `/notify remove` | `type` | Gérer le serveur | ✅ | Revenir au salon par défaut (variables d'environnement) | +| `/notify list` | — | Gérer le serveur | ✅ | Configuration actuelle de chaque type | + +> Chaque action réussie est enregistrée dans `moderation_actions` **et** publiée dans `CHANNEL_MOD_LOGS_ID` (cible, modérateur, raison, durée). + +### Communauté et statistiques + +| Commande | Options | Accès | État | Description | +| --- | --- | --- | --- | --- | +| `/poll create` | `question`, `choices` (« ; » séparés, 2–10), `minutes` (1–10080) | **Staff** | ✅ | Sondage voté par boutons, résultats en direct | +| `/poll close` | `id` | **Staff** | ✅ | Clôture, affiche le résultat gagnant et fige le message | +| `/stats discord` | — | User | ✅ | Membres, salons, rôles, boosts, âge du serveur, latence | +| `/stats gitea` | — | User | ✅ | Commits récents, issues et PR ouvertes, dernière release | +| `/stats fws` | — | User | ✅ | Indicateurs locaux (tickets, sondages, modération) + version FWS Arch | +| `/fun coinflip` | — | User | ✅ | Pile ou face | +| `/fun dice` | `sides` (2–1000, 6 par défaut) | User | ✅ | Lancer de dé | +| `/fun 8ball` | `question` | User | ✅ | Boule magique (12 réponses) | +| `/fun choose` | `options` (« ; » séparés, 2–10) | User | ✅ | Choix aléatoire argumenté | + +Légende : ✅ fonctionnel · les erreurs attendues sont renvoyées en message éphémère (`UserFacingError`), les autres sont loggées et remplacées par un message générique. + +## 6. Automatisations + +- **Accueil** (`src/events/guild-member-add.js`) : attribution du rôle `ROLE_MEMBER_ID` (ignorée si le rôle est au-dessus de celui du bot), embed de bienvenue dans `CHANNEL_WELCOME_ID` avec renvoi vers `CHANNEL_RULES_ID`, et message privé contenant les liens officiels (silencieux si les MP sont fermés). +- **Départs** (`src/events/guild-member-remove.js`) : embed dans `CHANNEL_LOGS_ID` (repli sur `CHANNEL_MOD_LOGS_ID`) avec effectif, ancienneté et âge du compte. +- **Notifications** (`src/services/notifications/notification-service.js`) : routage par type — override par serveur en SQLite (`notification_channels`, configuré via `/notify set`), sinon la variable d'environnement correspondante. Un type sans salon est simplement ignoré (log en `debug`). +- **Webhooks Gitea** : serveur HTTP natif (`WEBHOOK_ENABLED=true`). Vérifie la signature **HMAC-SHA256** (`x-gitea-signature`) en temps constant, rejette les corps > 1 Mo et les JSON invalides, déduplique les redeliveries via `webhook_deliveries`, puis publie les embeds via le service de notifications : `issues` → issues, `pull_request` → PR, `push` → commits, `create`/`delete` → références, `release` → releases. +- **Sondages** (`src/services/polls/poll-service.js`) : un vote par membre et par sondage (modifiable, un clic change le vote), message rafraîchi à chaque vote, et un ordonnanceur ferme automatiquement les sondages arrivés à échéance (vérification toutes les 30 s) même après un redémarrage. +- **Statuts du bot** (`src/services/status/bot-status-service.js`) : la présence affichée sous le nom du bot est une **liste enregistrée en base** (`bot_statuses`), éditable à chaud avec `/status` (ajout, retrait, pause, rythme). La rotation repart du premier statut activé à chaque cycle et le rythme est relu à chaque tour, donc `/status interval` s'applique sans redémarrer le bot. Liste vide → ligne par défaut « les commandes avec /help » plutôt qu'un statut figé. +- **Salons vocaux** (`src/events/voice-state-update.js`) : entrer dans **l'un des salons déclencheurs** crée un salon temporaire en bas de la catégorie de ce déclencheur et y déplace le membre (ou le renvoie dans celui qu'il possède déjà pour ce déclencheur) ; dès que le dernier membre part, le salon est supprimé après un court délai de grâce (`VOICE_EMPTY_GRACE_MS`, 5 s par défaut) qui laisse le temps de changer de salon sans perdre le sien. La suppression n'oublie la ligne en base que lorsque le salon a réellement disparu : une erreur d'API laisse le salon enregistré pour être réessayé. `sweepVoiceChannels()` oublie les salons disparus et supprime les vides — au démarrage, puis toutes les minutes via `startVoiceJanitor()`, ce qui garantit qu'un salon généré ne survit pas vide après un événement manqué ou un échec d'API. + +## 7. Architecture + +Détails complets : [`docs/architecture.md`](docs/architecture.md). + +```text +src/ +├── index.js # Point d'entrée : env, DB, client, loaders, webhooks, shutdown propre +├── config/ # env.js (lecture/validation .env) · constants.js (couleurs, niveaux, catégories) +├── core/ # client.js · command-loader.js · event-loader.js +│ # permissions.js (niveaux + hiérarchie) · logger.js · errors.js +├── commands// # fws, gitea, tickets, moderation, community, general +├── events/ # interaction-create (commandes, boutons, modales), ready, member add/remove, +│ # voice state (salons vocaux), errors, shard +├── services/ +│ ├── gitea/ # gitea-client.js (REST + retry) · gitea-embeds.js · gitea-modals.js · pending-actions.js +│ ├── members/ # member-service.js (accueil, rôle initial, départs) +│ ├── moderation/ # moderation-service.js (hiérarchie, sanctions, journal) +│ ├── notifications/ # notification-service.js (routage) · gitea-notifications.js (mapping webhooks) +│ ├── polls/ # poll-service.js (création, votes, clôture, ordonnanceur) +│ ├── status/ # bot-status-service.js (statuts du bot, validation, rotation) +│ ├── tickets/ # ticket-service.js (salons privés, cycle de vie) +│ └── voice/ # voice-service.js (déclencheurs multiples, salons temporaires, panneau) +├── database/ # index.js (connexion + migrations SQL) · migrations/ · repositories/ +├── webhooks/ # server.js (node:http) · gitea-webhook.js (signature + dispatch) +├── ui/ # embeds.js (identité visuelle) · buttons.js (liens, tickets, sondages) +└── utils/ # retry.js (backoff exponentiel) · cooldown.js +``` + +Chargement automatique : toute commande dans `src/commands/**` et tout événement dans `src/events/*` sont pris en compte au démarrage. + +**Contrat d'une commande** (`access` vérifié dans `interaction-create.js`, une `UserFacingError` est affichée telle quelle, toute autre erreur est loggée et remplacée par un message générique) : + +```js +export const access = ACCESS_LEVELS.STAFF; // niveau minimum +export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optionnel, par sous-commande +export const data = new SlashCommandBuilder() /* ... */; +export async function execute(interaction) {} +``` + +**Intents utilisés** : `Guilds`, `GuildMembers` *(privilégié — à activer dans le portail)*, `GuildModeration`, `GuildMessages`, `GuildVoiceStates`. `MessageContent` n'est volontairement pas demandé. + +### Ton et vocabulaire des messages + +Tous les textes visibles dans Discord suivent les mêmes règles, rappelées en tête de `src/ui/embeds.js` (source unique de vérité) : + +- **Tutoiement**, phrases courtes, voix active ; jamais de reproche, d'ironie ni de majuscules hurlantes. +- Le **titre** annonce le résultat, la **description** dit quoi faire ensuite ; un seul emoji par titre, jamais décoratif dans le corps. +- **Aucun accord genré** sur une personne : « tu es propriétaire », « cette personne », « l'équipe », « ce membre » — pas de « il / elle », de « cher / chère », ni d'écriture inclusive à points. +- Une **erreur** explique la cause, rappelle la règle et propose la sortie de secours ; un succès remercie et précise la suite (`/ban` renvoie vers `/mod logs`, `/ticket create` rappelle que la personne propriétaire peut fermer). +- Titres partagés : `✅ C'est fait`, `❌ Oups`, `⚠️ Attention`, `💡 Bon à savoir` (`TONE` dans `src/ui/embeds.js`). Listes toujours préfixées de `•` (`bullets()`), dernière ligne de conseil ajoutée par `withHint()`. +- Même vocabulaire partout : **équipe** (staff), **membre**, **salon**, **ticket**, **motif** (jamais « raison » comme libellé), **déclencheur** vocal. + +## 8. Base de données (SQLite) + +- Moteur : `node:sqlite` (`DatabaseSync`), mode **WAL**, foreign keys activées. +- Migrations : fichiers SQL numérotés dans `src/database/migrations/`, appliqués en transaction et tracés dans `schema_migrations` (`npm run db:init`). +- Tables : `guild_settings` (paramètres par serveur), `notification_channels`, `ticket_categories`, `tickets` (unicité ticket ouvert/auteur/catégorie), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (déclencheurs vocaux et leur catégorie), `voice_channels` (propriétaire, verrouillage, limite), `bot_statuses` (statuts du bot, globaux — unicité du texte), `event_logs`, `webhook_deliveries`. +- Accès données : un repository par domaine (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-repository.js`) — les requêtes SQL ne sortent jamais de cette couche. +- Les migrations `002-ticket-and-poll-details.sql` (traçabilité de prise en charge `claimed_at` et de fermeture `close_reason`), `003-voice-channels.sql` (salons vocaux temporaires), `004-voice-triggers.sql` (plusieurs déclencheurs vocaux par serveur) et `005-bot-statuses.sql` (statuts du bot édités en commande) complètent le schéma initial. +- La base contient des données réelles : elle est **exclue de git** (`.gitignore`) et doit être sauvegardée (`BACKUP_DIR`). + +## 9. Logs + +- Format **JSON**, une ligne par entrée, fichier par jour : `logs/AAAA-MM-JJ.log` + console. +- Niveaux filtrés par `LOG_LEVEL` ; erreurs et warnings sur stderr. +- **Masquage des secrets** : token Discord, token Gitea et secret webhook sont remplacés par `***` dans chaque ligne loggée. +- Rétention fonctionnelle : `LOG_RETENTION_DAYS` (purge des `event_logs`). + +## 10. Scripts npm + +| Script | Rôle | +| --- | --- | +| `npm start` | Démarre le bot (`node src/index.js`) | +| `npm run dev` | Démarre avec rechargement automatique (`node --watch`) | +| `npm run deploy:commands` | Enregistre les commandes slash sur le serveur `DISCORD_GUILD_ID` (à relancer après ajout/modification d'une commande) | +| `npm run db:init` | Crée la base SQLite et applique les migrations | +| `npm run lint` / `npm run lint:fix` | ESLint (vérifier / corriger) | +| `npm run format` / `npm run format:check` | Prettier (formater / vérifier) | +| `npm run changelog` | Regénère `CHANGELOG.md` depuis les commits Conventional Commits (voir §12) | +| `npm run changelog:check` | Vérifie que `CHANGELOG.md` est à jour (code de sortie 1 sinon) | +| `npm test` | Tests unitaires `node:test` : `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs` | + +En cas de souci : `npm run deploy:commands` après chaque changement de commandes, vérifie que l'intent **Server Members** est activé, et que le bot a bien les permissions listées en 3.2 sur ses salons cibles. + +## 11. Sécurité + +- Permissions vérifiées **côté serveur** (niveau FWS + permissions Discord + hiérarchie des rôles) : jamais confiance au client. +- Aucune action possible sur un rôle/membre positionné au-dessus de l'auteur. +- Secrets jamais committés (`.env` ignoré) ni loggés en clair (masquage automatique). +- Webhooks Gitea : signature HMAC-SHA256 obligatoire, comparaison à temps constant, corps limité à 1 Mo, anti-doublon sur l'ID de delivery. +- Tokens à moindre privilège ; rate limits respectés (timeout + retry contrôlé sur erreurs transitoires uniquement). +- Entrées utilisateur validées (`setMinValue`/`setMaxValue`/`setMaxLength` sur toutes les options). + +## 12. Versionnage et releases + +- **SemVer** (`MAJEUR.MINEUR.PATCH`) : `MAJEUR` = changement incompatible, `MINEUR` = fonctionnalité rétrocompatible, `PATCH` = correction. Version courante : voir `version` dans [`package.json`](package.json) (avant `1.0.0`, tout peut changer — un changement incompatible ne fait monter que le `MINEUR`, conformément au §4 de SemVer). +- **`CHANGELOG.md` est généré** depuis les commits Conventional Commits : `npm run changelog` (les `feat:` alimentent *Features*, les `fix:` *Bug Fixes*, les autres types *Other changes*). Le script affiche aussi la **version suivante suggérée** ; `npm run changelog:check` échoue si le fichier n'est pas à jour. +- Les tags sont repris automatiquement : chaque tag `vX.Y.Z` trouvé dans l'historique ouvre sa propre section dans le changelog, les commits plus récents restent sous `[Unreleased]`. +- La génération fait partie de la définition de « terminé » : le fichier ne se modifie pas à la main. + +## 13. Contribution + +Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de l'organisation](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md). Résumé appliqué ici : + +### Commits + +- Messages en **anglais**, format **Conventional Commits** : `(): `. +- Types autorisés : `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`. +- Titre court et impératif ; un **corps** est ajouté seulement pour expliquer le *pourquoi* (contexte, décision, compromis). + +### Branches et pull requests + +1. Créer une branche `type/description` **depuis `main`** (ex. `feat/ticket-service`, `fix/voice-cleanup`). +2. Commiter selon les conventions ci-dessus. +3. Ouvrir une **pull request** avec un titre et une description clairs, en référençant l'issue (`Fixes #123`). +4. **Au moins un reviewer** valide ; les tests doivent passer. +5. Merger en **squash** : 1 PR = 1 commit propre sur `main`. + +### Organisation du travail + +- Tableau **Kanban** du projet : *Backlog / À faire*, *En cours*, *En revue*, *Terminé*. Une carte = une unité de travail = une branche + une PR ; une carte ne passe en *Terminé* qu'une fois la PR mergée. +- Toute anomalie ou demande passe par une **issue** (titre clair + description précise) avec un label recommandé : `bug`, `enhancement`, `question`, `good first issue`, `help wanted`. Les modèles sont fournis dans [`.gitea/ISSUE_TEMPLATE/`](.gitea/ISSUE_TEMPLATE) et [`.gitea/PULL_REQUEST_TEMPLATE.md`](.gitea/PULL_REQUEST_TEMPLATE.md). +- Un bug se décrit avec les **étapes de reproduction**, le **comportement attendu** vs **observé**, l'**environnement** et les **logs** utiles. + +### Code et documentation + +- Fichiers en **kebab-case**, identifiants **en anglais**, commentaires **en anglais** expliquant le *pourquoi* (le non-évident : compromis, cas limites, références). +- Vérifier la stack et les dépendances déjà présentes avant d'en ajouter une nouvelle (une seule dépendance runtime ici : `discord.js`). +- Avant de proposer : `npm run lint`, `npm run format:check`, `npm test` et `npm run changelog` doivent passer. +- Documentation **bilingue** : [`README.md`](README.md) (FR) et [`README.en.md`](README.en.md) (EN) restent synchronisés ; un test le vérifie. +- Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md), à mettre à jour avec les conventions. + +## 14. Checklist de mise en production + +- [ ] Renommer le dépôt en `fws-discordbot` côté Gitea (convention `fws-*` de l'organisation) +- [ ] Créer le tableau Kanban (*Backlog / À faire*, *En cours*, *En revue*, *Terminé*) +- [ ] Renseigner les statuts du bot (`/status add`, `/status interval`) — la rotation est enregistrée en base +- [ ] Enregistrer les commandes slash sur le serveur FWS (`npm run deploy:commands`) +- [ ] Créer et configurer les rôles Owner, Dev, Staff, User (IDs dans `.env`) +- [ ] Définir les salons : bienvenue, tickets, notifications, logs +- [ ] Configurer chaque salon vocal déclencheur (`/voice setup`) et vérifier création/suppression automatique +- [ ] Activer l'intent **Server Members** dans le portail développeur +- [ ] Configurer Gitea : token à moindre privilège + webhook avec secret +- [ ] Protéger et sauvegarder la base SQLite +- [ ] Tester les parcours critiques : ticket de bout en bout, avertissement, sondage, webhook Gitea +- [ ] Tester les limites API et les chemins d'erreur +- [ ] Vérifier les embeds sur ordinateur et mobile +- [ ] Renseigner les liens officiels et les captures (`assets/screenshots/`) +- [ ] Publier la première version `0.1.0` (tag `v0.1.0` puis `npm run changelog`) + +## 15. Ressources + +- Organisation FWS : `[lien à ajouter]` +- Serveur Discord FWS : `[lien à ajouter]` +- Dépôt FWS Arch : `[lien à ajouter]` +- Instance Gitea : `[lien à ajouter]` +- Documentation FWS : `[lien à ajouter]` +- Documentation technique : [`docs/architecture.md`](docs/architecture.md) +- Conventions de l'organisation : [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md) +- Journal des modifications : [`CHANGELOG.md`](CHANGELOG.md) *(généré)* +- Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md) +- Version anglaise de ce document : [`README.en.md`](README.en.md) diff --git a/docs/architecture.md b/docs/architecture.md index fada2c7..bb48862 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,88 +1,88 @@ -# Architecture — FWS-Bot - -Stack : **Node.js ≥ 22.13** (JavaScript ESM), **discord.js v14**, **SQLite** via le module natif `node:sqlite` (aucune dépendance native à compiler). - -## Arborescence - -```text -fws-discordbot/ -├── .env.example # Modèle de configuration (sans secret) -├── assets/screenshots/ # Captures référencées dans la documentation -├── data/ # Base SQLite et sauvegardes (ignoré par git) -├── docs/ # Documentation technique -├── logs/ # Logs techniques journaliers (ignoré par git) -├── scripts/ -│ ├── deploy-commands.js # Enregistre les commandes slash sur le serveur -│ └── init-database.js # Crée la base et applique les migrations -├── src/ -│ ├── index.js # Point d'entrée -│ ├── config/ -│ │ ├── env.js # Lecture et validation des variables d'environnement -│ │ └── constants.js # Couleurs, niveaux d'accès, catégories de tickets -│ ├── core/ -│ │ ├── client.js # Client Discord et intents -│ │ ├── command-loader.js # Chargement automatique de src/commands/** -│ │ ├── event-loader.js # Chargement automatique de src/events/* -│ │ ├── permissions.js # Contrôle central des accès et de la hiérarchie -│ │ ├── logger.js # Logs JSON avec masquage des secrets -│ │ └── errors.js # Erreurs typées (utilisateur, permission, API) -│ ├── commands//.js -│ ├── events/ # Un fichier par événement Discord -│ ├── services/ # Logique métier et intégrations (Gitea, notifications…) -│ ├── database/ -│ │ ├── index.js # Connexion et migrations -│ │ ├── migrations/ # Fichiers SQL numérotés -│ │ └── repositories/ # Accès aux tables -│ ├── webhooks/ # Serveur HTTP et réception des webhooks Gitea -│ ├── ui/ # Embeds et boutons standardisés -│ └── utils/ # Retry, cooldown… -└── tests/ # Tests node:test -``` - -## Contrat d'une commande - -```js -export const access = ACCESS_LEVELS.STAFF; // niveau minimum -export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optionnel -export const data = new SlashCommandBuilder()...; -export async function execute(interaction) {} -``` - -Le contrôle d'accès est appliqué dans `events/interaction-create.js` avant l'exécution. Une `UserFacingError` est affichée telle quelle ; toute autre erreur est journalisée et remplacée par un message générique. - -## Contrat d'un événement - -```js -export const name = Events.GuildMemberAdd; -export const once = false; // optionnel -export async function execute(client, ...args) {} -``` - -## Intents Discord - -| Intent | Usage | Privilégié | -| ----------------- | -------------------------------- | ----------------------------------- | -| `Guilds` | Commandes, salons, rôles | Non | -| `GuildMembers` | Bienvenue, départs, rôle initial | **Oui** (à activer dans le portail) | -| `GuildModeration` | Événements de ban | Non | -| `GuildMessages` | `/clear`, salons de tickets | Non | - -`MessageContent` n'est pas demandé. - -## Lancement local - -```bash -npm install -cp .env.example .env # puis remplir les valeurs -npm run db:init -npm run deploy:commands -npm run dev -``` - -## Qualité - -| Commande | Rôle | -| ---------------------- | ----------------- | -| `npm run lint` | ESLint | -| `npm run format:check` | Prettier | -| `npm test` | Tests `node:test` | +# Architecture — FWS-Bot + +Stack : **Node.js ≥ 22.13** (JavaScript ESM), **discord.js v14**, **SQLite** via le module natif `node:sqlite` (aucune dépendance native à compiler). + +## Arborescence + +```text +fws-discordbot/ +├── .env.example # Modèle de configuration (sans secret) +├── assets/screenshots/ # Captures référencées dans la documentation +├── data/ # Base SQLite et sauvegardes (ignoré par git) +├── docs/ # Documentation technique +├── logs/ # Logs techniques journaliers (ignoré par git) +├── scripts/ +│ ├── deploy-commands.js # Enregistre les commandes slash sur le serveur +│ └── init-database.js # Crée la base et applique les migrations +├── src/ +│ ├── index.js # Point d'entrée +│ ├── config/ +│ │ ├── env.js # Lecture et validation des variables d'environnement +│ │ └── constants.js # Couleurs, niveaux d'accès, catégories de tickets +│ ├── core/ +│ │ ├── client.js # Client Discord et intents +│ │ ├── command-loader.js # Chargement automatique de src/commands/** +│ │ ├── event-loader.js # Chargement automatique de src/events/* +│ │ ├── permissions.js # Contrôle central des accès et de la hiérarchie +│ │ ├── logger.js # Logs JSON avec masquage des secrets +│ │ └── errors.js # Erreurs typées (utilisateur, permission, API) +│ ├── commands//.js +│ ├── events/ # Un fichier par événement Discord +│ ├── services/ # Logique métier et intégrations (Gitea, notifications…) +│ ├── database/ +│ │ ├── index.js # Connexion et migrations +│ │ ├── migrations/ # Fichiers SQL numérotés +│ │ └── repositories/ # Accès aux tables +│ ├── webhooks/ # Serveur HTTP et réception des webhooks Gitea +│ ├── ui/ # Embeds et boutons standardisés +│ └── utils/ # Retry, cooldown… +└── tests/ # Tests node:test +``` + +## Contrat d'une commande + +```js +export const access = ACCESS_LEVELS.STAFF; // niveau minimum +export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optionnel +export const data = new SlashCommandBuilder()...; +export async function execute(interaction) {} +``` + +Le contrôle d'accès est appliqué dans `events/interaction-create.js` avant l'exécution. Une `UserFacingError` est affichée telle quelle ; toute autre erreur est journalisée et remplacée par un message générique. + +## Contrat d'un événement + +```js +export const name = Events.GuildMemberAdd; +export const once = false; // optionnel +export async function execute(client, ...args) {} +``` + +## Intents Discord + +| Intent | Usage | Privilégié | +| ----------------- | -------------------------------- | ----------------------------------- | +| `Guilds` | Commandes, salons, rôles | Non | +| `GuildMembers` | Bienvenue, départs, rôle initial | **Oui** (à activer dans le portail) | +| `GuildModeration` | Événements de ban | Non | +| `GuildMessages` | `/clear`, salons de tickets | Non | + +`MessageContent` n'est pas demandé. + +## Lancement local + +```bash +npm install +cp .env.example .env # puis remplir les valeurs +npm run db:init +npm run deploy:commands +npm run dev +``` + +## Qualité + +| Commande | Rôle | +| ---------------------- | ----------------- | +| `npm run lint` | ESLint | +| `npm run format:check` | Prettier | +| `npm test` | Tests `node:test` | diff --git a/eslint.config.js b/eslint.config.js index d7f95d0..04fcf2c 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,21 +1,21 @@ -import js from '@eslint/js'; -import prettier from 'eslint-config-prettier'; -import globals from 'globals'; - -export default [ - { ignores: ['node_modules/', 'data/', 'logs/', 'coverage/'] }, - js.configs.recommended, - { - languageOptions: { - ecmaVersion: 'latest', - sourceType: 'module', - globals: globals.node, - }, - rules: { - 'no-unused-vars': ['error', { argsIgnorePattern: '^_' }], - 'prefer-const': 'error', - eqeqeq: ['error', 'always'], - }, - }, - prettier, -]; +import js from '@eslint/js'; +import prettier from 'eslint-config-prettier'; +import globals from 'globals'; + +export default [ + { ignores: ['node_modules/', 'data/', 'logs/', 'coverage/'] }, + js.configs.recommended, + { + languageOptions: { + ecmaVersion: 'latest', + sourceType: 'module', + globals: globals.node, + }, + rules: { + 'no-unused-vars': ['error', { argsIgnorePattern: '^_' }], + 'prefer-const': 'error', + eqeqeq: ['error', 'always'], + }, + }, + prettier, +]; diff --git a/package-lock.json b/package-lock.json index 7cc794b..01143a7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,1443 +1,1443 @@ -{ - "name": "fws-discordbot", - "version": "0.1.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "fws-discordbot", - "version": "0.1.0", - "dependencies": { - "discord.js": "^14.21.0" - }, - "devDependencies": { - "@eslint/js": "^9.30.0", - "eslint": "^9.30.0", - "eslint-config-prettier": "^10.1.5", - "globals": "^16.3.0", - "prettier": "^3.6.2" - }, - "engines": { - "node": ">=22.13.0" - } - }, - "node_modules/@discordjs/builders": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz", - "integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==", - "license": "Apache-2.0", - "dependencies": { - "@discordjs/formatters": "^0.6.2", - "@discordjs/util": "^1.2.0", - "@sapphire/shapeshift": "^4.0.0", - "discord-api-types": "^0.38.40", - "fast-deep-equal": "^3.1.3", - "ts-mixer": "^6.0.4", - "tslib": "^2.6.3" - }, - "engines": { - "node": ">=16.11.0" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@discordjs/collection": { - "version": "1.5.3", - "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz", - "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=16.11.0" - } - }, - "node_modules/@discordjs/formatters": { - "version": "0.6.2", - "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz", - "integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==", - "license": "Apache-2.0", - "dependencies": { - "discord-api-types": "^0.38.33" - }, - "engines": { - "node": ">=16.11.0" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@discordjs/rest": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.3.tgz", - "integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==", - "license": "Apache-2.0", - "dependencies": { - "@discordjs/collection": "^2.1.1", - "@discordjs/util": "^1.2.0", - "@sapphire/async-queue": "^1.5.3", - "@sapphire/snowflake": "^3.5.5", - "@vladfrangu/async_event_emitter": "^2.4.6", - "discord-api-types": "^0.38.50", - "magic-bytes.js": "^1.13.0", - "tslib": "^2.6.3", - "undici": "^6.27.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@discordjs/rest/node_modules/@discordjs/collection": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz", - "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==", - "license": "Apache-2.0", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@discordjs/util": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz", - "integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==", - "license": "Apache-2.0", - "dependencies": { - "discord-api-types": "^0.38.33" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@discordjs/ws": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz", - "integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==", - "license": "Apache-2.0", - "dependencies": { - "@discordjs/collection": "^2.1.0", - "@discordjs/rest": "^2.5.1", - "@discordjs/util": "^1.1.0", - "@sapphire/async-queue": "^1.5.2", - "@types/ws": "^8.5.10", - "@vladfrangu/async_event_emitter": "^2.2.4", - "discord-api-types": "^0.38.1", - "tslib": "^2.6.2", - "ws": "^8.17.0" - }, - "engines": { - "node": ">=16.11.0" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@discordjs/ws/node_modules/@discordjs/collection": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz", - "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==", - "license": "Apache-2.0", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/@eslint-community/eslint-utils": { - "version": "4.10.1", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", - "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==", - "dev": true, - "license": "MIT", - "dependencies": { - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" - } - }, - "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", - "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@eslint-community/regexpp": { - "version": "4.12.2", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", - "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.0.0 || ^14.0.0 || >=16.0.0" - } - }, - "node_modules/@eslint/config-array": { - "version": "0.21.2", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz", - "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/object-schema": "^2.1.7", - "debug": "^4.3.1", - "minimatch": "^3.1.5" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/config-helpers": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", - "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/core": "^0.17.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/core": { - "version": "0.17.0", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", - "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@types/json-schema": "^7.0.15" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/eslintrc": { - "version": "3.3.7", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.7.tgz", - "integrity": "sha512-F42g89Qd5oAWtp0k0nnSrjziAKza7w8SVT4mStc18LZMaRb4J1HQAHLCalEtDCxrTuksx7NU9qsmeLwpOfPqWw==", - "dev": true, - "license": "MIT", - "dependencies": { - "ajv": "^6.14.0", - "debug": "^4.3.2", - "espree": "^10.0.1", - "globals": "^14.0.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.3.2", - "minimatch": "^3.1.5", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@eslint/eslintrc/node_modules/globals": { - "version": "14.0.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", - "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@eslint/js": { - "version": "9.39.5", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.5.tgz", - "integrity": "sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://eslint.org/donate" - } - }, - "node_modules/@eslint/object-schema": { - "version": "2.1.7", - "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", - "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/plugin-kit": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", - "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/core": "^0.17.0", - "levn": "^0.4.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@humanfs/core": { - "version": "0.19.2", - "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", - "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@humanfs/types": "^0.15.0" - }, - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanfs/node": { - "version": "0.16.8", - "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", - "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@humanfs/core": "^0.19.2", - "@humanfs/types": "^0.15.0", - "@humanwhocodes/retry": "^0.4.0" - }, - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanfs/types": { - "version": "0.15.0", - "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", - "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanwhocodes/module-importer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", - "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12.22" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@humanwhocodes/retry": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", - "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18.18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@sapphire/async-queue": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz", - "integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==", - "license": "MIT", - "engines": { - "node": ">=v14.0.0", - "npm": ">=7.0.0" - } - }, - "node_modules/@sapphire/shapeshift": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz", - "integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==", - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "lodash": "^4.17.21" - }, - "engines": { - "node": ">=v16" - } - }, - "node_modules/@sapphire/snowflake": { - "version": "3.5.5", - "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz", - "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==", - "license": "MIT", - "engines": { - "node": ">=v14.0.0", - "npm": ">=7.0.0" - } - }, - "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/json-schema": { - "version": "7.0.15", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", - "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "26.5.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.5.1.tgz", - "integrity": "sha512-CzNm2FezW4VR/LjG6yUdiEgLE/rAQ9Slj5gCu/C2VrdcW7I0ahNZ8DRbHT7zOZ6r3ONgd/bsQIeSaoDGrd1C6g==", - "license": "MIT", - "dependencies": { - "undici-types": "~8.9.0" - } - }, - "node_modules/@types/ws": { - "version": "8.18.1", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", - "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@vladfrangu/async_event_emitter": { - "version": "2.4.7", - "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz", - "integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==", - "license": "MIT", - "engines": { - "node": ">=v14.0.0", - "npm": ">=7.0.0" - } - }, - "node_modules/acorn": { - "version": "8.18.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", - "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", - "dev": true, - "license": "MIT", - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-jsx": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, - "node_modules/ajv": { - "version": "6.15.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", - "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, - "license": "Python-2.0" - }, - "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, - "license": "MIT" - }, - "node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, - "license": "MIT" - }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true, - "license": "MIT" - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/deep-is": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/discord-api-types": { - "version": "0.38.55", - "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.55.tgz", - "integrity": "sha512-ytuaRTzdnHUCXJ6KjL9MrItQX0xKncBKEeYI1Bst4+ud47eejH3cG6gaesYakjpPcUhh68XYS2YwGq3mmujFsA==", - "license": "MIT" - }, - "node_modules/discord.js": { - "version": "14.27.0", - "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.27.0.tgz", - "integrity": "sha512-qHbFlFG2N7y3LjPySYsL6A1+BnX6bkTVgo842EX0CqVPk/KTMwZkojPHEXKsQUpWZNyz5BISNHK1cPpQw0+m4A==", - "license": "Apache-2.0", - "dependencies": { - "@discordjs/builders": "^1.14.1", - "@discordjs/collection": "1.5.3", - "@discordjs/formatters": "^0.6.2", - "@discordjs/rest": "^2.6.2", - "@discordjs/util": "^1.2.0", - "@discordjs/ws": "^1.2.3", - "@sapphire/snowflake": "3.5.5", - "discord-api-types": "^0.38.49", - "fast-deep-equal": "3.1.3", - "lodash.snakecase": "4.1.1", - "magic-bytes.js": "^1.13.0", - "tslib": "^2.6.3", - "undici": "^6.27.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/discordjs/discord.js?sponsor" - } - }, - "node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/eslint": { - "version": "9.39.5", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.5.tgz", - "integrity": "sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw==", - "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.8.0", - "@eslint-community/regexpp": "^4.12.1", - "@eslint/config-array": "^0.21.2", - "@eslint/config-helpers": "^0.4.2", - "@eslint/core": "^0.17.0", - "@eslint/eslintrc": "^3.3.6", - "@eslint/js": "9.39.5", - "@eslint/plugin-kit": "^0.4.1", - "@humanfs/node": "^0.16.6", - "@humanwhocodes/module-importer": "^1.0.1", - "@humanwhocodes/retry": "^0.4.2", - "@types/estree": "^1.0.6", - "ajv": "^6.14.0", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.6", - "debug": "^4.3.2", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^8.4.0", - "eslint-visitor-keys": "^4.2.1", - "espree": "^10.4.0", - "esquery": "^1.5.0", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^8.0.0", - "find-up": "^5.0.0", - "glob-parent": "^6.0.2", - "ignore": "^5.2.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.1.5", - "natural-compare": "^1.4.0", - "optionator": "^0.9.3" - }, - "bin": { - "eslint": "bin/eslint.js" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://eslint.org/donate" - }, - "peerDependencies": { - "jiti": "*" - }, - "peerDependenciesMeta": { - "jiti": { - "optional": true - } - } - }, - "node_modules/eslint-config-prettier": { - "version": "10.1.8", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-10.1.8.tgz", - "integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==", - "dev": true, - "license": "MIT", - "bin": { - "eslint-config-prettier": "bin/cli.js" - }, - "funding": { - "url": "https://opencollective.com/eslint-config-prettier" - }, - "peerDependencies": { - "eslint": ">=7.0.0" - } - }, - "node_modules/eslint-scope": { - "version": "8.4.0", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", - "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-visitor-keys": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", - "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/espree": { - "version": "10.4.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", - "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "acorn": "^8.15.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^4.2.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/esquery": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", - "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "estraverse": "^5.1.0" - }, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "estraverse": "^5.2.0" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "license": "MIT" - }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "dev": true, - "license": "MIT" - }, - "node_modules/file-entry-cache": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", - "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "flat-cache": "^4.0.0" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/find-up": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", - "dev": true, - "license": "MIT", - "dependencies": { - "locate-path": "^6.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/flat-cache": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", - "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", - "dev": true, - "license": "MIT", - "dependencies": { - "flatted": "^3.2.9", - "keyv": "^4.5.4" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/flatted": { - "version": "3.4.4", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", - "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", - "dev": true, - "license": "ISC" - }, - "node_modules/glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/globals": { - "version": "16.5.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-16.5.0.tgz", - "integrity": "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/import-fresh": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", - "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.19" - } - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, - "license": "ISC" - }, - "node_modules/js-yaml": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", - "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/puzrin" - }, - { - "type": "github", - "url": "https://github.com/sponsors/nodeca" - } - ], - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/json-buffer": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", - "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "dev": true, - "license": "MIT" - }, - "node_modules/keyv": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", - "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", - "dev": true, - "license": "MIT", - "dependencies": { - "json-buffer": "3.0.1" - } - }, - "node_modules/levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^5.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/lodash": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", - "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", - "license": "MIT" - }, - "node_modules/lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.snakecase": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", - "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==", - "license": "MIT" - }, - "node_modules/magic-bytes.js": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.1.tgz", - "integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==", - "license": "MIT" - }, - "node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "dev": true, - "license": "MIT" - }, - "node_modules/natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true, - "license": "MIT" - }, - "node_modules/optionator": { - "version": "0.9.4", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", - "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.5" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/p-limit": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "yocto-queue": "^0.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^3.0.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/parent-module": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, - "license": "MIT", - "dependencies": { - "callsites": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/prettier": { - "version": "3.9.6", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.6.tgz", - "integrity": "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==", - "dev": true, - "license": "MIT", - "bin": { - "prettier": "bin/prettier.cjs" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/prettier/prettier?sponsor=1" - } - }, - "node_modules/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/ts-mixer": { - "version": "6.0.4", - "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz", - "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==", - "license": "MIT" - }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "license": "0BSD" - }, - "node_modules/type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/undici": { - "version": "6.28.1", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.1.tgz", - "integrity": "sha512-zWpdTVD54H48CIybL0rWQ3ukpb9d23wM7eH5RtfdmeP70cWHNjtfo7P4vZX+5CoDcO53J4Pu5uXp7lNfjc6DRA==", - "license": "MIT", - "engines": { - "node": ">=18.17" - } - }, - "node_modules/undici-types": { - "version": "8.9.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", - "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", - "license": "MIT" - }, - "node_modules/uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "punycode": "^2.1.0" - } - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/word-wrap": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", - "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/ws": { - "version": "8.21.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", - "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - } - } -} +{ + "name": "fws-discordbot", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "fws-discordbot", + "version": "0.1.0", + "dependencies": { + "discord.js": "^14.21.0" + }, + "devDependencies": { + "@eslint/js": "^9.30.0", + "eslint": "^9.30.0", + "eslint-config-prettier": "^10.1.5", + "globals": "^16.3.0", + "prettier": "^3.6.2" + }, + "engines": { + "node": ">=22.13.0" + } + }, + "node_modules/@discordjs/builders": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz", + "integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/formatters": "^0.6.2", + "@discordjs/util": "^1.2.0", + "@sapphire/shapeshift": "^4.0.0", + "discord-api-types": "^0.38.40", + "fast-deep-equal": "^3.1.3", + "ts-mixer": "^6.0.4", + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/collection": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz", + "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/formatters": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz", + "integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==", + "license": "Apache-2.0", + "dependencies": { + "discord-api-types": "^0.38.33" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/rest": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.3.tgz", + "integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/collection": "^2.1.1", + "@discordjs/util": "^1.2.0", + "@sapphire/async-queue": "^1.5.3", + "@sapphire/snowflake": "^3.5.5", + "@vladfrangu/async_event_emitter": "^2.4.6", + "discord-api-types": "^0.38.50", + "magic-bytes.js": "^1.13.0", + "tslib": "^2.6.3", + "undici": "^6.27.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/rest/node_modules/@discordjs/collection": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz", + "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/util": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz", + "integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==", + "license": "Apache-2.0", + "dependencies": { + "discord-api-types": "^0.38.33" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/ws": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz", + "integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/collection": "^2.1.0", + "@discordjs/rest": "^2.5.1", + "@discordjs/util": "^1.1.0", + "@sapphire/async-queue": "^1.5.2", + "@types/ws": "^8.5.10", + "@vladfrangu/async_event_emitter": "^2.2.4", + "discord-api-types": "^0.38.1", + "tslib": "^2.6.2", + "ws": "^8.17.0" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/ws/node_modules/@discordjs/collection": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz", + "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.2", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz", + "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.7.tgz", + "integrity": "sha512-F42g89Qd5oAWtp0k0nnSrjziAKza7w8SVT4mStc18LZMaRb4J1HQAHLCalEtDCxrTuksx7NU9qsmeLwpOfPqWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.3.2", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.5", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.5.tgz", + "integrity": "sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@sapphire/async-queue": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz", + "integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sapphire/shapeshift": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz", + "integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "lodash": "^4.17.21" + }, + "engines": { + "node": ">=v16" + } + }, + "node_modules/@sapphire/snowflake": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz", + "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.5.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.5.1.tgz", + "integrity": "sha512-CzNm2FezW4VR/LjG6yUdiEgLE/rAQ9Slj5gCu/C2VrdcW7I0ahNZ8DRbHT7zOZ6r3ONgd/bsQIeSaoDGrd1C6g==", + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@vladfrangu/async_event_emitter": { + "version": "2.4.7", + "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz", + "integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "1.1.18", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", + "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/discord-api-types": { + "version": "0.38.55", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.55.tgz", + "integrity": "sha512-ytuaRTzdnHUCXJ6KjL9MrItQX0xKncBKEeYI1Bst4+ud47eejH3cG6gaesYakjpPcUhh68XYS2YwGq3mmujFsA==", + "license": "MIT" + }, + "node_modules/discord.js": { + "version": "14.27.0", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.27.0.tgz", + "integrity": "sha512-qHbFlFG2N7y3LjPySYsL6A1+BnX6bkTVgo842EX0CqVPk/KTMwZkojPHEXKsQUpWZNyz5BISNHK1cPpQw0+m4A==", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/builders": "^1.14.1", + "@discordjs/collection": "1.5.3", + "@discordjs/formatters": "^0.6.2", + "@discordjs/rest": "^2.6.2", + "@discordjs/util": "^1.2.0", + "@discordjs/ws": "^1.2.3", + "@sapphire/snowflake": "3.5.5", + "discord-api-types": "^0.38.49", + "fast-deep-equal": "3.1.3", + "lodash.snakecase": "4.1.1", + "magic-bytes.js": "^1.13.0", + "tslib": "^2.6.3", + "undici": "^6.27.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.5", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.5.tgz", + "integrity": "sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw==", + "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.2", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.6", + "@eslint/js": "9.39.5", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-config-prettier": { + "version": "10.1.8", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-10.1.8.tgz", + "integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==", + "dev": true, + "license": "MIT", + "bin": { + "eslint-config-prettier": "bin/cli.js" + }, + "funding": { + "url": "https://opencollective.com/eslint-config-prettier" + }, + "peerDependencies": { + "eslint": ">=7.0.0" + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", + "dev": true, + "license": "ISC" + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "16.5.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-16.5.0.tgz", + "integrity": "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", + "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==", + "license": "MIT" + }, + "node_modules/magic-bytes.js": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.1.tgz", + "integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==", + "license": "MIT" + }, + "node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prettier": { + "version": "3.9.6", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.6.tgz", + "integrity": "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ts-mixer": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz", + "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/undici": { + "version": "6.28.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.1.tgz", + "integrity": "sha512-zWpdTVD54H48CIybL0rWQ3ukpb9d23wM7eH5RtfdmeP70cWHNjtfo7P4vZX+5CoDcO53J4Pu5uXp7lNfjc6DRA==", + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "license": "MIT" + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/package.json b/package.json index cc9fcfa..5c5eaa1 100644 --- a/package.json +++ b/package.json @@ -1,34 +1,34 @@ -{ - "name": "fws-discordbot", - "version": "0.1.0", - "description": "FWS-Bot — Discord bot for the FWS open source organization", - "private": true, - "type": "module", - "main": "src/index.js", - "engines": { - "node": ">=22.13.0" - }, - "scripts": { - "start": "node src/index.js", - "dev": "node --watch src/index.js", - "deploy:commands": "node scripts/deploy-commands.js", - "db:init": "node scripts/init-database.js", - "changelog": "node scripts/generate-changelog.js", - "changelog:check": "node scripts/generate-changelog.js --check", - "lint": "eslint .", - "lint:fix": "eslint . --fix", - "format": "prettier --write .", - "format:check": "prettier --check .", - "test": "node --test tests/" - }, - "dependencies": { - "discord.js": "^14.21.0" - }, - "devDependencies": { - "@eslint/js": "^9.30.0", - "eslint": "^9.30.0", - "eslint-config-prettier": "^10.1.5", - "globals": "^16.3.0", - "prettier": "^3.6.2" - } -} +{ + "name": "fws-discordbot", + "version": "0.1.0", + "description": "FWS-Bot — Discord bot for the FWS open source organization", + "private": true, + "type": "module", + "main": "src/index.js", + "engines": { + "node": ">=22.13.0" + }, + "scripts": { + "start": "node src/index.js", + "dev": "node --watch src/index.js", + "deploy:commands": "node scripts/deploy-commands.js", + "db:init": "node scripts/init-database.js", + "changelog": "node scripts/generate-changelog.js", + "changelog:check": "node scripts/generate-changelog.js --check", + "lint": "eslint .", + "lint:fix": "eslint . --fix", + "format": "prettier --write .", + "format:check": "prettier --check .", + "test": "node --test tests/" + }, + "dependencies": { + "discord.js": "^14.21.0" + }, + "devDependencies": { + "@eslint/js": "^9.30.0", + "eslint": "^9.30.0", + "eslint-config-prettier": "^10.1.5", + "globals": "^16.3.0", + "prettier": "^3.6.2" + } +} diff --git a/scripts/deploy-commands.js b/scripts/deploy-commands.js index 8958e9d..d5dd5a7 100644 --- a/scripts/deploy-commands.js +++ b/scripts/deploy-commands.js @@ -1,13 +1,13 @@ -import { REST, Routes } from 'discord.js'; -import { assertRequiredEnv, env } from '../src/config/env.js'; -import { loadCommands } from '../src/core/command-loader.js'; - -assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']); - -const body = (await loadCommands()).map((command) => command.data.toJSON()); -const rest = new REST().setToken(env.discord.token); - -// Guild commands update instantly, which suits a single-server bot (M2-T05). -await rest.put(Routes.applicationGuildCommands(env.discord.clientId, env.discord.guildId), { body }); - -console.log(`Registered ${body.length} slash commands on guild ${env.discord.guildId}.`); +import { REST, Routes } from 'discord.js'; +import { assertRequiredEnv, env } from '../src/config/env.js'; +import { loadCommands } from '../src/core/command-loader.js'; + +assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']); + +const body = (await loadCommands()).map((command) => command.data.toJSON()); +const rest = new REST().setToken(env.discord.token); + +// Guild commands update instantly, which suits a single-server bot (M2-T05). +await rest.put(Routes.applicationGuildCommands(env.discord.clientId, env.discord.guildId), { body }); + +console.log(`Registered ${body.length} slash commands on guild ${env.discord.guildId}.`); diff --git a/scripts/generate-changelog.js b/scripts/generate-changelog.js index 74d05ee..14786cf 100644 --- a/scripts/generate-changelog.js +++ b/scripts/generate-changelog.js @@ -1,172 +1,172 @@ -#!/usr/bin/env node -import { execFileSync } from 'node:child_process'; -import { readFileSync, writeFileSync } from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -/** - * Builds CHANGELOG.md from the Conventional Commits of the history, as the FWS conventions - * require: `feat` and `fix` feed the Features and Bug Fixes sections, the other types are - * grouped under "Other changes". The file is generated, so run this script instead of editing it. - * - * Usage: node scripts/generate-changelog.js [--check] - * --check exits with code 1 when CHANGELOG.md is out of date (used by CI and tests) - */ - -const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const changelogPath = path.join(rootDir, 'CHANGELOG.md'); -const checkOnly = process.argv.includes('--check'); - -/** Section order and titles; anything else falls into "Other changes". */ -const SECTIONS = [ - { title: 'Features', test: (type) => type === 'feat' }, - { title: 'Bug Fixes', test: (type) => type === 'fix' }, - { title: 'Performance', test: (type) => type === 'perf' }, - { - title: 'Other changes', - test: (type) => type !== 'feat' && type !== 'fix' && type !== 'perf', - }, -]; - -const OTHER_LABELS = { - build: 'build', - chore: 'chore', - ci: 'ci', - docs: 'docs', - refactor: 'refactor', - revert: 'revert', - style: 'style', - test: 'test', -}; - -const git = (args) => execFileSync('git', args, { cwd: rootDir, encoding: 'utf8' }); - -function readCommits() { - // One record per commit, fields separated by unit separators so bodies stay readable. - const raw = git([ - 'log', - '--no-merges', - '--date=short', - '--format=%H%x1f%ad%x1f%s%x1f%b%x1f%D%x1e', - // A commit that only rewrites the changelog must not appear in it, otherwise `--check` - // could never be green once that file is committed. - '--', - '.', - ':(exclude)CHANGELOG.md', - ]); - return raw - .split('\x1e') - .map((record) => record.trim()) - .filter(Boolean) - .map((record) => { - const [hash, date, subject, body = '', decoration = ''] = record.split('\x1f'); - const match = /^(?[a-z]+)(?:\((?[^)]*)\))?(?!)?: (?.+)$/.exec( - subject.trim(), - ); - const breaking = Boolean(match?.groups.breaking) || /BREAKING CHANGE/.test(body); - return { - hash, - date, - subject: subject.trim(), - type: match?.groups.type ?? 'other', - scope: match?.groups.scope ?? null, - description: match?.groups.description ?? subject.trim(), - breaking, - tags: decoration - .split(',') - .map((ref) => ref.trim().replace(/^tag: /, '')) - .filter((ref) => /^v?\d+\.\d+\.\d+/.test(ref)), - }; - }); -} - -function entryLine(commit) { - const scope = commit.scope ? `**${commit.scope}:** ` : ''; - const breaking = commit.breaking ? '**BREAKING** ' : ''; - const label = commit.type === 'other' ? '' : `_(${OTHER_LABELS[commit.type] ?? commit.type})_ `; - const detail = commit.type === 'other' ? commit.subject : commit.description; - return `- ${breaking}${scope}${label}${detail} ([${commit.hash.slice(0, 7)}])`; -} - -/** A commit without a tag belongs to "Unreleased"; a tag closes the section it points to. */ -function groupByRelease(commits) { - const releases = []; - let current = { title: 'Unreleased', date: null, commits: [] }; - - for (const commit of commits) { - current.commits.push(commit); - for (const tag of commit.tags) { - releases.push({ title: tag, date: commit.date, commits: current.commits }); - current = { title: 'Unreleased', date: null, commits: [] }; - } - } - if (current.commits.length > 0) releases.push(current); - return releases; -} - -function renderRelease(release) { - const heading = release.date ? `## [${release.title}] — ${release.date}` : `## [${release.title}]`; - const lines = [heading]; - - for (const section of SECTIONS) { - const entries = release.commits.filter((commit) => section.test(commit.type)); - if (entries.length === 0) continue; - lines.push('', `### ${section.title}`, ...entries.map(entryLine)); - } - - if (release.commits.length === 0) lines.push('', '_Nothing yet._'); - return lines.join('\n'); -} - -/** SemVer hint from the commits since the last release: breaking > feature > fix. */ -function suggestVersion(commits) { - const version = JSON.parse(readFileSync(path.join(rootDir, 'package.json'), 'utf8')).version; - const [major, minor, patch] = version.split('.').map(Number); - const breaking = commits.some((commit) => commit.breaking); - const feature = commits.some((commit) => commit.type === 'feat'); - - // SemVer §4: below 1.0.0 anything may change, so a breaking change only bumps the minor. - if (major === 0) return breaking || feature ? `0.${minor + 1}.0` : `0.${minor}.${patch + 1}`; - if (breaking) return `${major + 1}.0.0`; - if (feature) return `${major}.${minor + 1}.0`; - return `${major}.${minor}.${patch + 1}`; -} - -function buildChangelog(commits) { - const releases = groupByRelease(commits); - - return [ - '# Changelog', - '', - 'All notable changes to this project are documented in this file. It is **generated from the', - 'Conventional Commits** of the history: run `npm run changelog` instead of editing it by hand.', - 'The project follows [Semantic Versioning](https://semver.org/).', - '', - releases.map(renderRelease).join('\n\n'), - '', - ].join('\n'); -} - -const commits = readCommits(); -const content = buildChangelog(commits); -const unreleased = commits.filter((commit) => !commit.tags.length); -const previous = (() => { - try { - return readFileSync(changelogPath, 'utf8'); - } catch { - return null; - } -})(); - -if (checkOnly) { - if (previous !== content) { - console.error('CHANGELOG.md is out of date: run `npm run changelog`.'); - process.exit(1); - } - console.log('CHANGELOG.md is up to date.'); - process.exit(0); -} - -writeFileSync(changelogPath, content); -console.log(`Wrote ${path.relative(rootDir, changelogPath)} from ${commits.length} commits.`); -console.log(`Suggested next version: ${suggestVersion(unreleased)}`); +#!/usr/bin/env node +import { execFileSync } from 'node:child_process'; +import { readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** + * Builds CHANGELOG.md from the Conventional Commits of the history, as the FWS conventions + * require: `feat` and `fix` feed the Features and Bug Fixes sections, the other types are + * grouped under "Other changes". The file is generated, so run this script instead of editing it. + * + * Usage: node scripts/generate-changelog.js [--check] + * --check exits with code 1 when CHANGELOG.md is out of date (used by CI and tests) + */ + +const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const changelogPath = path.join(rootDir, 'CHANGELOG.md'); +const checkOnly = process.argv.includes('--check'); + +/** Section order and titles; anything else falls into "Other changes". */ +const SECTIONS = [ + { title: 'Features', test: (type) => type === 'feat' }, + { title: 'Bug Fixes', test: (type) => type === 'fix' }, + { title: 'Performance', test: (type) => type === 'perf' }, + { + title: 'Other changes', + test: (type) => type !== 'feat' && type !== 'fix' && type !== 'perf', + }, +]; + +const OTHER_LABELS = { + build: 'build', + chore: 'chore', + ci: 'ci', + docs: 'docs', + refactor: 'refactor', + revert: 'revert', + style: 'style', + test: 'test', +}; + +const git = (args) => execFileSync('git', args, { cwd: rootDir, encoding: 'utf8' }); + +function readCommits() { + // One record per commit, fields separated by unit separators so bodies stay readable. + const raw = git([ + 'log', + '--no-merges', + '--date=short', + '--format=%H%x1f%ad%x1f%s%x1f%b%x1f%D%x1e', + // A commit that only rewrites the changelog must not appear in it, otherwise `--check` + // could never be green once that file is committed. + '--', + '.', + ':(exclude)CHANGELOG.md', + ]); + return raw + .split('\x1e') + .map((record) => record.trim()) + .filter(Boolean) + .map((record) => { + const [hash, date, subject, body = '', decoration = ''] = record.split('\x1f'); + const match = /^(?[a-z]+)(?:\((?[^)]*)\))?(?!)?: (?.+)$/.exec( + subject.trim(), + ); + const breaking = Boolean(match?.groups.breaking) || /BREAKING CHANGE/.test(body); + return { + hash, + date, + subject: subject.trim(), + type: match?.groups.type ?? 'other', + scope: match?.groups.scope ?? null, + description: match?.groups.description ?? subject.trim(), + breaking, + tags: decoration + .split(',') + .map((ref) => ref.trim().replace(/^tag: /, '')) + .filter((ref) => /^v?\d+\.\d+\.\d+/.test(ref)), + }; + }); +} + +function entryLine(commit) { + const scope = commit.scope ? `**${commit.scope}:** ` : ''; + const breaking = commit.breaking ? '**BREAKING** ' : ''; + const label = commit.type === 'other' ? '' : `_(${OTHER_LABELS[commit.type] ?? commit.type})_ `; + const detail = commit.type === 'other' ? commit.subject : commit.description; + return `- ${breaking}${scope}${label}${detail} ([${commit.hash.slice(0, 7)}])`; +} + +/** A commit without a tag belongs to "Unreleased"; a tag closes the section it points to. */ +function groupByRelease(commits) { + const releases = []; + let current = { title: 'Unreleased', date: null, commits: [] }; + + for (const commit of commits) { + current.commits.push(commit); + for (const tag of commit.tags) { + releases.push({ title: tag, date: commit.date, commits: current.commits }); + current = { title: 'Unreleased', date: null, commits: [] }; + } + } + if (current.commits.length > 0) releases.push(current); + return releases; +} + +function renderRelease(release) { + const heading = release.date ? `## [${release.title}] — ${release.date}` : `## [${release.title}]`; + const lines = [heading]; + + for (const section of SECTIONS) { + const entries = release.commits.filter((commit) => section.test(commit.type)); + if (entries.length === 0) continue; + lines.push('', `### ${section.title}`, ...entries.map(entryLine)); + } + + if (release.commits.length === 0) lines.push('', '_Nothing yet._'); + return lines.join('\n'); +} + +/** SemVer hint from the commits since the last release: breaking > feature > fix. */ +function suggestVersion(commits) { + const version = JSON.parse(readFileSync(path.join(rootDir, 'package.json'), 'utf8')).version; + const [major, minor, patch] = version.split('.').map(Number); + const breaking = commits.some((commit) => commit.breaking); + const feature = commits.some((commit) => commit.type === 'feat'); + + // SemVer §4: below 1.0.0 anything may change, so a breaking change only bumps the minor. + if (major === 0) return breaking || feature ? `0.${minor + 1}.0` : `0.${minor}.${patch + 1}`; + if (breaking) return `${major + 1}.0.0`; + if (feature) return `${major}.${minor + 1}.0`; + return `${major}.${minor}.${patch + 1}`; +} + +function buildChangelog(commits) { + const releases = groupByRelease(commits); + + return [ + '# Changelog', + '', + 'All notable changes to this project are documented in this file. It is **generated from the', + 'Conventional Commits** of the history: run `npm run changelog` instead of editing it by hand.', + 'The project follows [Semantic Versioning](https://semver.org/).', + '', + releases.map(renderRelease).join('\n\n'), + '', + ].join('\n'); +} + +const commits = readCommits(); +const content = buildChangelog(commits); +const unreleased = commits.filter((commit) => !commit.tags.length); +const previous = (() => { + try { + return readFileSync(changelogPath, 'utf8'); + } catch { + return null; + } +})(); + +if (checkOnly) { + if (previous !== content) { + console.error('CHANGELOG.md is out of date: run `npm run changelog`.'); + process.exit(1); + } + console.log('CHANGELOG.md is up to date.'); + process.exit(0); +} + +writeFileSync(changelogPath, content); +console.log(`Wrote ${path.relative(rootDir, changelogPath)} from ${commits.length} commits.`); +console.log(`Suggested next version: ${suggestVersion(unreleased)}`); diff --git a/scripts/init-database.js b/scripts/init-database.js index b34e6eb..720153c 100644 --- a/scripts/init-database.js +++ b/scripts/init-database.js @@ -1,7 +1,7 @@ -import { env } from '../src/config/env.js'; -import { closeDatabase, initDatabase } from '../src/database/index.js'; - -initDatabase(); -closeDatabase(); - -console.log(`Database ready at ${env.database.path}`); +import { env } from '../src/config/env.js'; +import { closeDatabase, initDatabase } from '../src/database/index.js'; + +initDatabase(); +closeDatabase(); + +console.log(`Database ready at ${env.database.path}`); diff --git a/src/commands/community/fun.js b/src/commands/community/fun.js index 3423d42..a50fab2 100644 --- a/src/commands/community/fun.js +++ b/src/commands/community/fun.js @@ -1,107 +1,107 @@ -import { SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; -import { parseChoices } from '../../services/polls/poll-service.js'; -import { baseEmbed, bullets } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.USER; - -const EIGHT_BALL_ANSWERS = Object.freeze([ - 'Oui, sans aucun doute.', - 'Compte là-dessus et bois de l’eau.', - 'Les signes disent que oui.', - 'Impossible de le prédire pour le moment.', - 'Concentre-toi et redemande.', - 'Ma réponse est non.', - 'Très probablement.', - 'Mes sources disent non.', - 'La réponse est floue, réessaie.', - 'Absolument !', - 'Pas dans un avenir proche.', - 'Oui, mais fais attention à toi.', -]); - -const pick = (list) => list[Math.floor(Math.random() * list.length)]; - -export const data = new SlashCommandBuilder() - .setName('fun') - .setDescription('Commandes de divertissement') - .addSubcommand((sub) => sub.setName('coinflip').setDescription('Pile ou face')) - .addSubcommand((sub) => - sub - .setName('dice') - .setDescription('Lancer un dé') - .addIntegerOption((option) => - option - .setName('sides') - .setDescription('Nombre de faces (6 par défaut)') - .setMinValue(2) - .setMaxValue(1000), - ), - ) - .addSubcommand((sub) => - sub - .setName('8ball') - .setDescription('Poser une question à la boule magique') - .addStringOption((option) => - option.setName('question').setDescription('Ta question').setRequired(true).setMaxLength(300), - ), - ) - .addSubcommand((sub) => - sub - .setName('choose') - .setDescription('Choisir au hasard parmi plusieurs options') - .addStringOption((option) => - option.setName('options').setDescription('Options séparées par ";" (2 à 10)').setRequired(true), - ), - ); - -/** Lightweight, stateless fun commands (M10-T07). */ -export async function execute(interaction) { - const subcommand = interaction.options.getSubcommand(); - - if (subcommand === 'coinflip') { - const result = pick(['Pile', 'Face']); - await interaction.reply({ - embeds: [baseEmbed(COLORS.info).setTitle('🪙 Pile ou face').setDescription(`**${result}** !`)], - }); - return; - } - - if (subcommand === 'dice') { - const sides = interaction.options.getInteger('sides') ?? 6; - const roll = 1 + Math.floor(Math.random() * sides); - await interaction.reply({ - embeds: [ - baseEmbed(COLORS.info) - .setTitle(`🎲 Lancer de dé (d${sides})`) - .setDescription(`Tu obtiens **${roll}** !`), - ], - }); - return; - } - - if (subcommand === '8ball') { - const question = interaction.options.getString('question', true); - await interaction.reply({ - embeds: [ - baseEmbed(COLORS.info) - .setTitle('🎱 Boule magique') - .addFields( - { name: 'Question', value: question }, - { name: 'Réponse', value: pick(EIGHT_BALL_ANSWERS) }, - ), - ], - }); - return; - } - - const options = parseChoices(interaction.options.getString('options', true)); - await interaction.reply({ - embeds: [ - baseEmbed(COLORS.info) - .setTitle('🎯 Choix aléatoire') - .addFields({ name: 'Options', value: bullets(options) }) - .setDescription(`Je choisis : **${pick(options)}**`), - ], - }); -} +import { SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { parseChoices } from '../../services/polls/poll-service.js'; +import { baseEmbed, bullets } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.USER; + +const EIGHT_BALL_ANSWERS = Object.freeze([ + 'Oui, sans aucun doute.', + 'Compte là-dessus et bois de l’eau.', + 'Les signes disent que oui.', + 'Impossible de le prédire pour le moment.', + 'Concentre-toi et redemande.', + 'Ma réponse est non.', + 'Très probablement.', + 'Mes sources disent non.', + 'La réponse est floue, réessaie.', + 'Absolument !', + 'Pas dans un avenir proche.', + 'Oui, mais fais attention à toi.', +]); + +const pick = (list) => list[Math.floor(Math.random() * list.length)]; + +export const data = new SlashCommandBuilder() + .setName('fun') + .setDescription('Commandes de divertissement') + .addSubcommand((sub) => sub.setName('coinflip').setDescription('Pile ou face')) + .addSubcommand((sub) => + sub + .setName('dice') + .setDescription('Lancer un dé') + .addIntegerOption((option) => + option + .setName('sides') + .setDescription('Nombre de faces (6 par défaut)') + .setMinValue(2) + .setMaxValue(1000), + ), + ) + .addSubcommand((sub) => + sub + .setName('8ball') + .setDescription('Poser une question à la boule magique') + .addStringOption((option) => + option.setName('question').setDescription('Ta question').setRequired(true).setMaxLength(300), + ), + ) + .addSubcommand((sub) => + sub + .setName('choose') + .setDescription('Choisir au hasard parmi plusieurs options') + .addStringOption((option) => + option.setName('options').setDescription('Options séparées par ";" (2 à 10)').setRequired(true), + ), + ); + +/** Lightweight, stateless fun commands (M10-T07). */ +export async function execute(interaction) { + const subcommand = interaction.options.getSubcommand(); + + if (subcommand === 'coinflip') { + const result = pick(['Pile', 'Face']); + await interaction.reply({ + embeds: [baseEmbed(COLORS.info).setTitle('🪙 Pile ou face').setDescription(`**${result}** !`)], + }); + return; + } + + if (subcommand === 'dice') { + const sides = interaction.options.getInteger('sides') ?? 6; + const roll = 1 + Math.floor(Math.random() * sides); + await interaction.reply({ + embeds: [ + baseEmbed(COLORS.info) + .setTitle(`🎲 Lancer de dé (d${sides})`) + .setDescription(`Tu obtiens **${roll}** !`), + ], + }); + return; + } + + if (subcommand === '8ball') { + const question = interaction.options.getString('question', true); + await interaction.reply({ + embeds: [ + baseEmbed(COLORS.info) + .setTitle('🎱 Boule magique') + .addFields( + { name: 'Question', value: question }, + { name: 'Réponse', value: pick(EIGHT_BALL_ANSWERS) }, + ), + ], + }); + return; + } + + const options = parseChoices(interaction.options.getString('options', true)); + await interaction.reply({ + embeds: [ + baseEmbed(COLORS.info) + .setTitle('🎯 Choix aléatoire') + .addFields({ name: 'Options', value: bullets(options) }) + .setDescription(`Je choisis : **${pick(options)}**`), + ], + }); +} diff --git a/src/commands/community/poll.js b/src/commands/community/poll.js index 53c6aae..d2ed675 100644 --- a/src/commands/community/poll.js +++ b/src/commands/community/poll.js @@ -1,62 +1,62 @@ -import { MessageFlags, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS } from '../../config/constants.js'; -import { buildPollEmbed, closePollById, createPoll } from '../../services/polls/poll-service.js'; -import { successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.STAFF; - -export const data = new SlashCommandBuilder() - .setName('poll') - .setDescription('Sondages') - .addSubcommand((sub) => - sub - .setName('create') - .setDescription('Créer un sondage') - .addStringOption((option) => - option.setName('question').setDescription('Question posée').setRequired(true).setMaxLength(200), - ) - .addStringOption((option) => - option - .setName('choices') - .setDescription('Propositions séparées par des « ; » (2 à 10)') - .setRequired(true), - ) - .addIntegerOption((option) => - option - .setName('minutes') - .setDescription('Durée avant fermeture automatique, en minutes') - .setMinValue(1) - .setMaxValue(10_080), - ), - ) - .addSubcommand((sub) => - sub - .setName('close') - .setDescription('Fermer un sondage') - .addIntegerOption((option) => - option.setName('id').setDescription('Numéro du sondage (affiché dans l’embed)').setRequired(true), - ), - ); - -/** Polls are published in the current channel and voted with buttons (M10). */ -export async function execute(interaction) { - if (interaction.options.getSubcommand() === 'close') { - const poll = await closePollById(interaction.client, interaction.options.getInteger('id', true)); - await interaction.reply({ embeds: [buildPollEmbed(poll)] }); - return; - } - - const question = interaction.options.getString('question', true); - const choicesInput = interaction.options.getString('choices', true); - const minutes = interaction.options.getInteger('minutes'); - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const pollId = await createPoll(interaction, { question, choicesInput, minutes }); - await interaction.editReply({ - embeds: [ - successEmbed( - `Ton sondage **#${pollId}** est en ligne dans <#${interaction.channelId}> : tout le monde vote avec les boutons.`, - ), - ], - }); -} +import { MessageFlags, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { buildPollEmbed, closePollById, createPoll } from '../../services/polls/poll-service.js'; +import { successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.STAFF; + +export const data = new SlashCommandBuilder() + .setName('poll') + .setDescription('Sondages') + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Créer un sondage') + .addStringOption((option) => + option.setName('question').setDescription('Question posée').setRequired(true).setMaxLength(200), + ) + .addStringOption((option) => + option + .setName('choices') + .setDescription('Propositions séparées par des « ; » (2 à 10)') + .setRequired(true), + ) + .addIntegerOption((option) => + option + .setName('minutes') + .setDescription('Durée avant fermeture automatique, en minutes') + .setMinValue(1) + .setMaxValue(10_080), + ), + ) + .addSubcommand((sub) => + sub + .setName('close') + .setDescription('Fermer un sondage') + .addIntegerOption((option) => + option.setName('id').setDescription('Numéro du sondage (affiché dans l’embed)').setRequired(true), + ), + ); + +/** Polls are published in the current channel and voted with buttons (M10). */ +export async function execute(interaction) { + if (interaction.options.getSubcommand() === 'close') { + const poll = await closePollById(interaction.client, interaction.options.getInteger('id', true)); + await interaction.reply({ embeds: [buildPollEmbed(poll)] }); + return; + } + + const question = interaction.options.getString('question', true); + const choicesInput = interaction.options.getString('choices', true); + const minutes = interaction.options.getInteger('minutes'); + + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const pollId = await createPoll(interaction, { question, choicesInput, minutes }); + await interaction.editReply({ + embeds: [ + successEmbed( + `Ton sondage **#${pollId}** est en ligne dans <#${interaction.channelId}> : tout le monde vote avec les boutons.`, + ), + ], + }); +} diff --git a/src/commands/community/stats.js b/src/commands/community/stats.js index a8ac0d8..73ea420 100644 --- a/src/commands/community/stats.js +++ b/src/commands/community/stats.js @@ -1,116 +1,116 @@ -import { SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; -import { createLogger } from '../../core/logger.js'; -import { countByAction } from '../../database/repositories/moderation-repository.js'; -import { countPolls } from '../../database/repositories/poll-repository.js'; -import { countOpenTickets } from '../../database/repositories/ticket-repository.js'; -import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; -import { baseEmbed, errorEmbed } from '../../ui/embeds.js'; - -const log = createLogger('stats'); - -export const access = ACCESS_LEVELS.USER; - -export const data = new SlashCommandBuilder() - .setName('stats') - .setDescription('Statistiques publiques') - .addSubcommand((sub) => sub.setName('discord').setDescription('Statistiques du serveur Discord')) - .addSubcommand((sub) => sub.setName('gitea').setDescription('Activité et indicateurs Gitea')) - .addSubcommand((sub) => sub.setName('fws').setDescription('Indicateurs FWS / FWS Arch')); - -const discordStatsEmbed = (interaction) => { - const guild = interaction.guild; - return baseEmbed() - .setTitle(`📊 Statistiques — ${guild.name}`) - .setThumbnail(guild.iconURL({ size: 128 })) - .addFields( - { name: 'Membres', value: String(guild.memberCount), inline: true }, - { name: 'Salons', value: String(guild.channels.cache.size), inline: true }, - { name: 'Rôles', value: String(guild.roles.cache.size), inline: true }, - { name: 'Boosts', value: String(guild.premiumSubscriptionCount ?? 0), inline: true }, - { name: 'Créé', value: ``, inline: true }, - { name: 'Latence', value: `${Math.round(interaction.client.ws.ping)} ms`, inline: true }, - ); -}; - -async function giteaStatsEmbed() { - const [issues, pulls, commits, releases] = await Promise.all([ - gitea.listIssues('state=open&type=issues&limit=50'), - gitea.listPullRequests('state=open&limit=50'), - gitea.listCommits(5), - gitea.listReleases(1), - ]); - - const latestCommits = asList(commits) - .slice(0, 5) - .map((commit) => `\`${commit.sha?.slice(0, 7)}\` ${commit.commit?.message?.split('\n')[0] ?? ''}`) - .join('\n'); - const release = asList(releases)[0]; - - const embed = baseEmbed(COLORS.gitea) - .setTitle('📈 Activité Gitea') - .setURL(repositoryUrl()) - .setDescription(latestCommits || 'Aucun commit récent pour le moment.') - .addFields( - { name: 'Issues ouvertes', value: String(asList(issues).length), inline: true }, - { name: 'PR ouvertes', value: String(asList(pulls).length), inline: true }, - ); - - if (release) - embed.addFields({ name: 'Dernière release', value: release.tag_name ?? 'inconnue', inline: true }); - return embed; -} - -/** Community activity stored locally, independent from Gitea availability (M11). */ -function fwsStatsEmbed(interaction) { - const actions = countByAction(interaction.guildId); - const total = actions.reduce((sum, row) => sum + row.count, 0); - - return baseEmbed(COLORS.gitea) - .setTitle('📈 Indicateurs FWS') - .addFields( - { name: 'Tickets ouverts', value: String(countOpenTickets(interaction.guildId)), inline: true }, - { name: 'Sondages créés', value: String(countPolls(interaction.guildId)), inline: true }, - { name: 'Actions de modération', value: String(total), inline: true }, - { name: 'Dépôt', value: repositoryUrl() || 'Non configuré' }, - ) - .setFooter({ text: 'Statistiques locales · FWS-Bot' }); -} - -/** `/stats` never fails because of Gitea: the API errors are caught (M11-T03). */ -export async function execute(interaction) { - const subcommand = interaction.options.getSubcommand(); - await interaction.deferReply(); - - if (subcommand === 'discord') { - await interaction.editReply({ embeds: [discordStatsEmbed(interaction)] }); - return; - } - - if (subcommand === 'fws') { - try { - const releases = asList(await gitea.listReleases(1)); - const embed = fwsStatsEmbed(interaction); - if (releases[0]) - embed.addFields({ name: 'Version FWS Arch', value: releases[0].tag_name ?? 'inconnue' }); - await interaction.editReply({ embeds: [embed] }); - } catch (error) { - log.warn('Gitea unavailable while building /stats fws', error); - await interaction.editReply({ embeds: [fwsStatsEmbed(interaction)] }); - } - return; - } - - try { - await interaction.editReply({ embeds: [await giteaStatsEmbed()] }); - } catch (error) { - log.error('Could not read Gitea stats', error); - await interaction.editReply({ - embeds: [ - errorEmbed( - 'Les statistiques Gitea ne répondent pas. Réessaie dans un instant — si ça continue, l’équipe peut vérifier `GITEA_URL` et `GITEA_TOKEN`. Le reste du bot fonctionne normalement.', - ), - ], - }); - } -} +import { SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { createLogger } from '../../core/logger.js'; +import { countByAction } from '../../database/repositories/moderation-repository.js'; +import { countPolls } from '../../database/repositories/poll-repository.js'; +import { countOpenTickets } from '../../database/repositories/ticket-repository.js'; +import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; +import { baseEmbed, errorEmbed } from '../../ui/embeds.js'; + +const log = createLogger('stats'); + +export const access = ACCESS_LEVELS.USER; + +export const data = new SlashCommandBuilder() + .setName('stats') + .setDescription('Statistiques publiques') + .addSubcommand((sub) => sub.setName('discord').setDescription('Statistiques du serveur Discord')) + .addSubcommand((sub) => sub.setName('gitea').setDescription('Activité et indicateurs Gitea')) + .addSubcommand((sub) => sub.setName('fws').setDescription('Indicateurs FWS / FWS Arch')); + +const discordStatsEmbed = (interaction) => { + const guild = interaction.guild; + return baseEmbed() + .setTitle(`📊 Statistiques — ${guild.name}`) + .setThumbnail(guild.iconURL({ size: 128 })) + .addFields( + { name: 'Membres', value: String(guild.memberCount), inline: true }, + { name: 'Salons', value: String(guild.channels.cache.size), inline: true }, + { name: 'Rôles', value: String(guild.roles.cache.size), inline: true }, + { name: 'Boosts', value: String(guild.premiumSubscriptionCount ?? 0), inline: true }, + { name: 'Créé', value: ``, inline: true }, + { name: 'Latence', value: `${Math.round(interaction.client.ws.ping)} ms`, inline: true }, + ); +}; + +async function giteaStatsEmbed() { + const [issues, pulls, commits, releases] = await Promise.all([ + gitea.listIssues('state=open&type=issues&limit=50'), + gitea.listPullRequests('state=open&limit=50'), + gitea.listCommits(5), + gitea.listReleases(1), + ]); + + const latestCommits = asList(commits) + .slice(0, 5) + .map((commit) => `\`${commit.sha?.slice(0, 7)}\` ${commit.commit?.message?.split('\n')[0] ?? ''}`) + .join('\n'); + const release = asList(releases)[0]; + + const embed = baseEmbed(COLORS.gitea) + .setTitle('📈 Activité Gitea') + .setURL(repositoryUrl()) + .setDescription(latestCommits || 'Aucun commit récent pour le moment.') + .addFields( + { name: 'Issues ouvertes', value: String(asList(issues).length), inline: true }, + { name: 'PR ouvertes', value: String(asList(pulls).length), inline: true }, + ); + + if (release) + embed.addFields({ name: 'Dernière release', value: release.tag_name ?? 'inconnue', inline: true }); + return embed; +} + +/** Community activity stored locally, independent from Gitea availability (M11). */ +function fwsStatsEmbed(interaction) { + const actions = countByAction(interaction.guildId); + const total = actions.reduce((sum, row) => sum + row.count, 0); + + return baseEmbed(COLORS.gitea) + .setTitle('📈 Indicateurs FWS') + .addFields( + { name: 'Tickets ouverts', value: String(countOpenTickets(interaction.guildId)), inline: true }, + { name: 'Sondages créés', value: String(countPolls(interaction.guildId)), inline: true }, + { name: 'Actions de modération', value: String(total), inline: true }, + { name: 'Dépôt', value: repositoryUrl() || 'Non configuré' }, + ) + .setFooter({ text: 'Statistiques locales · FWS-Bot' }); +} + +/** `/stats` never fails because of Gitea: the API errors are caught (M11-T03). */ +export async function execute(interaction) { + const subcommand = interaction.options.getSubcommand(); + await interaction.deferReply(); + + if (subcommand === 'discord') { + await interaction.editReply({ embeds: [discordStatsEmbed(interaction)] }); + return; + } + + if (subcommand === 'fws') { + try { + const releases = asList(await gitea.listReleases(1)); + const embed = fwsStatsEmbed(interaction); + if (releases[0]) + embed.addFields({ name: 'Version FWS Arch', value: releases[0].tag_name ?? 'inconnue' }); + await interaction.editReply({ embeds: [embed] }); + } catch (error) { + log.warn('Gitea unavailable while building /stats fws', error); + await interaction.editReply({ embeds: [fwsStatsEmbed(interaction)] }); + } + return; + } + + try { + await interaction.editReply({ embeds: [await giteaStatsEmbed()] }); + } catch (error) { + log.error('Could not read Gitea stats', error); + await interaction.editReply({ + embeds: [ + errorEmbed( + 'Les statistiques Gitea ne répondent pas. Réessaie dans un instant — si ça continue, l’équipe peut vérifier `GITEA_URL` et `GITEA_TOKEN`. Le reste du bot fonctionne normalement.', + ), + ], + }); + } +} diff --git a/src/commands/fws/fws.js b/src/commands/fws/fws.js index 19e612e..35bb0c3 100644 --- a/src/commands/fws/fws.js +++ b/src/commands/fws/fws.js @@ -1,238 +1,238 @@ -import { SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; -import { env } from '../../config/env.js'; -import { createLogger } from '../../core/logger.js'; -import { getSetting } from '../../database/repositories/settings-repository.js'; -import { countOpenTickets } from '../../database/repositories/ticket-repository.js'; -import { asList, gitea, isGiteaConfigured, repositoryUrl } from '../../services/gitea/gitea-client.js'; -import { releaseEmbed } from '../../services/gitea/gitea-embeds.js'; -import { replyGiteaFailure } from '../../services/gitea/gitea-modals.js'; -import { linkButtons } from '../../ui/buttons.js'; -import { baseEmbed, errorEmbed, infoEmbed } from '../../ui/embeds.js'; - -const log = createLogger('fws'); - -export const access = ACCESS_LEVELS.USER; - -export const data = new SlashCommandBuilder() - .setName('fws') - .setDescription('Informations sur FWS et FWS Arch') - .addSubcommand((sub) => sub.setName('info').setDescription('Présente FWS et FWS Arch')) - .addSubcommand((sub) => sub.setName('version').setDescription('Version actuelle de FWS Arch')) - .addSubcommand((sub) => sub.setName('status').setDescription('État des services et projets')) - .addSubcommand((sub) => sub.setName('links').setDescription('Ressources officielles')) - .addSubcommand((sub) => - sub - .setName('changelog') - .setDescription('Nouveautés d’une version') - .addStringOption((option) => - option.setName('version').setDescription('Version souhaitée (la dernière par défaut)'), - ), - ); - -const officialLinks = () => [ - { label: 'Site', url: env.links.website }, - { label: 'Documentation', url: env.links.docs }, - { label: 'Dépôt FWS Arch', url: env.links.archRepo }, - { label: 'Gitea', url: env.gitea.url }, - { label: 'Discord', url: env.links.discordInvite }, -]; - -/** Guild settings are stored as JSON in SQLite; a failure falls back to the default (M4-T07). */ -function readSetting(guildId, key, fallback = null) { - try { - return getSetting(guildId, key, fallback); - } catch (error) { - log.debug(`Could not read setting ${key}`, error); - return fallback; - } -} - -const DEFAULT_PRESENTATION = - 'FWS est une organisation open source multi-projets.\n' + - "**FWS Arch** est un fork d'Arch Linux avec une surcouche conviviale."; - -async function latestRelease() { - try { - return await gitea.getLatestRelease(); - } catch { - return asList(await gitea.listReleases(1))[0] ?? null; - } -} - -async function showInfo(interaction) { - const configured = readSetting(interaction.guildId, 'fws.info', DEFAULT_PRESENTATION); - const description = typeof configured === 'string' && configured ? configured : DEFAULT_PRESENTATION; - await interaction.reply({ - embeds: [baseEmbed().setTitle('🚀 FWS & FWS Arch').setDescription(description)], - components: linkButtons(officialLinks()), - }); -} - -async function showVersion(interaction) { - const fallback = readSetting(interaction.guildId, 'fws.version', null); - if (!isGiteaConfigured()) { - await interaction.reply({ - embeds: [ - fallback - ? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`) - : errorEmbed( - 'La partie Gitea n’est pas encore configurée : je ne peux pas lire la dernière version. L’équipe peut la renseigner dans le `.env`.', - ), - ], - }); - return; - } - - await interaction.deferReply(); - try { - const release = await latestRelease(); - if (!release) { - await interaction.editReply({ - embeds: [ - fallback - ? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`) - : infoEmbed('📦 Version FWS Arch', 'Aucune release publiée pour le moment.'), - ], - }); - return; - } - - await interaction.editReply({ - embeds: [releaseEmbed(release, { withNotes: false })], - components: release.html_url ? linkButtons([{ label: 'Notes de version', url: release.html_url }]) : [], - }); - } catch (error) { - await replyGiteaFailure(interaction, error); - } -} - -async function showStatus(interaction) { - await interaction.deferReply(); - - const giteaConfigured = isGiteaConfigured(); - const giteaReachable = giteaConfigured - ? await gitea - .listReleases(1) - .then(() => true) - .catch(() => false) - : false; - - let openTickets = null; - try { - openTickets = countOpenTickets(interaction.guildId); - } catch (error) { - log.warn('Database unavailable while building /fws status', error); - } - - const uptime = Math.floor(process.uptime()); - const embed = baseEmbed(COLORS.info) - .setTitle('🩺 État des services') - .addFields( - { - name: 'API Gitea', - value: !giteaConfigured - ? '⚙️ Pas encore configurée' - : giteaReachable - ? `✅ En ligne — ${repositoryUrl()}` - : '❌ Injoignable pour le moment', - inline: false, - }, - { - name: 'Webhooks Gitea', - value: env.webhook.enabled ? '✅ Actifs' : '⚙️ Désactivés (`WEBHOOK_ENABLED=false`)', - inline: false, - }, - { - name: 'Base SQLite', - value: - openTickets === null - ? '❌ Indisponible pour le moment' - : `✅ Accessible — ${openTickets} ticket(s) ouvert(s)`, - inline: false, - }, - { - name: 'Discord', - value: `✅ Connecté — ${Math.round(interaction.client.ws.ping)} ms`, - inline: false, - }, - { name: 'En ligne depuis', value: `` }, - ); - - await interaction.editReply({ embeds: [embed] }); -} - -async function showChangelog(interaction) { - const version = interaction.options.getString('version'); - if (!isGiteaConfigured()) { - await interaction.reply({ - embeds: [ - errorEmbed( - 'La partie Gitea n’est pas encore configurée : le changelog arrivera dès qu’elle sera branchée.', - ), - ], - }); - return; - } - - await interaction.deferReply(); - try { - const release = version ? await gitea.getReleaseByTag(version) : await latestRelease(); - if (!release) { - await interaction.editReply({ - embeds: [ - infoEmbed( - '📜 Changelog', - `Je ne trouve aucune release pour **${version}** : \`/gitea release\` liste les versions existantes.`, - ), - ], - }); - return; - } - - await interaction.editReply({ - embeds: [releaseEmbed(release)], - components: release.html_url ? linkButtons([{ label: 'Ouvrir sur Gitea', url: release.html_url }]) : [], - }); - } catch (error) { - if (version) { - log.warn(`Release ${version} not found`, error); - await interaction.editReply({ - embeds: [ - infoEmbed( - '📜 Changelog', - `Cette version **${version}** n’existe pas dans les releases Gitea : \`/gitea release\` liste celles qui existent.`, - ), - ], - }); - return; - } - await replyGiteaFailure(interaction, error); - } -} - -/** Static presentation plus live data from Gitea (M4). */ -export async function execute(interaction) { - switch (interaction.options.getSubcommand()) { - case 'info': - await showInfo(interaction); - return; - case 'links': - await interaction.reply({ - embeds: [baseEmbed().setTitle('🔗 Liens officiels FWS')], - components: linkButtons(officialLinks()), - }); - return; - case 'version': - await showVersion(interaction); - return; - case 'status': - await showStatus(interaction); - return; - case 'changelog': - await showChangelog(interaction); - return; - default: - return; - } -} +import { SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { getSetting } from '../../database/repositories/settings-repository.js'; +import { countOpenTickets } from '../../database/repositories/ticket-repository.js'; +import { asList, gitea, isGiteaConfigured, repositoryUrl } from '../../services/gitea/gitea-client.js'; +import { releaseEmbed } from '../../services/gitea/gitea-embeds.js'; +import { replyGiteaFailure } from '../../services/gitea/gitea-modals.js'; +import { linkButtons } from '../../ui/buttons.js'; +import { baseEmbed, errorEmbed, infoEmbed } from '../../ui/embeds.js'; + +const log = createLogger('fws'); + +export const access = ACCESS_LEVELS.USER; + +export const data = new SlashCommandBuilder() + .setName('fws') + .setDescription('Informations sur FWS et FWS Arch') + .addSubcommand((sub) => sub.setName('info').setDescription('Présente FWS et FWS Arch')) + .addSubcommand((sub) => sub.setName('version').setDescription('Version actuelle de FWS Arch')) + .addSubcommand((sub) => sub.setName('status').setDescription('État des services et projets')) + .addSubcommand((sub) => sub.setName('links').setDescription('Ressources officielles')) + .addSubcommand((sub) => + sub + .setName('changelog') + .setDescription('Nouveautés d’une version') + .addStringOption((option) => + option.setName('version').setDescription('Version souhaitée (la dernière par défaut)'), + ), + ); + +const officialLinks = () => [ + { label: 'Site', url: env.links.website }, + { label: 'Documentation', url: env.links.docs }, + { label: 'Dépôt FWS Arch', url: env.links.archRepo }, + { label: 'Gitea', url: env.gitea.url }, + { label: 'Discord', url: env.links.discordInvite }, +]; + +/** Guild settings are stored as JSON in SQLite; a failure falls back to the default (M4-T07). */ +function readSetting(guildId, key, fallback = null) { + try { + return getSetting(guildId, key, fallback); + } catch (error) { + log.debug(`Could not read setting ${key}`, error); + return fallback; + } +} + +const DEFAULT_PRESENTATION = + 'FWS est une organisation open source multi-projets.\n' + + "**FWS Arch** est un fork d'Arch Linux avec une surcouche conviviale."; + +async function latestRelease() { + try { + return await gitea.getLatestRelease(); + } catch { + return asList(await gitea.listReleases(1))[0] ?? null; + } +} + +async function showInfo(interaction) { + const configured = readSetting(interaction.guildId, 'fws.info', DEFAULT_PRESENTATION); + const description = typeof configured === 'string' && configured ? configured : DEFAULT_PRESENTATION; + await interaction.reply({ + embeds: [baseEmbed().setTitle('🚀 FWS & FWS Arch').setDescription(description)], + components: linkButtons(officialLinks()), + }); +} + +async function showVersion(interaction) { + const fallback = readSetting(interaction.guildId, 'fws.version', null); + if (!isGiteaConfigured()) { + await interaction.reply({ + embeds: [ + fallback + ? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`) + : errorEmbed( + 'La partie Gitea n’est pas encore configurée : je ne peux pas lire la dernière version. L’équipe peut la renseigner dans le `.env`.', + ), + ], + }); + return; + } + + await interaction.deferReply(); + try { + const release = await latestRelease(); + if (!release) { + await interaction.editReply({ + embeds: [ + fallback + ? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`) + : infoEmbed('📦 Version FWS Arch', 'Aucune release publiée pour le moment.'), + ], + }); + return; + } + + await interaction.editReply({ + embeds: [releaseEmbed(release, { withNotes: false })], + components: release.html_url ? linkButtons([{ label: 'Notes de version', url: release.html_url }]) : [], + }); + } catch (error) { + await replyGiteaFailure(interaction, error); + } +} + +async function showStatus(interaction) { + await interaction.deferReply(); + + const giteaConfigured = isGiteaConfigured(); + const giteaReachable = giteaConfigured + ? await gitea + .listReleases(1) + .then(() => true) + .catch(() => false) + : false; + + let openTickets = null; + try { + openTickets = countOpenTickets(interaction.guildId); + } catch (error) { + log.warn('Database unavailable while building /fws status', error); + } + + const uptime = Math.floor(process.uptime()); + const embed = baseEmbed(COLORS.info) + .setTitle('🩺 État des services') + .addFields( + { + name: 'API Gitea', + value: !giteaConfigured + ? '⚙️ Pas encore configurée' + : giteaReachable + ? `✅ En ligne — ${repositoryUrl()}` + : '❌ Injoignable pour le moment', + inline: false, + }, + { + name: 'Webhooks Gitea', + value: env.webhook.enabled ? '✅ Actifs' : '⚙️ Désactivés (`WEBHOOK_ENABLED=false`)', + inline: false, + }, + { + name: 'Base SQLite', + value: + openTickets === null + ? '❌ Indisponible pour le moment' + : `✅ Accessible — ${openTickets} ticket(s) ouvert(s)`, + inline: false, + }, + { + name: 'Discord', + value: `✅ Connecté — ${Math.round(interaction.client.ws.ping)} ms`, + inline: false, + }, + { name: 'En ligne depuis', value: `` }, + ); + + await interaction.editReply({ embeds: [embed] }); +} + +async function showChangelog(interaction) { + const version = interaction.options.getString('version'); + if (!isGiteaConfigured()) { + await interaction.reply({ + embeds: [ + errorEmbed( + 'La partie Gitea n’est pas encore configurée : le changelog arrivera dès qu’elle sera branchée.', + ), + ], + }); + return; + } + + await interaction.deferReply(); + try { + const release = version ? await gitea.getReleaseByTag(version) : await latestRelease(); + if (!release) { + await interaction.editReply({ + embeds: [ + infoEmbed( + '📜 Changelog', + `Je ne trouve aucune release pour **${version}** : \`/gitea release\` liste les versions existantes.`, + ), + ], + }); + return; + } + + await interaction.editReply({ + embeds: [releaseEmbed(release)], + components: release.html_url ? linkButtons([{ label: 'Ouvrir sur Gitea', url: release.html_url }]) : [], + }); + } catch (error) { + if (version) { + log.warn(`Release ${version} not found`, error); + await interaction.editReply({ + embeds: [ + infoEmbed( + '📜 Changelog', + `Cette version **${version}** n’existe pas dans les releases Gitea : \`/gitea release\` liste celles qui existent.`, + ), + ], + }); + return; + } + await replyGiteaFailure(interaction, error); + } +} + +/** Static presentation plus live data from Gitea (M4). */ +export async function execute(interaction) { + switch (interaction.options.getSubcommand()) { + case 'info': + await showInfo(interaction); + return; + case 'links': + await interaction.reply({ + embeds: [baseEmbed().setTitle('🔗 Liens officiels FWS')], + components: linkButtons(officialLinks()), + }); + return; + case 'version': + await showVersion(interaction); + return; + case 'status': + await showStatus(interaction); + return; + case 'changelog': + await showChangelog(interaction); + return; + default: + return; + } +} diff --git a/src/commands/general/help.js b/src/commands/general/help.js index 889b3fd..c2b0443 100644 --- a/src/commands/general/help.js +++ b/src/commands/general/help.js @@ -1,25 +1,25 @@ -import { MessageFlags, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js'; -import { getAccessLevel } from '../../core/permissions.js'; -import { baseEmbed, bullets } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.USER; - -export const data = new SlashCommandBuilder() - .setName('help') - .setDescription('Affiche les commandes accessibles selon ton rôle'); - -export async function execute(interaction) { - const level = getAccessLevel(interaction.member); - const lines = interaction.client.commands - .filter((command) => (command.access ?? ACCESS_LEVELS.USER) <= level) - .map((command) => `\`/${command.data.name}\` — ${command.data.description}`) - .sort(); - - const embed = baseEmbed() - .setTitle('🤖 Tes commandes') - .setDescription( - `Tu es au niveau **${ACCESS_LABELS[level]}**. Voici ce que tu peux lancer :\n\n${bullets(lines)}`, - ); - await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); -} +import { MessageFlags, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js'; +import { getAccessLevel } from '../../core/permissions.js'; +import { baseEmbed, bullets } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.USER; + +export const data = new SlashCommandBuilder() + .setName('help') + .setDescription('Affiche les commandes accessibles selon ton rôle'); + +export async function execute(interaction) { + const level = getAccessLevel(interaction.member); + const lines = interaction.client.commands + .filter((command) => (command.access ?? ACCESS_LEVELS.USER) <= level) + .map((command) => `\`/${command.data.name}\` — ${command.data.description}`) + .sort(); + + const embed = baseEmbed() + .setTitle('🤖 Tes commandes') + .setDescription( + `Tu es au niveau **${ACCESS_LABELS[level]}**. Voici ce que tu peux lancer :\n\n${bullets(lines)}`, + ); + await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); +} diff --git a/src/commands/general/status.js b/src/commands/general/status.js index 70ec418..8e3f21c 100644 --- a/src/commands/general/status.js +++ b/src/commands/general/status.js @@ -1,153 +1,153 @@ -import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS } from '../../config/constants.js'; -import { - addBotStatus, - applyBotStatus, - applyStatusIfAlone, - clearBotStatusList, - FALLBACK_STATUS, - formatSeconds, - removeBotStatus, - ROTATION_MAX_SECONDS, - ROTATION_MIN_SECONDS, - saveRotationSeconds, - STATUS_TYPE_CHOICES, - statusAddedEmbed, - statusListEmbed, - toggleBotStatus, -} from '../../services/status/bot-status-service.js'; -import { successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.STAFF; - -const idOption = (option) => - option.setName('id').setDescription('Numéro affiché par /status list').setRequired(true).setMinValue(1); - -export const data = new SlashCommandBuilder() - .setName('status') - .setDescription('Statuts affichés sous le nom du bot') - .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild) - .addSubcommand((sub) => - sub - .setName('add') - .setDescription('Ajouter un statut à la rotation') - .addStringOption((option) => - option - .setName('text') - .setDescription('Texte affiché, par exemple « les tickets ouverts en un clic »') - .setRequired(true) - .setMaxLength(128), - ) - .addStringOption((option) => - option - .setName('type') - .setDescription('Type d’activité (regarde par défaut)') - .addChoices(...STATUS_TYPE_CHOICES), - ) - .addStringOption((option) => - option.setName('url').setDescription('Lien exigé par le type « en direct »'), - ), - ) - .addSubcommand((sub) => sub.setName('list').setDescription('Voir les statuts enregistrés')) - .addSubcommand((sub) => - sub.setName('remove').setDescription('Retirer un statut de la rotation').addIntegerOption(idOption), - ) - .addSubcommand((sub) => - sub.setName('enable').setDescription('Remettre un statut en rotation').addIntegerOption(idOption), - ) - .addSubcommand((sub) => - sub.setName('disable').setDescription('Mettre un statut en pause').addIntegerOption(idOption), - ) - .addSubcommand((sub) => - sub - .setName('interval') - .setDescription('Rythme de la rotation') - .addIntegerOption((option) => - option - .setName('seconds') - .setDescription('Secondes entre deux changements') - .setRequired(true) - .setMinValue(ROTATION_MIN_SECONDS) - .setMaxValue(ROTATION_MAX_SECONDS), - ), - ) - .addSubcommand((sub) => - sub.setName('clear').setDescription('Vider la liste et revenir au statut par défaut'), - ); - -const reply = (interaction, embed) => interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); - -/** The bot presence is global, but the rotation delay is stored per guild like other settings (M15). */ -export async function execute(interaction) { - const subcommand = interaction.options.getSubcommand(); - - if (subcommand === 'list') { - await reply(interaction, statusListEmbed({ guildId: interaction.guildId })); - return; - } - - if (subcommand === 'add') { - const status = addBotStatus({ - text: interaction.options.getString('text', true), - type: interaction.options.getString('type') ?? 'watching', - url: interaction.options.getString('url'), - createdBy: interaction.user.id, - }); - // A single status is shown right away: an addition should never wait for the next turn. - const applied = applyStatusIfAlone(interaction.client) !== null; - await reply(interaction, statusAddedEmbed(status, { applied })); - return; - } - - if (subcommand === 'interval') { - const seconds = saveRotationSeconds( - interaction.options.getInteger('seconds', true), - interaction.guildId, - interaction.user.id, - ); - await reply( - interaction, - successEmbed( - `C’est noté : les statuts changeront toutes les **${formatSeconds(seconds)}**. Ça prend effet tout de suite, sans redémarrage.`, - ), - ); - return; - } - - if (subcommand === 'clear') { - const removed = clearBotStatusList(); - applyBotStatus(interaction.client); - await reply( - interaction, - successEmbed( - removed === 0 - ? `La liste était déjà vide : j’affiche « ${FALLBACK_STATUS.text} ».` - : `C’est fait : ${removed} statut(s) supprimé(s). J’affiche de nouveau « ${FALLBACK_STATUS.text} » en attendant les prochains.`, - ), - ); - return; - } - - const id = interaction.options.getInteger('id', true); - - if (subcommand === 'remove') { - const status = removeBotStatus(id); - await reply( - interaction, - successEmbed(`C’est fait : « ${status.text} » ne fait plus partie de la rotation.`), - ); - return; - } - - const enabled = subcommand === 'enable'; - const status = toggleBotStatus(id, enabled); - if (enabled) applyStatusIfAlone(interaction.client); - await reply( - interaction, - successEmbed( - enabled - ? `« ${status.text} » reprend sa place dans la rotation.` - : `« ${status.text} » est en pause : il reste dans la liste, mais ne s’affiche plus.`, - ), - ); -} +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { + addBotStatus, + applyBotStatus, + applyStatusIfAlone, + clearBotStatusList, + FALLBACK_STATUS, + formatSeconds, + removeBotStatus, + ROTATION_MAX_SECONDS, + ROTATION_MIN_SECONDS, + saveRotationSeconds, + STATUS_TYPE_CHOICES, + statusAddedEmbed, + statusListEmbed, + toggleBotStatus, +} from '../../services/status/bot-status-service.js'; +import { successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.STAFF; + +const idOption = (option) => + option.setName('id').setDescription('Numéro affiché par /status list').setRequired(true).setMinValue(1); + +export const data = new SlashCommandBuilder() + .setName('status') + .setDescription('Statuts affichés sous le nom du bot') + .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild) + .addSubcommand((sub) => + sub + .setName('add') + .setDescription('Ajouter un statut à la rotation') + .addStringOption((option) => + option + .setName('text') + .setDescription('Texte affiché, par exemple « les tickets ouverts en un clic »') + .setRequired(true) + .setMaxLength(128), + ) + .addStringOption((option) => + option + .setName('type') + .setDescription('Type d’activité (regarde par défaut)') + .addChoices(...STATUS_TYPE_CHOICES), + ) + .addStringOption((option) => + option.setName('url').setDescription('Lien exigé par le type « en direct »'), + ), + ) + .addSubcommand((sub) => sub.setName('list').setDescription('Voir les statuts enregistrés')) + .addSubcommand((sub) => + sub.setName('remove').setDescription('Retirer un statut de la rotation').addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub.setName('enable').setDescription('Remettre un statut en rotation').addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub.setName('disable').setDescription('Mettre un statut en pause').addIntegerOption(idOption), + ) + .addSubcommand((sub) => + sub + .setName('interval') + .setDescription('Rythme de la rotation') + .addIntegerOption((option) => + option + .setName('seconds') + .setDescription('Secondes entre deux changements') + .setRequired(true) + .setMinValue(ROTATION_MIN_SECONDS) + .setMaxValue(ROTATION_MAX_SECONDS), + ), + ) + .addSubcommand((sub) => + sub.setName('clear').setDescription('Vider la liste et revenir au statut par défaut'), + ); + +const reply = (interaction, embed) => interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); + +/** The bot presence is global, but the rotation delay is stored per guild like other settings (M15). */ +export async function execute(interaction) { + const subcommand = interaction.options.getSubcommand(); + + if (subcommand === 'list') { + await reply(interaction, statusListEmbed({ guildId: interaction.guildId })); + return; + } + + if (subcommand === 'add') { + const status = addBotStatus({ + text: interaction.options.getString('text', true), + type: interaction.options.getString('type') ?? 'watching', + url: interaction.options.getString('url'), + createdBy: interaction.user.id, + }); + // A single status is shown right away: an addition should never wait for the next turn. + const applied = applyStatusIfAlone(interaction.client) !== null; + await reply(interaction, statusAddedEmbed(status, { applied })); + return; + } + + if (subcommand === 'interval') { + const seconds = saveRotationSeconds( + interaction.options.getInteger('seconds', true), + interaction.guildId, + interaction.user.id, + ); + await reply( + interaction, + successEmbed( + `C’est noté : les statuts changeront toutes les **${formatSeconds(seconds)}**. Ça prend effet tout de suite, sans redémarrage.`, + ), + ); + return; + } + + if (subcommand === 'clear') { + const removed = clearBotStatusList(); + applyBotStatus(interaction.client); + await reply( + interaction, + successEmbed( + removed === 0 + ? `La liste était déjà vide : j’affiche « ${FALLBACK_STATUS.text} ».` + : `C’est fait : ${removed} statut(s) supprimé(s). J’affiche de nouveau « ${FALLBACK_STATUS.text} » en attendant les prochains.`, + ), + ); + return; + } + + const id = interaction.options.getInteger('id', true); + + if (subcommand === 'remove') { + const status = removeBotStatus(id); + await reply( + interaction, + successEmbed(`C’est fait : « ${status.text} » ne fait plus partie de la rotation.`), + ); + return; + } + + const enabled = subcommand === 'enable'; + const status = toggleBotStatus(id, enabled); + if (enabled) applyStatusIfAlone(interaction.client); + await reply( + interaction, + successEmbed( + enabled + ? `« ${status.text} » reprend sa place dans la rotation.` + : `« ${status.text} » est en pause : il reste dans la liste, mais ne s’affiche plus.`, + ), + ); +} diff --git a/src/commands/gitea/gitea.js b/src/commands/gitea/gitea.js index 99d035f..54c65ab 100644 --- a/src/commands/gitea/gitea.js +++ b/src/commands/gitea/gitea.js @@ -1,74 +1,74 @@ -import { SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; -import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; -import { replyGiteaFailure, assertGiteaConfigured } from '../../services/gitea/gitea-modals.js'; -import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.USER; - -export const data = new SlashCommandBuilder() - .setName('gitea') - .setDescription('Activité Gitea de FWS Arch') - .addSubcommand((sub) => sub.setName('activity').setDescription('Commits, issues et PR récents')) - .addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles')); - -const commitLines = (commits) => - bullets( - asList(commits) - .slice(0, 5) - .map((commit) => { - const message = commit.commit?.message?.split('\n')[0] ?? '(sans message)'; - return `\`${commit.sha?.slice(0, 7)}\` ${message} — *${commit.commit?.author?.name ?? 'un compte inconnu'}*`; - }), - ); - -/** Read-only summaries of the repository (M5-T06 / M5-T07). */ -export async function execute(interaction) { - assertGiteaConfigured(); - await interaction.deferReply(); - - try { - if (interaction.options.getSubcommand() === 'release') { - const releases = asList(await gitea.listReleases(5)); - if (releases.length === 0) { - await interaction.editReply({ embeds: [successEmbed('Aucune release publiée pour le moment.')] }); - return; - } - - const embed = baseEmbed(COLORS.gitea) - .setTitle('📦 Releases FWS Arch') - .setURL(repositoryUrl()) - .setDescription( - releases - .map((release) => { - const date = release.published_at - ? `` - : 'date inconnue'; - const tag = release.html_url ? `[${release.tag_name}](${release.html_url})` : release.tag_name; - return `${release.prerelease ? '🧪' : '📦'} **${tag}** — ${release.name || 'sans titre'} · ${date}`; - }) - .join('\n'), - ); - await interaction.editReply({ embeds: [embed] }); - return; - } - - const [issues, pulls, commits] = await Promise.all([ - gitea.listIssues('state=open&type=issues&limit=50'), - gitea.listPullRequests('state=open&limit=50'), - gitea.listCommits(5), - ]); - - const embed = baseEmbed(COLORS.gitea) - .setTitle('📈 Activité récente') - .setURL(repositoryUrl()) - .setDescription(commitLines(commits) || 'Aucun commit récent pour le moment.') - .addFields( - { name: 'Issues ouvertes', value: String(asList(issues).length), inline: true }, - { name: 'PR ouvertes', value: String(asList(pulls).length), inline: true }, - ); - await interaction.editReply({ embeds: [embed] }); - } catch (error) { - await replyGiteaFailure(interaction, error); - } -} +import { SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; +import { replyGiteaFailure, assertGiteaConfigured } from '../../services/gitea/gitea-modals.js'; +import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.USER; + +export const data = new SlashCommandBuilder() + .setName('gitea') + .setDescription('Activité Gitea de FWS Arch') + .addSubcommand((sub) => sub.setName('activity').setDescription('Commits, issues et PR récents')) + .addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles')); + +const commitLines = (commits) => + bullets( + asList(commits) + .slice(0, 5) + .map((commit) => { + const message = commit.commit?.message?.split('\n')[0] ?? '(sans message)'; + return `\`${commit.sha?.slice(0, 7)}\` ${message} — *${commit.commit?.author?.name ?? 'un compte inconnu'}*`; + }), + ); + +/** Read-only summaries of the repository (M5-T06 / M5-T07). */ +export async function execute(interaction) { + assertGiteaConfigured(); + await interaction.deferReply(); + + try { + if (interaction.options.getSubcommand() === 'release') { + const releases = asList(await gitea.listReleases(5)); + if (releases.length === 0) { + await interaction.editReply({ embeds: [successEmbed('Aucune release publiée pour le moment.')] }); + return; + } + + const embed = baseEmbed(COLORS.gitea) + .setTitle('📦 Releases FWS Arch') + .setURL(repositoryUrl()) + .setDescription( + releases + .map((release) => { + const date = release.published_at + ? `` + : 'date inconnue'; + const tag = release.html_url ? `[${release.tag_name}](${release.html_url})` : release.tag_name; + return `${release.prerelease ? '🧪' : '📦'} **${tag}** — ${release.name || 'sans titre'} · ${date}`; + }) + .join('\n'), + ); + await interaction.editReply({ embeds: [embed] }); + return; + } + + const [issues, pulls, commits] = await Promise.all([ + gitea.listIssues('state=open&type=issues&limit=50'), + gitea.listPullRequests('state=open&limit=50'), + gitea.listCommits(5), + ]); + + const embed = baseEmbed(COLORS.gitea) + .setTitle('📈 Activité récente') + .setURL(repositoryUrl()) + .setDescription(commitLines(commits) || 'Aucun commit récent pour le moment.') + .addFields( + { name: 'Issues ouvertes', value: String(asList(issues).length), inline: true }, + { name: 'PR ouvertes', value: String(asList(pulls).length), inline: true }, + ); + await interaction.editReply({ embeds: [embed] }); + } catch (error) { + await replyGiteaFailure(interaction, error); + } +} diff --git a/src/commands/gitea/issue.js b/src/commands/gitea/issue.js index febdb38..7f98ecb 100644 --- a/src/commands/gitea/issue.js +++ b/src/commands/gitea/issue.js @@ -1,80 +1,80 @@ -import { SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; -import { UserFacingError } from '../../core/errors.js'; -import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; -import { issueEmbed } from '../../services/gitea/gitea-embeds.js'; -import { - assertGiteaConfigured, - openIssueModal, - replyGiteaFailure, -} from '../../services/gitea/gitea-modals.js'; -import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.USER; - -// TODO(M5-T03): make the required level for `create` configurable per guild. -export const subcommandAccess = { create: ACCESS_LEVELS.USER }; - -export const data = new SlashCommandBuilder() - .setName('issue') - .setDescription('Issues Gitea') - .addSubcommand((sub) => sub.setName('create').setDescription('Créer une issue Gitea')) - .addSubcommand((sub) => - sub - .setName('view') - .setDescription('Afficher une issue') - .addIntegerOption((option) => - option.setName('number').setDescription('Numéro de l’issue').setRequired(true).setMinValue(1), - ), - ) - .addSubcommand((sub) => sub.setName('list').setDescription('Lister les issues ouvertes')); - -/** Issues can be browsed and created straight from Discord (M5-T02 / M5-T03). */ -export async function execute(interaction) { - const subcommand = interaction.options.getSubcommand(); - - if (subcommand === 'create') { - await openIssueModal(interaction); - return; - } - - assertGiteaConfigured(); - await interaction.deferReply(); - - try { - if (subcommand === 'view') { - const issue = await gitea.getIssue(interaction.options.getInteger('number', true)); - if (!issue?.number) { - throw new UserFacingError( - 'Je ne trouve pas cette issue sur Gitea : vérifie son numéro avec `/issue list`.', - ); - } - await interaction.editReply({ embeds: [issueEmbed(issue)] }); - return; - } - - const issues = asList(await gitea.listIssues('state=open&type=issues&limit=15')); - if (issues.length === 0) { - await interaction.editReply({ - embeds: [successEmbed('Aucune issue ouverte : rien en attente, tout est traité 🎉')], - }); - return; - } - - const embed = baseEmbed(COLORS.gitea) - .setTitle('🐙 Issues ouvertes') - .setURL(`${repositoryUrl()}/issues`) - .setDescription( - bullets( - issues.map( - (issue) => - `**#${issue.number}** ${issue.title} — ouverte par *${issue.user?.login ?? 'un compte inconnu'}*`, - ), - ), - ) - .setFooter({ text: `${issues.length} issue(s) affichée(s)` }); - await interaction.editReply({ embeds: [embed] }); - } catch (error) { - await replyGiteaFailure(interaction, error); - } -} +import { SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { UserFacingError } from '../../core/errors.js'; +import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; +import { issueEmbed } from '../../services/gitea/gitea-embeds.js'; +import { + assertGiteaConfigured, + openIssueModal, + replyGiteaFailure, +} from '../../services/gitea/gitea-modals.js'; +import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.USER; + +// TODO(M5-T03): make the required level for `create` configurable per guild. +export const subcommandAccess = { create: ACCESS_LEVELS.USER }; + +export const data = new SlashCommandBuilder() + .setName('issue') + .setDescription('Issues Gitea') + .addSubcommand((sub) => sub.setName('create').setDescription('Créer une issue Gitea')) + .addSubcommand((sub) => + sub + .setName('view') + .setDescription('Afficher une issue') + .addIntegerOption((option) => + option.setName('number').setDescription('Numéro de l’issue').setRequired(true).setMinValue(1), + ), + ) + .addSubcommand((sub) => sub.setName('list').setDescription('Lister les issues ouvertes')); + +/** Issues can be browsed and created straight from Discord (M5-T02 / M5-T03). */ +export async function execute(interaction) { + const subcommand = interaction.options.getSubcommand(); + + if (subcommand === 'create') { + await openIssueModal(interaction); + return; + } + + assertGiteaConfigured(); + await interaction.deferReply(); + + try { + if (subcommand === 'view') { + const issue = await gitea.getIssue(interaction.options.getInteger('number', true)); + if (!issue?.number) { + throw new UserFacingError( + 'Je ne trouve pas cette issue sur Gitea : vérifie son numéro avec `/issue list`.', + ); + } + await interaction.editReply({ embeds: [issueEmbed(issue)] }); + return; + } + + const issues = asList(await gitea.listIssues('state=open&type=issues&limit=15')); + if (issues.length === 0) { + await interaction.editReply({ + embeds: [successEmbed('Aucune issue ouverte : rien en attente, tout est traité 🎉')], + }); + return; + } + + const embed = baseEmbed(COLORS.gitea) + .setTitle('🐙 Issues ouvertes') + .setURL(`${repositoryUrl()}/issues`) + .setDescription( + bullets( + issues.map( + (issue) => + `**#${issue.number}** ${issue.title} — ouverte par *${issue.user?.login ?? 'un compte inconnu'}*`, + ), + ), + ) + .setFooter({ text: `${issues.length} issue(s) affichée(s)` }); + await interaction.editReply({ embeds: [embed] }); + } catch (error) { + await replyGiteaFailure(interaction, error); + } +} diff --git a/src/commands/gitea/pr.js b/src/commands/gitea/pr.js index c9b7570..6ddea77 100644 --- a/src/commands/gitea/pr.js +++ b/src/commands/gitea/pr.js @@ -1,95 +1,95 @@ -import { SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; -import { UserFacingError } from '../../core/errors.js'; -import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; -import { pullRequestEmbed } from '../../services/gitea/gitea-embeds.js'; -import { - assertGiteaConfigured, - openPullRequestModal, - replyGiteaFailure, -} from '../../services/gitea/gitea-modals.js'; -import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.USER; -export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; - -export const data = new SlashCommandBuilder() - .setName('pr') - .setDescription('Pull requests Gitea') - .addSubcommand((sub) => - sub - .setName('create') - .setDescription('Créer une pull request') - .addStringOption((option) => - option - .setName('head') - .setDescription('Branche source, celle qui apporte les changements') - .setRequired(true), - ) - .addStringOption((option) => - option - .setName('base') - .setDescription('Branche cible, celle qui reçoit les changements') - .setRequired(true), - ), - ) - .addSubcommand((sub) => - sub - .setName('view') - .setDescription('Afficher une pull request') - .addIntegerOption((option) => - option.setName('number').setDescription('Numéro de la PR').setRequired(true).setMinValue(1), - ), - ) - .addSubcommand((sub) => sub.setName('list').setDescription('Lister les pull requests ouvertes')); - -/** The title and description are collected through a modal (M5-T04 / M5-T05). */ -export async function execute(interaction) { - const subcommand = interaction.options.getSubcommand(); - - if (subcommand === 'create') { - await openPullRequestModal(interaction); - return; - } - - assertGiteaConfigured(); - await interaction.deferReply(); - - try { - if (subcommand === 'view') { - const pull = await gitea.getPullRequest(interaction.options.getInteger('number', true)); - if (!pull?.number) { - throw new UserFacingError( - 'Je ne trouve pas cette pull request sur Gitea : vérifie son numéro avec `/pr list`.', - ); - } - await interaction.editReply({ embeds: [pullRequestEmbed(pull)] }); - return; - } - - const pulls = asList(await gitea.listPullRequests('state=open&limit=15')); - if (pulls.length === 0) { - await interaction.editReply({ - embeds: [successEmbed('Aucune pull request ouverte : rien à relire pour le moment 🎉')], - }); - return; - } - - const embed = baseEmbed(COLORS.gitea) - .setTitle('🐙 Pull requests ouvertes') - .setURL(`${repositoryUrl()}/pulls`) - .setDescription( - bullets( - pulls.map( - (pull) => - `**#${pull.number}** ${pull.title} — ${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'} ` + - `(proposée par *${pull.user?.login ?? 'un compte inconnu'}*)`, - ), - ), - ) - .setFooter({ text: `${pulls.length} PR affichée(s)` }); - await interaction.editReply({ embeds: [embed] }); - } catch (error) { - await replyGiteaFailure(interaction, error); - } -} +import { SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { UserFacingError } from '../../core/errors.js'; +import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; +import { pullRequestEmbed } from '../../services/gitea/gitea-embeds.js'; +import { + assertGiteaConfigured, + openPullRequestModal, + replyGiteaFailure, +} from '../../services/gitea/gitea-modals.js'; +import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.USER; +export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; + +export const data = new SlashCommandBuilder() + .setName('pr') + .setDescription('Pull requests Gitea') + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Créer une pull request') + .addStringOption((option) => + option + .setName('head') + .setDescription('Branche source, celle qui apporte les changements') + .setRequired(true), + ) + .addStringOption((option) => + option + .setName('base') + .setDescription('Branche cible, celle qui reçoit les changements') + .setRequired(true), + ), + ) + .addSubcommand((sub) => + sub + .setName('view') + .setDescription('Afficher une pull request') + .addIntegerOption((option) => + option.setName('number').setDescription('Numéro de la PR').setRequired(true).setMinValue(1), + ), + ) + .addSubcommand((sub) => sub.setName('list').setDescription('Lister les pull requests ouvertes')); + +/** The title and description are collected through a modal (M5-T04 / M5-T05). */ +export async function execute(interaction) { + const subcommand = interaction.options.getSubcommand(); + + if (subcommand === 'create') { + await openPullRequestModal(interaction); + return; + } + + assertGiteaConfigured(); + await interaction.deferReply(); + + try { + if (subcommand === 'view') { + const pull = await gitea.getPullRequest(interaction.options.getInteger('number', true)); + if (!pull?.number) { + throw new UserFacingError( + 'Je ne trouve pas cette pull request sur Gitea : vérifie son numéro avec `/pr list`.', + ); + } + await interaction.editReply({ embeds: [pullRequestEmbed(pull)] }); + return; + } + + const pulls = asList(await gitea.listPullRequests('state=open&limit=15')); + if (pulls.length === 0) { + await interaction.editReply({ + embeds: [successEmbed('Aucune pull request ouverte : rien à relire pour le moment 🎉')], + }); + return; + } + + const embed = baseEmbed(COLORS.gitea) + .setTitle('🐙 Pull requests ouvertes') + .setURL(`${repositoryUrl()}/pulls`) + .setDescription( + bullets( + pulls.map( + (pull) => + `**#${pull.number}** ${pull.title} — ${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'} ` + + `(proposée par *${pull.user?.login ?? 'un compte inconnu'}*)`, + ), + ), + ) + .setFooter({ text: `${pulls.length} PR affichée(s)` }); + await interaction.editReply({ embeds: [embed] }); + } catch (error) { + await replyGiteaFailure(interaction, error); + } +} diff --git a/src/commands/moderation/ban.js b/src/commands/moderation/ban.js index 08e8dc1..61cfa6f 100644 --- a/src/commands/moderation/ban.js +++ b/src/commands/moderation/ban.js @@ -1,56 +1,56 @@ -import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS } from '../../config/constants.js'; -import { - assertModerationTarget, - logModerationAction, - targetNoticeEmbed, -} from '../../services/moderation/moderation-service.js'; -import { successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.STAFF; - -export const data = new SlashCommandBuilder() - .setName('ban') - .setDescription('Bannir un membre') - .setDefaultMemberPermissions(PermissionFlagsBits.BanMembers) - .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) - .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)) - .addIntegerOption((option) => - option - .setName('delete_days') - .setDescription('Supprimer aussi les messages des N derniers jours (0 à 7)') - .setMinValue(0) - .setMaxValue(7), - ); - -/** Bans the user, whether or not they are still on the server (M8-T04 / M8-T09). */ -export async function execute(interaction) { - const user = interaction.options.getUser('user', true); - const reason = interaction.options.getString('reason'); - const deleteDays = interaction.options.getInteger('delete_days') ?? 0; - - const member = await interaction.guild.members.fetch(user.id).catch(() => null); - if (member) { - assertModerationTarget(interaction, member); - await member - .send({ - embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })], - }) - .catch(() => {}); - } - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - await interaction.guild.bans.create(user.id, { - reason: reason ?? `Bannissement demandé par ${interaction.user.tag}`, - deleteMessageSeconds: deleteDays * 86_400, - }); - - await logModerationAction(interaction, { action: 'ban', targetId: user.id, reason }); - await interaction.editReply({ - embeds: [ - successEmbed( - `C’est fait : **${user.tag}** ne peut plus revenir sur le serveur. L’historique reste consultable avec \`/mod logs\`.`, - ), - ], - }); -} +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { + assertModerationTarget, + logModerationAction, + targetNoticeEmbed, +} from '../../services/moderation/moderation-service.js'; +import { successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.STAFF; + +export const data = new SlashCommandBuilder() + .setName('ban') + .setDescription('Bannir un membre') + .setDefaultMemberPermissions(PermissionFlagsBits.BanMembers) + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) + .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)) + .addIntegerOption((option) => + option + .setName('delete_days') + .setDescription('Supprimer aussi les messages des N derniers jours (0 à 7)') + .setMinValue(0) + .setMaxValue(7), + ); + +/** Bans the user, whether or not they are still on the server (M8-T04 / M8-T09). */ +export async function execute(interaction) { + const user = interaction.options.getUser('user', true); + const reason = interaction.options.getString('reason'); + const deleteDays = interaction.options.getInteger('delete_days') ?? 0; + + const member = await interaction.guild.members.fetch(user.id).catch(() => null); + if (member) { + assertModerationTarget(interaction, member); + await member + .send({ + embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })], + }) + .catch(() => {}); + } + + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + await interaction.guild.bans.create(user.id, { + reason: reason ?? `Bannissement demandé par ${interaction.user.tag}`, + deleteMessageSeconds: deleteDays * 86_400, + }); + + await logModerationAction(interaction, { action: 'ban', targetId: user.id, reason }); + await interaction.editReply({ + embeds: [ + successEmbed( + `C’est fait : **${user.tag}** ne peut plus revenir sur le serveur. L’historique reste consultable avec \`/mod logs\`.`, + ), + ], + }); +} diff --git a/src/commands/moderation/clear.js b/src/commands/moderation/clear.js index cf3568c..17d6223 100644 --- a/src/commands/moderation/clear.js +++ b/src/commands/moderation/clear.js @@ -1,49 +1,49 @@ -import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS } from '../../config/constants.js'; -import { UserFacingError } from '../../core/errors.js'; -import { logModerationAction } from '../../services/moderation/moderation-service.js'; -import { successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.STAFF; - -export const data = new SlashCommandBuilder() - .setName('clear') - .setDescription('Supprimer des messages') - .setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages) - .addIntegerOption((option) => - option - .setName('amount') - .setDescription('Nombre de messages à supprimer (1 à 100)') - .setRequired(true) - .setMinValue(1) - .setMaxValue(100), - ); - -/** Bulk deletes messages in the current channel and logs it (M8-T05). */ -export async function execute(interaction) { - const amount = interaction.options.getInteger('amount', true); - if (!interaction.channel?.isTextBased() || !interaction.channel.bulkDelete) { - throw new UserFacingError( - 'Je ne peux pas supprimer plusieurs messages d’un coup ici : lance la commande dans un salon textuel.', - ); - } - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const deleted = await interaction.channel.bulkDelete(amount, true); - - await logModerationAction(interaction, { - action: 'clear', - targetId: null, - reason: `${deleted.size} message(s) supprimé(s) dans #${interaction.channel.name}`, - }); - await interaction.editReply({ - embeds: [ - successEmbed( - `C’est nettoyé : ${deleted.size} message(s) supprimé(s) dans <#${interaction.channelId}>.` + - (deleted.size < amount - ? '\n_Discord conserve les messages de plus de 14 jours : ils n’ont pas pu être retirés._' - : ''), - ), - ], - }); -} +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { UserFacingError } from '../../core/errors.js'; +import { logModerationAction } from '../../services/moderation/moderation-service.js'; +import { successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.STAFF; + +export const data = new SlashCommandBuilder() + .setName('clear') + .setDescription('Supprimer des messages') + .setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages) + .addIntegerOption((option) => + option + .setName('amount') + .setDescription('Nombre de messages à supprimer (1 à 100)') + .setRequired(true) + .setMinValue(1) + .setMaxValue(100), + ); + +/** Bulk deletes messages in the current channel and logs it (M8-T05). */ +export async function execute(interaction) { + const amount = interaction.options.getInteger('amount', true); + if (!interaction.channel?.isTextBased() || !interaction.channel.bulkDelete) { + throw new UserFacingError( + 'Je ne peux pas supprimer plusieurs messages d’un coup ici : lance la commande dans un salon textuel.', + ); + } + + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const deleted = await interaction.channel.bulkDelete(amount, true); + + await logModerationAction(interaction, { + action: 'clear', + targetId: null, + reason: `${deleted.size} message(s) supprimé(s) dans #${interaction.channel.name}`, + }); + await interaction.editReply({ + embeds: [ + successEmbed( + `C’est nettoyé : ${deleted.size} message(s) supprimé(s) dans <#${interaction.channelId}>.` + + (deleted.size < amount + ? '\n_Discord conserve les messages de plus de 14 jours : ils n’ont pas pu être retirés._' + : ''), + ), + ], + }); +} diff --git a/src/commands/moderation/kick.js b/src/commands/moderation/kick.js index 0c009cb..c42da02 100644 --- a/src/commands/moderation/kick.js +++ b/src/commands/moderation/kick.js @@ -1,44 +1,44 @@ -import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS } from '../../config/constants.js'; -import { - assertModerationTarget, - fetchTargetMember, - logModerationAction, - targetNoticeEmbed, -} from '../../services/moderation/moderation-service.js'; -import { successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.STAFF; - -export const data = new SlashCommandBuilder() - .setName('kick') - .setDescription('Expulser un membre du serveur') - .setDefaultMemberPermissions(PermissionFlagsBits.KickMembers) - .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) - .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)); - -/** Expels the member after the hierarchy checks (M8-T03 / M8-T06). */ -export async function execute(interaction) { - const user = interaction.options.getUser('user', true); - const reason = interaction.options.getString('reason'); - - const target = await fetchTargetMember(interaction, user.id); - assertModerationTarget(interaction, target); - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - await target - .send({ - embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })], - }) - .catch(() => {}); - await target.kick(reason ?? `Expulsion demandée par ${interaction.user.tag}`); - - await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason }); - await interaction.editReply({ - embeds: [ - successEmbed( - `C’est fait : **${target.user.tag}** ne fait plus partie du serveur. La personne peut revenir avec une nouvelle invitation.`, - ), - ], - }); -} +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { + assertModerationTarget, + fetchTargetMember, + logModerationAction, + targetNoticeEmbed, +} from '../../services/moderation/moderation-service.js'; +import { successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.STAFF; + +export const data = new SlashCommandBuilder() + .setName('kick') + .setDescription('Expulser un membre du serveur') + .setDefaultMemberPermissions(PermissionFlagsBits.KickMembers) + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) + .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)); + +/** Expels the member after the hierarchy checks (M8-T03 / M8-T06). */ +export async function execute(interaction) { + const user = interaction.options.getUser('user', true); + const reason = interaction.options.getString('reason'); + + const target = await fetchTargetMember(interaction, user.id); + assertModerationTarget(interaction, target); + + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + await target + .send({ + embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })], + }) + .catch(() => {}); + await target.kick(reason ?? `Expulsion demandée par ${interaction.user.tag}`); + + await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason }); + await interaction.editReply({ + embeds: [ + successEmbed( + `C’est fait : **${target.user.tag}** ne fait plus partie du serveur. La personne peut revenir avec une nouvelle invitation.`, + ), + ], + }); +} diff --git a/src/commands/moderation/mod.js b/src/commands/moderation/mod.js index bab4bc3..fad1278 100644 --- a/src/commands/moderation/mod.js +++ b/src/commands/moderation/mod.js @@ -1,55 +1,55 @@ -import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS, COLORS, MODERATION_ACTIONS } from '../../config/constants.js'; -import { listActions } from '../../database/repositories/moderation-repository.js'; -import { formatDuration } from '../../services/moderation/moderation-service.js'; -import { baseEmbed, infoEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.STAFF; - -const HISTORY_LIMIT = 15; - -export const data = new SlashCommandBuilder() - .setName('mod') - .setDescription('Outils de modération') - .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers) - .addSubcommand((sub) => - sub - .setName('logs') - .setDescription('Consulter les actions de modération') - .addUserOption((option) => option.setName('user').setDescription('Filtrer par membre')), - ); - -function formatEntry(row) { - const meta = MODERATION_ACTIONS[row.action]; - const target = row.target_id ? `<@${row.target_id}>` : 'salon'; - const duration = row.duration_ms ? ` pendant ${formatDuration(row.duration_ms)}` : ''; - return ( - `\`${row.created_at}\` **${meta?.label ?? row.action}** — ${target}${duration}\n` + - `↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}` - ); -} - -/** Reads the moderation history from SQLite (M8-T06). */ -export async function execute(interaction) { - const user = interaction.options.getUser('user'); - const actions = listActions({ - guildId: interaction.guildId, - targetId: user?.id ?? null, - limit: HISTORY_LIMIT, - }); - - const embed = - actions.length === 0 - ? infoEmbed( - '📜 Historique de modération', - user - ? `Rien à signaler concernant ${user} : aucune action de modération enregistrée.` - : 'Aucune action de modération enregistrée sur ce serveur, tout est calme.', - ) - : baseEmbed(COLORS.moderation) - .setTitle(user ? `📜 Historique de ${user.tag}` : '📜 Dernières actions de modération') - .setDescription(actions.map(formatEntry).join('\n\n')) - .setFooter({ text: `${actions.length} action(s) affichée(s)` }); - - await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); -} +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS, COLORS, MODERATION_ACTIONS } from '../../config/constants.js'; +import { listActions } from '../../database/repositories/moderation-repository.js'; +import { formatDuration } from '../../services/moderation/moderation-service.js'; +import { baseEmbed, infoEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.STAFF; + +const HISTORY_LIMIT = 15; + +export const data = new SlashCommandBuilder() + .setName('mod') + .setDescription('Outils de modération') + .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers) + .addSubcommand((sub) => + sub + .setName('logs') + .setDescription('Consulter les actions de modération') + .addUserOption((option) => option.setName('user').setDescription('Filtrer par membre')), + ); + +function formatEntry(row) { + const meta = MODERATION_ACTIONS[row.action]; + const target = row.target_id ? `<@${row.target_id}>` : 'salon'; + const duration = row.duration_ms ? ` pendant ${formatDuration(row.duration_ms)}` : ''; + return ( + `\`${row.created_at}\` **${meta?.label ?? row.action}** — ${target}${duration}\n` + + `↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}` + ); +} + +/** Reads the moderation history from SQLite (M8-T06). */ +export async function execute(interaction) { + const user = interaction.options.getUser('user'); + const actions = listActions({ + guildId: interaction.guildId, + targetId: user?.id ?? null, + limit: HISTORY_LIMIT, + }); + + const embed = + actions.length === 0 + ? infoEmbed( + '📜 Historique de modération', + user + ? `Rien à signaler concernant ${user} : aucune action de modération enregistrée.` + : 'Aucune action de modération enregistrée sur ce serveur, tout est calme.', + ) + : baseEmbed(COLORS.moderation) + .setTitle(user ? `📜 Historique de ${user.tag}` : '📜 Dernières actions de modération') + .setDescription(actions.map(formatEntry).join('\n\n')) + .setFooter({ text: `${actions.length} action(s) affichée(s)` }); + + await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); +} diff --git a/src/commands/moderation/mute.js b/src/commands/moderation/mute.js index 5e485c3..bb9b120 100644 --- a/src/commands/moderation/mute.js +++ b/src/commands/moderation/mute.js @@ -1,61 +1,61 @@ -import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS } from '../../config/constants.js'; -import { - assertModerationTarget, - fetchTargetMember, - formatDuration, - logModerationAction, - targetNoticeEmbed, -} from '../../services/moderation/moderation-service.js'; -import { successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.STAFF; - -export const data = new SlashCommandBuilder() - .setName('mute') - .setDescription('Restreindre temporairement un membre') - .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers) - .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) - .addIntegerOption((option) => - option - .setName('minutes') - .setDescription('Durée de la sanction, en minutes') - .setRequired(true) - .setMinValue(1) - .setMaxValue(40_320), - ) - .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)); - -/** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */ -export async function execute(interaction) { - const user = interaction.options.getUser('user', true); - const minutes = interaction.options.getInteger('minutes', true); - const reason = interaction.options.getString('reason'); - const durationMs = minutes * 60_000; - - const target = await fetchTargetMember(interaction, user.id); - assertModerationTarget(interaction, target); - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - await target.timeout(durationMs, reason ?? `Exclusion temporaire de ${minutes} minutes`); - - await logModerationAction(interaction, { - action: 'mute', - targetId: target.id, - reason, - durationMs, - }); - await target - .send({ - embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })], - }) - .catch(() => {}); - - await interaction.editReply({ - embeds: [ - successEmbed( - `C’est fait : **${target.user.tag}** est en exclusion temporaire pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`, - ), - ], - }); -} +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { + assertModerationTarget, + fetchTargetMember, + formatDuration, + logModerationAction, + targetNoticeEmbed, +} from '../../services/moderation/moderation-service.js'; +import { successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.STAFF; + +export const data = new SlashCommandBuilder() + .setName('mute') + .setDescription('Restreindre temporairement un membre') + .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers) + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) + .addIntegerOption((option) => + option + .setName('minutes') + .setDescription('Durée de la sanction, en minutes') + .setRequired(true) + .setMinValue(1) + .setMaxValue(40_320), + ) + .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)); + +/** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */ +export async function execute(interaction) { + const user = interaction.options.getUser('user', true); + const minutes = interaction.options.getInteger('minutes', true); + const reason = interaction.options.getString('reason'); + const durationMs = minutes * 60_000; + + const target = await fetchTargetMember(interaction, user.id); + assertModerationTarget(interaction, target); + + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + await target.timeout(durationMs, reason ?? `Exclusion temporaire de ${minutes} minutes`); + + await logModerationAction(interaction, { + action: 'mute', + targetId: target.id, + reason, + durationMs, + }); + await target + .send({ + embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })], + }) + .catch(() => {}); + + await interaction.editReply({ + embeds: [ + successEmbed( + `C’est fait : **${target.user.tag}** est en exclusion temporaire pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`, + ), + ], + }); +} diff --git a/src/commands/moderation/notify.js b/src/commands/moderation/notify.js index 7bd7706..5680819 100644 --- a/src/commands/moderation/notify.js +++ b/src/commands/moderation/notify.js @@ -1,105 +1,105 @@ -import { ChannelType, MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS, NOTIFICATION_TYPES } from '../../config/constants.js'; -import { UserFacingError } from '../../core/errors.js'; -import { - listNotificationChannels, - removeNotificationChannel, - setNotificationChannel, -} from '../../database/repositories/notification-repository.js'; -import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.STAFF; - -const TYPE_CHOICES = NOTIFICATION_TYPES.map((type) => ({ name: type, value: type })); - -export const data = new SlashCommandBuilder() - .setName('notify') - .setDescription('Configuration des salons de notification') - .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild) - .addSubcommand((sub) => - sub - .setName('set') - .setDescription('Associer un salon à un type de notification') - .addStringOption((option) => - option - .setName('type') - .setDescription('Type de notification') - .setRequired(true) - .addChoices(...TYPE_CHOICES), - ) - .addChannelOption((option) => - option - .setName('channel') - .setDescription('Salon de destination') - .setRequired(true) - .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement), - ), - ) - .addSubcommand((sub) => - sub - .setName('remove') - .setDescription('Revenir au salon par défaut de la configuration') - .addStringOption((option) => - option - .setName('type') - .setDescription('Type de notification') - .setRequired(true) - .addChoices(...TYPE_CHOICES), - ), - ) - .addSubcommand((sub) => sub.setName('list').setDescription('Afficher la configuration actuelle')); - -/** Per-guild notification routing stored in SQLite (M9-T01). */ -export async function execute(interaction) { - const subcommand = interaction.options.getSubcommand(); - - if (subcommand === 'set') { - const type = interaction.options.getString('type', true); - const channel = interaction.options.getChannel('channel', true); - setNotificationChannel({ guildId: interaction.guildId, type, channelId: channel.id }); - await interaction.reply({ - embeds: [ - successEmbed(`C’est noté : les notifications **${type}** partent maintenant dans <#${channel.id}>.`), - ], - flags: MessageFlags.Ephemeral, - }); - return; - } - - if (subcommand === 'remove') { - const type = interaction.options.getString('type', true); - const removed = removeNotificationChannel(interaction.guildId, type); - if (!removed) { - throw new UserFacingError( - `Le type **${type}** utilise déjà la configuration par défaut : il n’y a rien à retirer.`, - ); - } - await interaction.reply({ - embeds: [ - successEmbed(`C’est fait : les notifications **${type}** repassent à la configuration par défaut.`), - ], - flags: MessageFlags.Ephemeral, - }); - return; - } - - const overrides = new Map( - listNotificationChannels(interaction.guildId).map((row) => [row.type, row.channel_id]), - ); - const lines = NOTIFICATION_TYPES.map((type) => { - const channelId = overrides.get(type); - return channelId - ? `\`${type}\` → <#${channelId}> _(choisi sur ce serveur)_` - : `\`${type}\` → _configuration par défaut_`; - }); - - await interaction.reply({ - embeds: [ - baseEmbed() - .setTitle('🔔 Salons de notification') - .setDescription(`${bullets(lines)}\n\nPour changer une destination : \`/notify set\`.`) - .setFooter({ text: `Serveur ${interaction.guildId}` }), - ], - flags: MessageFlags.Ephemeral, - }); -} +import { ChannelType, MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS, NOTIFICATION_TYPES } from '../../config/constants.js'; +import { UserFacingError } from '../../core/errors.js'; +import { + listNotificationChannels, + removeNotificationChannel, + setNotificationChannel, +} from '../../database/repositories/notification-repository.js'; +import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.STAFF; + +const TYPE_CHOICES = NOTIFICATION_TYPES.map((type) => ({ name: type, value: type })); + +export const data = new SlashCommandBuilder() + .setName('notify') + .setDescription('Configuration des salons de notification') + .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild) + .addSubcommand((sub) => + sub + .setName('set') + .setDescription('Associer un salon à un type de notification') + .addStringOption((option) => + option + .setName('type') + .setDescription('Type de notification') + .setRequired(true) + .addChoices(...TYPE_CHOICES), + ) + .addChannelOption((option) => + option + .setName('channel') + .setDescription('Salon de destination') + .setRequired(true) + .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement), + ), + ) + .addSubcommand((sub) => + sub + .setName('remove') + .setDescription('Revenir au salon par défaut de la configuration') + .addStringOption((option) => + option + .setName('type') + .setDescription('Type de notification') + .setRequired(true) + .addChoices(...TYPE_CHOICES), + ), + ) + .addSubcommand((sub) => sub.setName('list').setDescription('Afficher la configuration actuelle')); + +/** Per-guild notification routing stored in SQLite (M9-T01). */ +export async function execute(interaction) { + const subcommand = interaction.options.getSubcommand(); + + if (subcommand === 'set') { + const type = interaction.options.getString('type', true); + const channel = interaction.options.getChannel('channel', true); + setNotificationChannel({ guildId: interaction.guildId, type, channelId: channel.id }); + await interaction.reply({ + embeds: [ + successEmbed(`C’est noté : les notifications **${type}** partent maintenant dans <#${channel.id}>.`), + ], + flags: MessageFlags.Ephemeral, + }); + return; + } + + if (subcommand === 'remove') { + const type = interaction.options.getString('type', true); + const removed = removeNotificationChannel(interaction.guildId, type); + if (!removed) { + throw new UserFacingError( + `Le type **${type}** utilise déjà la configuration par défaut : il n’y a rien à retirer.`, + ); + } + await interaction.reply({ + embeds: [ + successEmbed(`C’est fait : les notifications **${type}** repassent à la configuration par défaut.`), + ], + flags: MessageFlags.Ephemeral, + }); + return; + } + + const overrides = new Map( + listNotificationChannels(interaction.guildId).map((row) => [row.type, row.channel_id]), + ); + const lines = NOTIFICATION_TYPES.map((type) => { + const channelId = overrides.get(type); + return channelId + ? `\`${type}\` → <#${channelId}> _(choisi sur ce serveur)_` + : `\`${type}\` → _configuration par défaut_`; + }); + + await interaction.reply({ + embeds: [ + baseEmbed() + .setTitle('🔔 Salons de notification') + .setDescription(`${bullets(lines)}\n\nPour changer une destination : \`/notify set\`.`) + .setFooter({ text: `Serveur ${interaction.guildId}` }), + ], + flags: MessageFlags.Ephemeral, + }); +} diff --git a/src/commands/moderation/role.js b/src/commands/moderation/role.js index e1f674a..c9998ee 100644 --- a/src/commands/moderation/role.js +++ b/src/commands/moderation/role.js @@ -1,91 +1,91 @@ -import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS } from '../../config/constants.js'; -import { UserFacingError } from '../../core/errors.js'; -import { fetchTargetMember, logModerationAction } from '../../services/moderation/moderation-service.js'; -import { successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.STAFF; - -export const data = new SlashCommandBuilder() - .setName('role') - .setDescription('Gestion des rôles') - .setDefaultMemberPermissions(PermissionFlagsBits.ManageRoles) - .addSubcommand((sub) => - sub - .setName('set') - .setDescription('Attribuer ou retirer un rôle') - .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) - .addRoleOption((option) => option.setName('role').setDescription('Rôle').setRequired(true)) - .addStringOption((option) => - option - .setName('action') - .setDescription('Ajouter ou retirer le rôle') - .setRequired(true) - .addChoices( - { name: 'Ajouter le rôle', value: 'add' }, - { name: 'Retirer le rôle', value: 'remove' }, - ), - ), - ); - -/** Adds or removes a role after checking both hierarchies (M7-T05 / M3-T05). */ -export async function execute(interaction) { - const user = interaction.options.getUser('user', true); - const role = interaction.options.getRole('role', true); - const action = interaction.options.getString('action', true); - const adding = action === 'add'; - - if (role.id === interaction.guild.roles.everyone.id) { - throw new UserFacingError( - 'Le rôle @everyone ne s’attribue pas : il est porté par tout le monde à la fois.', - ); - } - if (role.managed) { - throw new UserFacingError( - 'Ce rôle appartient à une intégration : Discord le gère tout seul, je ne peux pas le modifier.', - ); - } - - const bot = interaction.guild.members.me; - if (bot && bot.roles.highest.comparePositionTo(role) <= 0) { - throw new UserFacingError( - 'Je ne peux pas gérer ce rôle : il est placé plus haut que le mien. Remonte mon rôle dans la hiérarchie du serveur, et je m’en occupe.', - ); - } - - const target = await fetchTargetMember(interaction, user.id); - const hasRole = target.roles.cache.has(role.id); - if (adding && hasRole) { - throw new UserFacingError(`Rien à faire : **${target.user.tag}** porte déjà le rôle ${role}.`); - } - if (!adding && !hasRole) { - throw new UserFacingError(`Rien à retirer : **${target.user.tag}** n’a pas le rôle ${role}.`); - } - - const isGuildOwner = interaction.guild.ownerId === interaction.user.id; - if (!isGuildOwner && interaction.member.roles.highest.comparePositionTo(role) <= 0) { - throw new UserFacingError( - 'Ce rôle est au même niveau (ou plus haut) que le tien : je ne peux pas y toucher. Demande à quelqu’un de plus haut dans la hiérarchie.', - ); - } - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - if (adding) { - await target.roles.add(role, `Ajouté par ${interaction.user.tag}`); - } else { - await target.roles.remove(role, `Retiré par ${interaction.user.tag}`); - } - - await logModerationAction(interaction, { - action: 'role', - targetId: target.id, - reason: `${adding ? 'Ajout' : 'Retrait'} du rôle ${role.name} (${role.id})`, - }); - await interaction.editReply({ - embeds: [ - successEmbed( - `C’est fait : le rôle ${role} a été ${adding ? 'ajouté à' : 'retiré de'} **${target.user.tag}**.`, - ), - ], - }); -} +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { UserFacingError } from '../../core/errors.js'; +import { fetchTargetMember, logModerationAction } from '../../services/moderation/moderation-service.js'; +import { successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.STAFF; + +export const data = new SlashCommandBuilder() + .setName('role') + .setDescription('Gestion des rôles') + .setDefaultMemberPermissions(PermissionFlagsBits.ManageRoles) + .addSubcommand((sub) => + sub + .setName('set') + .setDescription('Attribuer ou retirer un rôle') + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) + .addRoleOption((option) => option.setName('role').setDescription('Rôle').setRequired(true)) + .addStringOption((option) => + option + .setName('action') + .setDescription('Ajouter ou retirer le rôle') + .setRequired(true) + .addChoices( + { name: 'Ajouter le rôle', value: 'add' }, + { name: 'Retirer le rôle', value: 'remove' }, + ), + ), + ); + +/** Adds or removes a role after checking both hierarchies (M7-T05 / M3-T05). */ +export async function execute(interaction) { + const user = interaction.options.getUser('user', true); + const role = interaction.options.getRole('role', true); + const action = interaction.options.getString('action', true); + const adding = action === 'add'; + + if (role.id === interaction.guild.roles.everyone.id) { + throw new UserFacingError( + 'Le rôle @everyone ne s’attribue pas : il est porté par tout le monde à la fois.', + ); + } + if (role.managed) { + throw new UserFacingError( + 'Ce rôle appartient à une intégration : Discord le gère tout seul, je ne peux pas le modifier.', + ); + } + + const bot = interaction.guild.members.me; + if (bot && bot.roles.highest.comparePositionTo(role) <= 0) { + throw new UserFacingError( + 'Je ne peux pas gérer ce rôle : il est placé plus haut que le mien. Remonte mon rôle dans la hiérarchie du serveur, et je m’en occupe.', + ); + } + + const target = await fetchTargetMember(interaction, user.id); + const hasRole = target.roles.cache.has(role.id); + if (adding && hasRole) { + throw new UserFacingError(`Rien à faire : **${target.user.tag}** porte déjà le rôle ${role}.`); + } + if (!adding && !hasRole) { + throw new UserFacingError(`Rien à retirer : **${target.user.tag}** n’a pas le rôle ${role}.`); + } + + const isGuildOwner = interaction.guild.ownerId === interaction.user.id; + if (!isGuildOwner && interaction.member.roles.highest.comparePositionTo(role) <= 0) { + throw new UserFacingError( + 'Ce rôle est au même niveau (ou plus haut) que le tien : je ne peux pas y toucher. Demande à quelqu’un de plus haut dans la hiérarchie.', + ); + } + + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + if (adding) { + await target.roles.add(role, `Ajouté par ${interaction.user.tag}`); + } else { + await target.roles.remove(role, `Retiré par ${interaction.user.tag}`); + } + + await logModerationAction(interaction, { + action: 'role', + targetId: target.id, + reason: `${adding ? 'Ajout' : 'Retrait'} du rôle ${role.name} (${role.id})`, + }); + await interaction.editReply({ + embeds: [ + successEmbed( + `C’est fait : le rôle ${role} a été ${adding ? 'ajouté à' : 'retiré de'} **${target.user.tag}**.`, + ), + ], + }); +} diff --git a/src/commands/moderation/warn.js b/src/commands/moderation/warn.js index db2b6cd..0c79d3f 100644 --- a/src/commands/moderation/warn.js +++ b/src/commands/moderation/warn.js @@ -1,53 +1,53 @@ -import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS } from '../../config/constants.js'; -import { countActions } from '../../database/repositories/moderation-repository.js'; -import { - assertModerationTarget, - fetchTargetMember, - logModerationAction, - targetNoticeEmbed, -} from '../../services/moderation/moderation-service.js'; -import { successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.STAFF; - -export const data = new SlashCommandBuilder() - .setName('warn') - .setDescription('Avertir un membre') - .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers) - .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) - .addStringOption((option) => - option.setName('reason').setDescription('Motif').setRequired(true).setMaxLength(500), - ); - -/** Records the warning, notifies the member and logs it (M8-T01 / M8-T06). */ -export async function execute(interaction) { - const user = interaction.options.getUser('user', true); - const reason = interaction.options.getString('reason', true); - - const target = await fetchTargetMember(interaction, user.id); - assertModerationTarget(interaction, target); - - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - await logModerationAction(interaction, { action: 'warn', targetId: target.id, reason }); - - const total = countActions({ guildId: interaction.guildId, targetId: target.id, action: 'warn' }); - await target - .send({ - embeds: [ - targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({ - name: 'Avertissements', - value: String(total), - }), - ], - }) - .catch(() => {}); - - await interaction.editReply({ - embeds: [ - successEmbed( - `C’est fait : **${target.user.tag}** reçoit un avertissement (${total} au total). La personne a aussi reçu un message privé quand c’était possible.`, - ), - ], - }); -} +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { countActions } from '../../database/repositories/moderation-repository.js'; +import { + assertModerationTarget, + fetchTargetMember, + logModerationAction, + targetNoticeEmbed, +} from '../../services/moderation/moderation-service.js'; +import { successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.STAFF; + +export const data = new SlashCommandBuilder() + .setName('warn') + .setDescription('Avertir un membre') + .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers) + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) + .addStringOption((option) => + option.setName('reason').setDescription('Motif').setRequired(true).setMaxLength(500), + ); + +/** Records the warning, notifies the member and logs it (M8-T01 / M8-T06). */ +export async function execute(interaction) { + const user = interaction.options.getUser('user', true); + const reason = interaction.options.getString('reason', true); + + const target = await fetchTargetMember(interaction, user.id); + assertModerationTarget(interaction, target); + + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + await logModerationAction(interaction, { action: 'warn', targetId: target.id, reason }); + + const total = countActions({ guildId: interaction.guildId, targetId: target.id, action: 'warn' }); + await target + .send({ + embeds: [ + targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({ + name: 'Avertissements', + value: String(total), + }), + ], + }) + .catch(() => {}); + + await interaction.editReply({ + embeds: [ + successEmbed( + `C’est fait : **${target.user.tag}** reçoit un avertissement (${total} au total). La personne a aussi reçu un message privé quand c’était possible.`, + ), + ], + }); +} diff --git a/src/commands/tickets/ticket.js b/src/commands/tickets/ticket.js index 39724fe..48b21f1 100644 --- a/src/commands/tickets/ticket.js +++ b/src/commands/tickets/ticket.js @@ -1,72 +1,72 @@ -import { MessageFlags, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js'; -import { - addParticipant, - claimTicket, - closeTicket, - createTicket, -} from '../../services/tickets/ticket-service.js'; -import { successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.USER; -// `close` is also allowed for the ticket author: checked in the ticket service. -export const subcommandAccess = { claim: ACCESS_LEVELS.STAFF, add: ACCESS_LEVELS.STAFF }; - -export const data = new SlashCommandBuilder() - .setName('ticket') - .setDescription('Tickets de support privés') - .addSubcommand((sub) => - sub - .setName('create') - .setDescription('Ouvrir un ticket') - .addStringOption((option) => - option - .setName('category') - .setDescription('Catégorie du ticket') - .setRequired(true) - .addChoices(...TICKET_CATEGORIES.map(({ id, label }) => ({ name: label, value: id }))), - ), - ) - .addSubcommand((sub) => - sub - .setName('close') - .setDescription('Fermer le ticket') - .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)), - ) - .addSubcommand((sub) => sub.setName('claim').setDescription('Prendre le ticket en charge')) - .addSubcommand((sub) => - sub - .setName('add') - .setDescription('Ajouter un participant') - .addUserOption((option) => option.setName('user').setDescription('Membre à ajouter').setRequired(true)), - ); - -/** Ticket lifecycle: each subcommand acts on a private channel (M6-T03..T09). */ -export async function execute(interaction) { - switch (interaction.options.getSubcommand()) { - case 'create': { - const categoryId = interaction.options.getString('category', true); - await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const channel = await createTicket(interaction, categoryId); - await interaction.editReply({ - embeds: [ - successEmbed( - `Ton ticket est ouvert : <#${channel.id}>. Décris ta demande dedans, une personne de l’équipe te répond dès que possible.`, - ), - ], - }); - return; - } - case 'close': - await closeTicket(interaction, interaction.options.getString('reason')); - return; - case 'claim': - await claimTicket(interaction); - return; - case 'add': - await addParticipant(interaction, interaction.options.getUser('user', true).id); - return; - default: - return; - } -} +import { MessageFlags, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js'; +import { + addParticipant, + claimTicket, + closeTicket, + createTicket, +} from '../../services/tickets/ticket-service.js'; +import { successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.USER; +// `close` is also allowed for the ticket author: checked in the ticket service. +export const subcommandAccess = { claim: ACCESS_LEVELS.STAFF, add: ACCESS_LEVELS.STAFF }; + +export const data = new SlashCommandBuilder() + .setName('ticket') + .setDescription('Tickets de support privés') + .addSubcommand((sub) => + sub + .setName('create') + .setDescription('Ouvrir un ticket') + .addStringOption((option) => + option + .setName('category') + .setDescription('Catégorie du ticket') + .setRequired(true) + .addChoices(...TICKET_CATEGORIES.map(({ id, label }) => ({ name: label, value: id }))), + ), + ) + .addSubcommand((sub) => + sub + .setName('close') + .setDescription('Fermer le ticket') + .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)), + ) + .addSubcommand((sub) => sub.setName('claim').setDescription('Prendre le ticket en charge')) + .addSubcommand((sub) => + sub + .setName('add') + .setDescription('Ajouter un participant') + .addUserOption((option) => option.setName('user').setDescription('Membre à ajouter').setRequired(true)), + ); + +/** Ticket lifecycle: each subcommand acts on a private channel (M6-T03..T09). */ +export async function execute(interaction) { + switch (interaction.options.getSubcommand()) { + case 'create': { + const categoryId = interaction.options.getString('category', true); + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const channel = await createTicket(interaction, categoryId); + await interaction.editReply({ + embeds: [ + successEmbed( + `Ton ticket est ouvert : <#${channel.id}>. Décris ta demande dedans, une personne de l’équipe te répond dès que possible.`, + ), + ], + }); + return; + } + case 'close': + await closeTicket(interaction, interaction.options.getString('reason')); + return; + case 'claim': + await claimTicket(interaction); + return; + case 'add': + await addParticipant(interaction, interaction.options.getUser('user', true).id); + return; + default: + return; + } +} diff --git a/src/commands/voice/voice.js b/src/commands/voice/voice.js index 67c1a28..5409d19 100644 --- a/src/commands/voice/voice.js +++ b/src/commands/voice/voice.js @@ -1,373 +1,373 @@ -import { ChannelType, MessageFlags, SlashCommandBuilder } from 'discord.js'; -import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; -import { UserFacingError } from '../../core/errors.js'; -import { - activeChannelCount, - claimOwnership, - findTrigger, - kickUser, - listTriggerSummaries, - NAME_MAX, - permitUser, - postSetupPanel, - rejectUser, - removeChannel, - removeVoiceTriggerConfig, - renameChannel, - saveVoiceTrigger, - setChannelLimit, - setTriggerEnabled, - showInfo, - toggleLock, - transferOwnership, -} from '../../services/voice/voice-service.js'; -import { baseEmbed, successEmbed } from '../../ui/embeds.js'; - -export const access = ACCESS_LEVELS.USER; -export const subcommandAccess = { - setup: ACCESS_LEVELS.STAFF, - panel: ACCESS_LEVELS.STAFF, - list: ACCESS_LEVELS.STAFF, - remove: ACCESS_LEVELS.STAFF, - enable: ACCESS_LEVELS.STAFF, - disable: ACCESS_LEVELS.STAFF, -}; - -const voiceChannelOption = (option) => option.addChannelTypes(ChannelType.GuildVoice); - -/** Longest embed listing worth sending before it gets unreadable. */ -const MAX_LISTED_TRIGGERS = 20; - -export const data = new SlashCommandBuilder() - .setName('voice') - .setDescription('Gestion des salons vocaux temporaires') - .addSubcommand((sub) => - sub - .setName('setup') - .setDescription('Ajouter ou modifier un salon déclencheur') - .addChannelOption((option) => - voiceChannelOption( - option - .setName('trigger') - .setDescription('Salon vocal à rejoindre pour créer un salon') - .setRequired(true), - ), - ) - .addStringOption((option) => - option.setName('label').setDescription('Nom du déclencheur (ex. « Dev », « SIO »)').setMaxLength(40), - ) - .addChannelOption((option) => - option - .setName('category') - .setDescription('Catégorie d’accueil des salons créés (défaut : celle du déclencheur)') - .addChannelTypes(ChannelType.GuildCategory), - ) - .addStringOption((option) => - option - .setName('template') - .setDescription('Modèle du nom, avec {user} (ex. « 🔊 Salon de {user} »)') - .setMaxLength(NAME_MAX), - ) - .addIntegerOption((option) => - option - .setName('limit') - .setDescription('Places par défaut (0 = illimité)') - .setMinValue(0) - .setMaxValue(99), - ) - .addBooleanOption((option) => - option.setName('panel').setDescription('Publier le panneau d’explication dans le salon'), - ), - ) - .addSubcommand((sub) => sub.setName('config').setDescription('Afficher les déclencheurs configurés')) - .addSubcommand((sub) => - sub - .setName('panel') - .setDescription('Republier le panneau d’explication dans les salons déclencheurs') - .addChannelOption((option) => - voiceChannelOption(option.setName('trigger').setDescription('Un seul déclencheur (défaut : tous)')), - ), - ) - .addSubcommandGroup((group) => - group - .setName('triggers') - .setDescription('Gérer les salons déclencheurs') - .addSubcommand((sub) => sub.setName('list').setDescription('Lister les déclencheurs')) - .addSubcommand((sub) => - sub - .setName('remove') - .setDescription('Supprimer un déclencheur') - .addChannelOption((option) => - voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)), - ), - ) - .addSubcommand((sub) => - sub - .setName('disable') - .setDescription('Désactiver un déclencheur sans le supprimer') - .addChannelOption((option) => - voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)), - ), - ) - .addSubcommand((sub) => - sub - .setName('enable') - .setDescription('Réactiver un déclencheur') - .addChannelOption((option) => - voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)), - ), - ), - ) - .addSubcommand((sub) => - sub - .setName('name') - .setDescription('Renommer ton salon') - .addStringOption((option) => - option.setName('name').setDescription('Nouveau nom').setRequired(true).setMaxLength(NAME_MAX), - ), - ) - .addSubcommand((sub) => - sub - .setName('limit') - .setDescription('Limiter le nombre de places (0 = illimité)') - .addIntegerOption((option) => - option - .setName('limit') - .setDescription('Nombre de places') - .setRequired(true) - .setMinValue(0) - .setMaxValue(99), - ), - ) - .addSubcommand((sub) => sub.setName('lock').setDescription('Verrouiller ton salon')) - .addSubcommand((sub) => sub.setName('unlock').setDescription('Déverrouiller ton salon')) - .addSubcommand((sub) => - sub - .setName('permit') - .setDescription('Autoriser un membre à rejoindre ton salon') - .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)), - ) - .addSubcommand((sub) => - sub - .setName('reject') - .setDescription('Interdire l’accès à un membre') - .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)), - ) - .addSubcommand((sub) => - sub - .setName('kick') - .setDescription('Exclure un membre du salon') - .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)), - ) - .addSubcommand((sub) => - sub - .setName('transfer') - .setDescription('Transférer la propriété du salon') - .addUserOption((option) => - option.setName('user').setDescription('Nouveau propriétaire').setRequired(true), - ), - ) - .addSubcommand((sub) => sub.setName('claim').setDescription('Récupérer un salon abandonné')) - .addSubcommand((sub) => - sub - .setName('delete') - .setDescription('Supprimer un salon temporaire') - .addChannelOption((option) => - voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')), - ), - ) - .addSubcommand((sub) => - sub - .setName('info') - .setDescription('Détails du salon temporaire') - .addChannelOption((option) => - voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')), - ), - ); - -const ORIGIN_LABELS = { - env: 'variables d’environnement', - settings: 'anciens réglages du bot', -}; - -/** One embed field per trigger, shared by `/voice config`, `/voice triggers list` and `/voice setup`. */ -function describeTrigger(trigger, index = null) { - const lines = [ - `**Salon :** <#${trigger.triggerId}>`, - `**Catégorie :** ${trigger.categoryId ? `<#${trigger.categoryId}>` : 'celle du salon déclencheur'}`, - `**Modèle :** \`${trigger.template}\``, - `**Limite :** ${trigger.userLimit ? `${trigger.userLimit} places` : 'illimitée'}`, - `**Salons en cours :** ${trigger.activeChannels ?? 0}`, - ]; - const origin = ORIGIN_LABELS[trigger.source]; - if (origin) lines.push(`**Origine :** ${origin}`); - - return { - name: `${index === null ? '' : `${index + 1}. `}${trigger.label ? `${trigger.label} · ` : ''}${ - trigger.enabled ? '✅ Actif' : '⛔ Désactivé' - }`, - value: lines.join('\n'), - }; -} - -function configEmbed(guildId) { - const triggers = listTriggerSummaries(guildId); - const embed = baseEmbed(COLORS.primary).setTitle('🎧 Salons vocaux temporaires'); - - if (triggers.length === 0) { - return embed.setDescription( - 'Aucun déclencheur pour le moment : tu peux en ajouter un avec `/voice setup` (un par thème, ex. « Dev », « SIO »).', - ); - } - - embed.setDescription( - `**${triggers.length}** déclencheur(s) · **${activeChannelCount(guildId)}** salon(s) temporaire(s) en cours\n` + - 'Chaque déclencheur crée ses salons en bas de sa propre catégorie, et ils disparaissent dès qu’ils se vident.', - ); - embed.addFields(triggers.slice(0, MAX_LISTED_TRIGGERS).map((trigger, i) => describeTrigger(trigger, i))); - if (triggers.length > MAX_LISTED_TRIGGERS) { - embed.addFields({ - name: 'Autres déclencheurs', - value: `… et ${triggers.length - MAX_LISTED_TRIGGERS} autre(s), visibles sur le serveur.`, - }); - } - return embed; -} - -async function runSetup(interaction) { - const channel = interaction.options.getChannel('trigger', true); - if (channel.type !== ChannelType.GuildVoice) { - throw new UserFacingError('Le salon déclencheur doit être un salon **vocal**.'); - } - - const category = interaction.options.getChannel('category'); - if (category && category.type !== ChannelType.GuildCategory) { - throw new UserFacingError('La catégorie d’accueil doit être une **catégorie**.'); - } - - const existing = findTrigger(interaction.guildId, channel.id); - const template = interaction.options.getString('template'); - const limit = interaction.options.getInteger('limit'); - const label = interaction.options.getString('label'); - - const trigger = saveVoiceTrigger( - interaction.guildId, - { - triggerId: channel.id, - ...(label !== null && { label }), - // A trigger with no explicit category hosts its channels in its own category. - categoryId: category?.id ?? existing?.categoryId ?? channel.parentId ?? null, - ...(template !== null && { template }), - ...(limit !== null && { userLimit: limit }), - }, - interaction.user.id, - ); - - if (!trigger) { - throw new UserFacingError('Le déclencheur n’a pas pu être enregistré, réessaie.'); - } - - const embed = baseEmbed(COLORS.success) - .setTitle(existing ? '✅ Déclencheur mis à jour' : '✅ Déclencheur ajouté') - .addFields(describeTrigger(trigger)) - .setFooter({ text: 'Les salons créés depuis ce déclencheur apparaîtront en bas de sa catégorie.' }); - - await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); - - const wantsPanel = interaction.options.getBoolean('panel') ?? true; - if (wantsPanel) await postSetupPanel(interaction, { triggerId: channel.id }).catch(() => {}); -} - -/** `/voice triggers …` — declaration and lifecycle of the trigger channels (M14-T01). */ -async function runTriggerGroup(interaction, subcommand) { - const guildId = interaction.guildId; - - if (subcommand === 'list') { - await interaction.reply({ embeds: [configEmbed(guildId)], flags: MessageFlags.Ephemeral }); - return; - } - - const target = interaction.options.getChannel('trigger', true); - if (subcommand === 'remove') { - removeVoiceTriggerConfig(guildId, target.id); - await interaction.reply({ - embeds: [ - successEmbed( - `C’est fait : <#${target.id}> n’est plus un déclencheur. Les salons déjà créés depuis lui restent en place jusqu’à ce qu’ils se vident.`, - ), - ], - flags: MessageFlags.Ephemeral, - }); - return; - } - - const trigger = setTriggerEnabled(guildId, target.id, subcommand === 'enable'); - await interaction.reply({ - embeds: [ - successEmbed( - trigger.enabled - ? `Bon retour ! Le déclencheur <#${trigger.triggerId}> crée à nouveau des salons.` - : `Le déclencheur <#${trigger.triggerId}> est en pause : y entrer ne crée plus de salon, et sa configuration est conservée.`, - ), - ], - flags: MessageFlags.Ephemeral, - }); -} - -/** Every subcommand acts on the caller's temporary channel, checked by the service (M14-T06). */ -export async function execute(interaction) { - const subcommand = interaction.options.getSubcommand(); - const channel = interaction.options.getChannel('channel'); - - if (interaction.options.getSubcommandGroup(false) === 'triggers') { - await runTriggerGroup(interaction, subcommand); - return; - } - - switch (subcommand) { - case 'setup': - await runSetup(interaction); - return; - case 'panel': - await postSetupPanel(interaction, { - triggerId: interaction.options.getChannel('trigger')?.id ?? null, - }); - return; - case 'config': - await interaction.reply({ embeds: [configEmbed(interaction.guildId)], flags: MessageFlags.Ephemeral }); - return; - case 'name': - await renameChannel(interaction, interaction.options.getString('name', true)); - return; - case 'limit': - await setChannelLimit(interaction, interaction.options.getInteger('limit', true)); - return; - case 'lock': - case 'unlock': - await toggleLock(interaction, { locked: subcommand === 'lock' }); - return; - case 'permit': - await permitUser(interaction, interaction.options.getUser('user', true).id); - return; - case 'reject': - await rejectUser(interaction, interaction.options.getUser('user', true).id); - return; - case 'kick': - await kickUser(interaction, interaction.options.getUser('user', true).id); - return; - case 'transfer': - await transferOwnership(interaction, interaction.options.getUser('user', true).id); - return; - case 'claim': - await claimOwnership(interaction); - return; - case 'delete': - await removeChannel(interaction, { channelId: channel?.id ?? null }); - return; - case 'info': - await showInfo(interaction, { channelId: channel?.id ?? null }); - return; - default: - return; - } -} +import { ChannelType, MessageFlags, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { UserFacingError } from '../../core/errors.js'; +import { + activeChannelCount, + claimOwnership, + findTrigger, + kickUser, + listTriggerSummaries, + NAME_MAX, + permitUser, + postSetupPanel, + rejectUser, + removeChannel, + removeVoiceTriggerConfig, + renameChannel, + saveVoiceTrigger, + setChannelLimit, + setTriggerEnabled, + showInfo, + toggleLock, + transferOwnership, +} from '../../services/voice/voice-service.js'; +import { baseEmbed, successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.USER; +export const subcommandAccess = { + setup: ACCESS_LEVELS.STAFF, + panel: ACCESS_LEVELS.STAFF, + list: ACCESS_LEVELS.STAFF, + remove: ACCESS_LEVELS.STAFF, + enable: ACCESS_LEVELS.STAFF, + disable: ACCESS_LEVELS.STAFF, +}; + +const voiceChannelOption = (option) => option.addChannelTypes(ChannelType.GuildVoice); + +/** Longest embed listing worth sending before it gets unreadable. */ +const MAX_LISTED_TRIGGERS = 20; + +export const data = new SlashCommandBuilder() + .setName('voice') + .setDescription('Gestion des salons vocaux temporaires') + .addSubcommand((sub) => + sub + .setName('setup') + .setDescription('Ajouter ou modifier un salon déclencheur') + .addChannelOption((option) => + voiceChannelOption( + option + .setName('trigger') + .setDescription('Salon vocal à rejoindre pour créer un salon') + .setRequired(true), + ), + ) + .addStringOption((option) => + option.setName('label').setDescription('Nom du déclencheur (ex. « Dev », « SIO »)').setMaxLength(40), + ) + .addChannelOption((option) => + option + .setName('category') + .setDescription('Catégorie d’accueil des salons créés (défaut : celle du déclencheur)') + .addChannelTypes(ChannelType.GuildCategory), + ) + .addStringOption((option) => + option + .setName('template') + .setDescription('Modèle du nom, avec {user} (ex. « 🔊 Salon de {user} »)') + .setMaxLength(NAME_MAX), + ) + .addIntegerOption((option) => + option + .setName('limit') + .setDescription('Places par défaut (0 = illimité)') + .setMinValue(0) + .setMaxValue(99), + ) + .addBooleanOption((option) => + option.setName('panel').setDescription('Publier le panneau d’explication dans le salon'), + ), + ) + .addSubcommand((sub) => sub.setName('config').setDescription('Afficher les déclencheurs configurés')) + .addSubcommand((sub) => + sub + .setName('panel') + .setDescription('Republier le panneau d’explication dans les salons déclencheurs') + .addChannelOption((option) => + voiceChannelOption(option.setName('trigger').setDescription('Un seul déclencheur (défaut : tous)')), + ), + ) + .addSubcommandGroup((group) => + group + .setName('triggers') + .setDescription('Gérer les salons déclencheurs') + .addSubcommand((sub) => sub.setName('list').setDescription('Lister les déclencheurs')) + .addSubcommand((sub) => + sub + .setName('remove') + .setDescription('Supprimer un déclencheur') + .addChannelOption((option) => + voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)), + ), + ) + .addSubcommand((sub) => + sub + .setName('disable') + .setDescription('Désactiver un déclencheur sans le supprimer') + .addChannelOption((option) => + voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)), + ), + ) + .addSubcommand((sub) => + sub + .setName('enable') + .setDescription('Réactiver un déclencheur') + .addChannelOption((option) => + voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)), + ), + ), + ) + .addSubcommand((sub) => + sub + .setName('name') + .setDescription('Renommer ton salon') + .addStringOption((option) => + option.setName('name').setDescription('Nouveau nom').setRequired(true).setMaxLength(NAME_MAX), + ), + ) + .addSubcommand((sub) => + sub + .setName('limit') + .setDescription('Limiter le nombre de places (0 = illimité)') + .addIntegerOption((option) => + option + .setName('limit') + .setDescription('Nombre de places') + .setRequired(true) + .setMinValue(0) + .setMaxValue(99), + ), + ) + .addSubcommand((sub) => sub.setName('lock').setDescription('Verrouiller ton salon')) + .addSubcommand((sub) => sub.setName('unlock').setDescription('Déverrouiller ton salon')) + .addSubcommand((sub) => + sub + .setName('permit') + .setDescription('Autoriser un membre à rejoindre ton salon') + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)), + ) + .addSubcommand((sub) => + sub + .setName('reject') + .setDescription('Interdire l’accès à un membre') + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)), + ) + .addSubcommand((sub) => + sub + .setName('kick') + .setDescription('Exclure un membre du salon') + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)), + ) + .addSubcommand((sub) => + sub + .setName('transfer') + .setDescription('Transférer la propriété du salon') + .addUserOption((option) => + option.setName('user').setDescription('Nouveau propriétaire').setRequired(true), + ), + ) + .addSubcommand((sub) => sub.setName('claim').setDescription('Récupérer un salon abandonné')) + .addSubcommand((sub) => + sub + .setName('delete') + .setDescription('Supprimer un salon temporaire') + .addChannelOption((option) => + voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')), + ), + ) + .addSubcommand((sub) => + sub + .setName('info') + .setDescription('Détails du salon temporaire') + .addChannelOption((option) => + voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')), + ), + ); + +const ORIGIN_LABELS = { + env: 'variables d’environnement', + settings: 'anciens réglages du bot', +}; + +/** One embed field per trigger, shared by `/voice config`, `/voice triggers list` and `/voice setup`. */ +function describeTrigger(trigger, index = null) { + const lines = [ + `**Salon :** <#${trigger.triggerId}>`, + `**Catégorie :** ${trigger.categoryId ? `<#${trigger.categoryId}>` : 'celle du salon déclencheur'}`, + `**Modèle :** \`${trigger.template}\``, + `**Limite :** ${trigger.userLimit ? `${trigger.userLimit} places` : 'illimitée'}`, + `**Salons en cours :** ${trigger.activeChannels ?? 0}`, + ]; + const origin = ORIGIN_LABELS[trigger.source]; + if (origin) lines.push(`**Origine :** ${origin}`); + + return { + name: `${index === null ? '' : `${index + 1}. `}${trigger.label ? `${trigger.label} · ` : ''}${ + trigger.enabled ? '✅ Actif' : '⛔ Désactivé' + }`, + value: lines.join('\n'), + }; +} + +function configEmbed(guildId) { + const triggers = listTriggerSummaries(guildId); + const embed = baseEmbed(COLORS.primary).setTitle('🎧 Salons vocaux temporaires'); + + if (triggers.length === 0) { + return embed.setDescription( + 'Aucun déclencheur pour le moment : tu peux en ajouter un avec `/voice setup` (un par thème, ex. « Dev », « SIO »).', + ); + } + + embed.setDescription( + `**${triggers.length}** déclencheur(s) · **${activeChannelCount(guildId)}** salon(s) temporaire(s) en cours\n` + + 'Chaque déclencheur crée ses salons en bas de sa propre catégorie, et ils disparaissent dès qu’ils se vident.', + ); + embed.addFields(triggers.slice(0, MAX_LISTED_TRIGGERS).map((trigger, i) => describeTrigger(trigger, i))); + if (triggers.length > MAX_LISTED_TRIGGERS) { + embed.addFields({ + name: 'Autres déclencheurs', + value: `… et ${triggers.length - MAX_LISTED_TRIGGERS} autre(s), visibles sur le serveur.`, + }); + } + return embed; +} + +async function runSetup(interaction) { + const channel = interaction.options.getChannel('trigger', true); + if (channel.type !== ChannelType.GuildVoice) { + throw new UserFacingError('Le salon déclencheur doit être un salon **vocal**.'); + } + + const category = interaction.options.getChannel('category'); + if (category && category.type !== ChannelType.GuildCategory) { + throw new UserFacingError('La catégorie d’accueil doit être une **catégorie**.'); + } + + const existing = findTrigger(interaction.guildId, channel.id); + const template = interaction.options.getString('template'); + const limit = interaction.options.getInteger('limit'); + const label = interaction.options.getString('label'); + + const trigger = saveVoiceTrigger( + interaction.guildId, + { + triggerId: channel.id, + ...(label !== null && { label }), + // A trigger with no explicit category hosts its channels in its own category. + categoryId: category?.id ?? existing?.categoryId ?? channel.parentId ?? null, + ...(template !== null && { template }), + ...(limit !== null && { userLimit: limit }), + }, + interaction.user.id, + ); + + if (!trigger) { + throw new UserFacingError('Le déclencheur n’a pas pu être enregistré, réessaie.'); + } + + const embed = baseEmbed(COLORS.success) + .setTitle(existing ? '✅ Déclencheur mis à jour' : '✅ Déclencheur ajouté') + .addFields(describeTrigger(trigger)) + .setFooter({ text: 'Les salons créés depuis ce déclencheur apparaîtront en bas de sa catégorie.' }); + + await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); + + const wantsPanel = interaction.options.getBoolean('panel') ?? true; + if (wantsPanel) await postSetupPanel(interaction, { triggerId: channel.id }).catch(() => {}); +} + +/** `/voice triggers …` — declaration and lifecycle of the trigger channels (M14-T01). */ +async function runTriggerGroup(interaction, subcommand) { + const guildId = interaction.guildId; + + if (subcommand === 'list') { + await interaction.reply({ embeds: [configEmbed(guildId)], flags: MessageFlags.Ephemeral }); + return; + } + + const target = interaction.options.getChannel('trigger', true); + if (subcommand === 'remove') { + removeVoiceTriggerConfig(guildId, target.id); + await interaction.reply({ + embeds: [ + successEmbed( + `C’est fait : <#${target.id}> n’est plus un déclencheur. Les salons déjà créés depuis lui restent en place jusqu’à ce qu’ils se vident.`, + ), + ], + flags: MessageFlags.Ephemeral, + }); + return; + } + + const trigger = setTriggerEnabled(guildId, target.id, subcommand === 'enable'); + await interaction.reply({ + embeds: [ + successEmbed( + trigger.enabled + ? `Bon retour ! Le déclencheur <#${trigger.triggerId}> crée à nouveau des salons.` + : `Le déclencheur <#${trigger.triggerId}> est en pause : y entrer ne crée plus de salon, et sa configuration est conservée.`, + ), + ], + flags: MessageFlags.Ephemeral, + }); +} + +/** Every subcommand acts on the caller's temporary channel, checked by the service (M14-T06). */ +export async function execute(interaction) { + const subcommand = interaction.options.getSubcommand(); + const channel = interaction.options.getChannel('channel'); + + if (interaction.options.getSubcommandGroup(false) === 'triggers') { + await runTriggerGroup(interaction, subcommand); + return; + } + + switch (subcommand) { + case 'setup': + await runSetup(interaction); + return; + case 'panel': + await postSetupPanel(interaction, { + triggerId: interaction.options.getChannel('trigger')?.id ?? null, + }); + return; + case 'config': + await interaction.reply({ embeds: [configEmbed(interaction.guildId)], flags: MessageFlags.Ephemeral }); + return; + case 'name': + await renameChannel(interaction, interaction.options.getString('name', true)); + return; + case 'limit': + await setChannelLimit(interaction, interaction.options.getInteger('limit', true)); + return; + case 'lock': + case 'unlock': + await toggleLock(interaction, { locked: subcommand === 'lock' }); + return; + case 'permit': + await permitUser(interaction, interaction.options.getUser('user', true).id); + return; + case 'reject': + await rejectUser(interaction, interaction.options.getUser('user', true).id); + return; + case 'kick': + await kickUser(interaction, interaction.options.getUser('user', true).id); + return; + case 'transfer': + await transferOwnership(interaction, interaction.options.getUser('user', true).id); + return; + case 'claim': + await claimOwnership(interaction); + return; + case 'delete': + await removeChannel(interaction, { channelId: channel?.id ?? null }); + return; + case 'info': + await showInfo(interaction, { channelId: channel?.id ?? null }); + return; + default: + return; + } +} diff --git a/src/config/constants.js b/src/config/constants.js index 814a8d7..788998c 100644 --- a/src/config/constants.js +++ b/src/config/constants.js @@ -1,68 +1,68 @@ -export const BOT_NAME = 'FWS-Bot'; - -/** Embed colors by category (M12-T01). */ -export const COLORS = Object.freeze({ - primary: 0x1793d1, - success: 0x2ecc71, - warning: 0xf1c40f, - error: 0xe74c3c, - info: 0x3498db, - gitea: 0x609926, - moderation: 0xe67e22, - ticket: 0x9b59b6, -}); - -/** Ordered from least to most privileged (M3-T01). */ -export const ACCESS_LEVELS = Object.freeze({ - USER: 0, - STAFF: 1, - DEV: 2, - OWNER: 3, -}); - -/** Same names for the same levels in every message (M12-T02). */ -export const ACCESS_LABELS = Object.freeze({ - [ACCESS_LEVELS.USER]: 'Membre', - [ACCESS_LEVELS.STAFF]: 'Staff', - [ACCESS_LEVELS.DEV]: 'Dev', - [ACCESS_LEVELS.OWNER]: 'Owner', -}); - -/** Moderation actions: Discord label, embed color and stored duration (M8). */ -export const MODERATION_ACTIONS = Object.freeze({ - warn: { label: 'Avertissement', color: COLORS.warning, duration: false }, - mute: { label: 'Exclusion temporaire', color: COLORS.moderation, duration: true }, - kick: { label: 'Expulsion', color: COLORS.moderation, duration: false }, - ban: { label: 'Bannissement', color: COLORS.error, duration: false }, - clear: { label: 'Suppression de messages', color: COLORS.warning, duration: false }, - role: { label: 'Modification de rôle', color: COLORS.primary, duration: false }, -}); - -/** Ticket categories and who can see them (M0-T05 / M6-T01). */ -export const TICKET_CATEGORIES = Object.freeze([ - { id: 'support', label: 'Aide et support', scope: ['staff', 'owner'] }, - { id: 'bug', label: 'Bug', scope: ['staff', 'dev', 'owner'] }, - { id: 'dev-question', label: 'Question de développement', scope: ['dev', 'owner'] }, - { id: 'report', label: 'Signalement', scope: ['staff', 'owner'] }, - { id: 'internal', label: 'Demande interne', scope: ['owner'] }, -]); - -/** Gitea webhook event -> notification type (M9-T03). */ -export const GITEA_EVENT_TYPES = Object.freeze({ - issues: 'issues', - pull_request: 'pull_request', - push: 'push', - create: 'push', - delete: 'push', - release: 'release', -}); - -export const NOTIFICATION_TYPES = Object.freeze([ - 'issues', - 'pull_requests', - 'commits', - 'releases', - 'announcements', - 'errors', - 'community', -]); +export const BOT_NAME = 'FWS-Bot'; + +/** Embed colors by category (M12-T01). */ +export const COLORS = Object.freeze({ + primary: 0x1793d1, + success: 0x2ecc71, + warning: 0xf1c40f, + error: 0xe74c3c, + info: 0x3498db, + gitea: 0x609926, + moderation: 0xe67e22, + ticket: 0x9b59b6, +}); + +/** Ordered from least to most privileged (M3-T01). */ +export const ACCESS_LEVELS = Object.freeze({ + USER: 0, + STAFF: 1, + DEV: 2, + OWNER: 3, +}); + +/** Same names for the same levels in every message (M12-T02). */ +export const ACCESS_LABELS = Object.freeze({ + [ACCESS_LEVELS.USER]: 'Membre', + [ACCESS_LEVELS.STAFF]: 'Staff', + [ACCESS_LEVELS.DEV]: 'Dev', + [ACCESS_LEVELS.OWNER]: 'Owner', +}); + +/** Moderation actions: Discord label, embed color and stored duration (M8). */ +export const MODERATION_ACTIONS = Object.freeze({ + warn: { label: 'Avertissement', color: COLORS.warning, duration: false }, + mute: { label: 'Exclusion temporaire', color: COLORS.moderation, duration: true }, + kick: { label: 'Expulsion', color: COLORS.moderation, duration: false }, + ban: { label: 'Bannissement', color: COLORS.error, duration: false }, + clear: { label: 'Suppression de messages', color: COLORS.warning, duration: false }, + role: { label: 'Modification de rôle', color: COLORS.primary, duration: false }, +}); + +/** Ticket categories and who can see them (M0-T05 / M6-T01). */ +export const TICKET_CATEGORIES = Object.freeze([ + { id: 'support', label: 'Aide et support', scope: ['staff', 'owner'] }, + { id: 'bug', label: 'Bug', scope: ['staff', 'dev', 'owner'] }, + { id: 'dev-question', label: 'Question de développement', scope: ['dev', 'owner'] }, + { id: 'report', label: 'Signalement', scope: ['staff', 'owner'] }, + { id: 'internal', label: 'Demande interne', scope: ['owner'] }, +]); + +/** Gitea webhook event -> notification type (M9-T03). */ +export const GITEA_EVENT_TYPES = Object.freeze({ + issues: 'issues', + pull_request: 'pull_request', + push: 'push', + create: 'push', + delete: 'push', + release: 'release', +}); + +export const NOTIFICATION_TYPES = Object.freeze([ + 'issues', + 'pull_requests', + 'commits', + 'releases', + 'announcements', + 'errors', + 'community', +]); diff --git a/src/config/env.js b/src/config/env.js index d109f4c..e08c0c7 100644 --- a/src/config/env.js +++ b/src/config/env.js @@ -1,103 +1,103 @@ -import { existsSync } from 'node:fs'; - -if (existsSync('.env')) { - process.loadEnvFile('.env'); -} - -const read = (key, fallback = '') => process.env[key]?.trim() || fallback; -const readInt = (key, fallback) => Number.parseInt(read(key), 10) || fallback; -const readBool = (key, fallback = false) => { - const value = read(key); - return value === '' ? fallback : value === 'true'; -}; -/** Durations accept 0, which `readInt` cannot express because 0 is falsy. */ -const readDuration = (key, fallback) => { - const value = read(key); - if (value === '') return fallback; - const parsed = Number.parseInt(value, 10); - return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback; -}; - -export const env = Object.freeze({ - nodeEnv: read('NODE_ENV', 'development'), - logLevel: read('LOG_LEVEL', 'info'), - logDir: read('LOG_DIR', './logs'), - logRetentionDays: readInt('LOG_RETENTION_DAYS', 30), - - discord: { - token: read('DISCORD_TOKEN'), - clientId: read('DISCORD_CLIENT_ID'), - guildId: read('DISCORD_GUILD_ID'), - }, - - roles: { - owner: read('ROLE_OWNER_ID'), - dev: read('ROLE_DEV_ID'), - staff: read('ROLE_STAFF_ID'), - member: read('ROLE_MEMBER_ID'), - }, - - channels: { - welcome: read('CHANNEL_WELCOME_ID'), - rules: read('CHANNEL_RULES_ID'), - announcements: read('CHANNEL_ANNOUNCEMENTS_ID'), - logs: read('CHANNEL_LOGS_ID'), - modLogs: read('CHANNEL_MOD_LOGS_ID'), - ticketLogs: read('CHANNEL_TICKETS_LOGS_ID'), - notifIssues: read('CHANNEL_NOTIF_ISSUES_ID'), - notifPullRequests: read('CHANNEL_NOTIF_PULL_REQUESTS_ID'), - notifCommits: read('CHANNEL_NOTIF_COMMITS_ID'), - notifReleases: read('CHANNEL_NOTIF_RELEASES_ID'), - notifErrors: read('CHANNEL_NOTIF_ERRORS_ID'), - ticketCategory: read('CATEGORY_TICKETS_ID'), - voiceTrigger: read('CHANNEL_VOICE_TRIGGER_ID'), - voiceCategory: read('CATEGORY_VOICE_ID'), - }, - - voice: { - emptyGraceMs: readDuration('VOICE_EMPTY_GRACE_MS', 5_000), - }, - - bot: { - statusIntervalSeconds: readDuration('BOT_STATUS_INTERVAL_SECONDS', 60), - }, - - gitea: { - url: read('GITEA_URL').replace(/\/+$/, ''), - token: read('GITEA_TOKEN'), - owner: read('GITEA_OWNER'), - repo: read('GITEA_REPO'), - timeoutMs: readInt('GITEA_TIMEOUT_MS', 10_000), - maxRetries: readInt('GITEA_MAX_RETRIES', 2), - }, - - webhook: { - enabled: readBool('WEBHOOK_ENABLED'), - host: read('WEBHOOK_HOST', '0.0.0.0'), - port: readInt('WEBHOOK_PORT', 3000), - path: read('WEBHOOK_PATH', '/webhooks/gitea'), - secret: read('GITEA_WEBHOOK_SECRET'), - }, - - database: { - path: read('DATABASE_PATH', './data/fws-bot.sqlite'), - backupDir: read('BACKUP_DIR', './data/backups'), - }, - - links: { - website: read('FWS_WEBSITE_URL'), - docs: read('FWS_DOCS_URL'), - discordInvite: read('FWS_DISCORD_INVITE_URL'), - archRepo: read('FWS_ARCH_REPO_URL'), - }, -}); - -/** Values that must never appear in Discord messages or logs. */ -export const secrets = [env.discord.token, env.gitea.token, env.webhook.secret].filter(Boolean); - -export function assertRequiredEnv(keys) { - const missing = keys.filter((key) => !read(key)); - if (missing.length > 0) { - throw new Error(`Missing required environment variables: ${missing.join(', ')}`); - } -} +import { existsSync } from 'node:fs'; + +if (existsSync('.env')) { + process.loadEnvFile('.env'); +} + +const read = (key, fallback = '') => process.env[key]?.trim() || fallback; +const readInt = (key, fallback) => Number.parseInt(read(key), 10) || fallback; +const readBool = (key, fallback = false) => { + const value = read(key); + return value === '' ? fallback : value === 'true'; +}; +/** Durations accept 0, which `readInt` cannot express because 0 is falsy. */ +const readDuration = (key, fallback) => { + const value = read(key); + if (value === '') return fallback; + const parsed = Number.parseInt(value, 10); + return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback; +}; + +export const env = Object.freeze({ + nodeEnv: read('NODE_ENV', 'development'), + logLevel: read('LOG_LEVEL', 'info'), + logDir: read('LOG_DIR', './logs'), + logRetentionDays: readInt('LOG_RETENTION_DAYS', 30), + + discord: { + token: read('DISCORD_TOKEN'), + clientId: read('DISCORD_CLIENT_ID'), + guildId: read('DISCORD_GUILD_ID'), + }, + + roles: { + owner: read('ROLE_OWNER_ID'), + dev: read('ROLE_DEV_ID'), + staff: read('ROLE_STAFF_ID'), + member: read('ROLE_MEMBER_ID'), + }, + + channels: { + welcome: read('CHANNEL_WELCOME_ID'), + rules: read('CHANNEL_RULES_ID'), + announcements: read('CHANNEL_ANNOUNCEMENTS_ID'), + logs: read('CHANNEL_LOGS_ID'), + modLogs: read('CHANNEL_MOD_LOGS_ID'), + ticketLogs: read('CHANNEL_TICKETS_LOGS_ID'), + notifIssues: read('CHANNEL_NOTIF_ISSUES_ID'), + notifPullRequests: read('CHANNEL_NOTIF_PULL_REQUESTS_ID'), + notifCommits: read('CHANNEL_NOTIF_COMMITS_ID'), + notifReleases: read('CHANNEL_NOTIF_RELEASES_ID'), + notifErrors: read('CHANNEL_NOTIF_ERRORS_ID'), + ticketCategory: read('CATEGORY_TICKETS_ID'), + voiceTrigger: read('CHANNEL_VOICE_TRIGGER_ID'), + voiceCategory: read('CATEGORY_VOICE_ID'), + }, + + voice: { + emptyGraceMs: readDuration('VOICE_EMPTY_GRACE_MS', 5_000), + }, + + bot: { + statusIntervalSeconds: readDuration('BOT_STATUS_INTERVAL_SECONDS', 60), + }, + + gitea: { + url: read('GITEA_URL').replace(/\/+$/, ''), + token: read('GITEA_TOKEN'), + owner: read('GITEA_OWNER'), + repo: read('GITEA_REPO'), + timeoutMs: readInt('GITEA_TIMEOUT_MS', 10_000), + maxRetries: readInt('GITEA_MAX_RETRIES', 2), + }, + + webhook: { + enabled: readBool('WEBHOOK_ENABLED'), + host: read('WEBHOOK_HOST', '0.0.0.0'), + port: readInt('WEBHOOK_PORT', 3000), + path: read('WEBHOOK_PATH', '/webhooks/gitea'), + secret: read('GITEA_WEBHOOK_SECRET'), + }, + + database: { + path: read('DATABASE_PATH', './data/fws-bot.sqlite'), + backupDir: read('BACKUP_DIR', './data/backups'), + }, + + links: { + website: read('FWS_WEBSITE_URL'), + docs: read('FWS_DOCS_URL'), + discordInvite: read('FWS_DISCORD_INVITE_URL'), + archRepo: read('FWS_ARCH_REPO_URL'), + }, +}); + +/** Values that must never appear in Discord messages or logs. */ +export const secrets = [env.discord.token, env.gitea.token, env.webhook.secret].filter(Boolean); + +export function assertRequiredEnv(keys) { + const missing = keys.filter((key) => !read(key)); + if (missing.length > 0) { + throw new Error(`Missing required environment variables: ${missing.join(', ')}`); + } +} diff --git a/src/core/client.js b/src/core/client.js index b9d577d..37444fa 100644 --- a/src/core/client.js +++ b/src/core/client.js @@ -1,26 +1,26 @@ -import { Client, Collection, GatewayIntentBits, Partials } from 'discord.js'; - -/** - * Only the intents required by the bot (M2-T02): - * - Guilds: slash commands, channels, roles - * - GuildMembers (privileged): welcome, departures, role assignment - * - GuildModeration: ban/kick audit events - * - GuildMessages: /clear and ticket channels - * - GuildVoiceStates: temporary voice channels (M14) - * MessageContent is intentionally not requested. - */ -export function createClient() { - const client = new Client({ - intents: [ - GatewayIntentBits.Guilds, - GatewayIntentBits.GuildMembers, - GatewayIntentBits.GuildModeration, - GatewayIntentBits.GuildMessages, - GatewayIntentBits.GuildVoiceStates, - ], - partials: [Partials.GuildMember], - }); - - client.commands = new Collection(); - return client; -} +import { Client, Collection, GatewayIntentBits, Partials } from 'discord.js'; + +/** + * Only the intents required by the bot (M2-T02): + * - Guilds: slash commands, channels, roles + * - GuildMembers (privileged): welcome, departures, role assignment + * - GuildModeration: ban/kick audit events + * - GuildMessages: /clear and ticket channels + * - GuildVoiceStates: temporary voice channels (M14) + * MessageContent is intentionally not requested. + */ +export function createClient() { + const client = new Client({ + intents: [ + GatewayIntentBits.Guilds, + GatewayIntentBits.GuildMembers, + GatewayIntentBits.GuildModeration, + GatewayIntentBits.GuildMessages, + GatewayIntentBits.GuildVoiceStates, + ], + partials: [Partials.GuildMember], + }); + + client.commands = new Collection(); + return client; +} diff --git a/src/core/command-loader.js b/src/core/command-loader.js index 706c889..ea1a60a 100644 --- a/src/core/command-loader.js +++ b/src/core/command-loader.js @@ -1,28 +1,28 @@ -import { readdir } from 'node:fs/promises'; -import path from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; - -const commandsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'commands'); - -/** - * Loads every command module from src/commands//.js. - * A command module exports: `data` (SlashCommandBuilder), `access` (ACCESS_LEVELS) and `execute`. - */ -export async function loadCommands() { - const entries = await readdir(commandsDir, { recursive: true, withFileTypes: true }); - const commands = []; - - for (const entry of entries) { - if (!entry.isFile() || !entry.name.endsWith('.js')) continue; - - const filePath = path.join(entry.parentPath, entry.name); - const command = await import(pathToFileURL(filePath).href); - - if (!command.data || typeof command.execute !== 'function') { - throw new Error(`Invalid command module: ${path.relative(commandsDir, filePath)}`); - } - commands.push(command); - } - - return commands; -} +import { readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const commandsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'commands'); + +/** + * Loads every command module from src/commands//.js. + * A command module exports: `data` (SlashCommandBuilder), `access` (ACCESS_LEVELS) and `execute`. + */ +export async function loadCommands() { + const entries = await readdir(commandsDir, { recursive: true, withFileTypes: true }); + const commands = []; + + for (const entry of entries) { + if (!entry.isFile() || !entry.name.endsWith('.js')) continue; + + const filePath = path.join(entry.parentPath, entry.name); + const command = await import(pathToFileURL(filePath).href); + + if (!command.data || typeof command.execute !== 'function') { + throw new Error(`Invalid command module: ${path.relative(commandsDir, filePath)}`); + } + commands.push(command); + } + + return commands; +} diff --git a/src/core/errors.js b/src/core/errors.js index 7697e8a..82a578a 100644 --- a/src/core/errors.js +++ b/src/core/errors.js @@ -1,24 +1,24 @@ -/** Error whose message is safe to show to Discord users. */ -export class UserFacingError extends Error { - constructor(message, options) { - super(message, options); - this.name = 'UserFacingError'; - } -} - -export class PermissionDeniedError extends UserFacingError { - constructor( - message = 'Cette action est réservée à l’équipe pour l’instant. Demande à une personne du staff si tu en as besoin.', - ) { - super(message); - this.name = 'PermissionDeniedError'; - } -} - -export class ExternalApiError extends Error { - constructor(service, message, options) { - super(`[${service}] ${message}`, options); - this.name = 'ExternalApiError'; - this.service = service; - } -} +/** Error whose message is safe to show to Discord users. */ +export class UserFacingError extends Error { + constructor(message, options) { + super(message, options); + this.name = 'UserFacingError'; + } +} + +export class PermissionDeniedError extends UserFacingError { + constructor( + message = 'Cette action est réservée à l’équipe pour l’instant. Demande à une personne du staff si tu en as besoin.', + ) { + super(message); + this.name = 'PermissionDeniedError'; + } +} + +export class ExternalApiError extends Error { + constructor(service, message, options) { + super(`[${service}] ${message}`, options); + this.name = 'ExternalApiError'; + this.service = service; + } +} diff --git a/src/core/event-loader.js b/src/core/event-loader.js index 388e17f..c9e86b4 100644 --- a/src/core/event-loader.js +++ b/src/core/event-loader.js @@ -1,29 +1,29 @@ -import { readdir } from 'node:fs/promises'; -import path from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; -import { createLogger } from './logger.js'; - -const eventsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'events'); -const log = createLogger('events'); - -/** - * Registers every event module from src/events. - * An event module exports: `name`, optional `once` and `execute(client, ...args)`. - */ -export async function registerEvents(client) { - const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js')); - - for (const file of files) { - const event = await import(pathToFileURL(path.join(eventsDir, file)).href); - const handler = async (...args) => { - try { - await event.execute(client, ...args); - } catch (error) { - log.error(`Event handler failed: ${event.name}`, error); - } - }; - - client[event.once ? 'once' : 'on'](event.name, handler); - log.debug(`Registered event ${event.name}`); - } -} +import { readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { createLogger } from './logger.js'; + +const eventsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'events'); +const log = createLogger('events'); + +/** + * Registers every event module from src/events. + * An event module exports: `name`, optional `once` and `execute(client, ...args)`. + */ +export async function registerEvents(client) { + const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js')); + + for (const file of files) { + const event = await import(pathToFileURL(path.join(eventsDir, file)).href); + const handler = async (...args) => { + try { + await event.execute(client, ...args); + } catch (error) { + log.error(`Event handler failed: ${event.name}`, error); + } + }; + + client[event.once ? 'once' : 'on'](event.name, handler); + log.debug(`Registered event ${event.name}`); + } +} diff --git a/src/core/logger.js b/src/core/logger.js index 4b72dc8..2cff1ef 100644 --- a/src/core/logger.js +++ b/src/core/logger.js @@ -1,50 +1,50 @@ -import { appendFileSync, mkdirSync } from 'node:fs'; -import path from 'node:path'; -import { env, secrets } from '../config/env.js'; - -const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 }; -const threshold = LEVELS[env.logLevel] ?? LEVELS.info; - -mkdirSync(env.logDir, { recursive: true }); - -export function maskSecrets(text) { - return secrets.reduce((masked, secret) => masked.replaceAll(secret, '***'), String(text)); -} - -function serialize(meta) { - if (meta instanceof Error) { - return { name: meta.name, message: meta.message, stack: meta.stack }; - } - return meta; -} - -function write(level, scope, message, meta) { - if (LEVELS[level] < threshold) return; - - const entry = { - time: new Date().toISOString(), - level, - scope, - message, - ...(meta !== undefined && { meta: serialize(meta) }), - }; - const line = maskSecrets(JSON.stringify(entry)); - - const output = level === 'error' || level === 'warn' ? console.error : console.log; - output(line); - - // Technical logs are split per day to simplify retention (M11-T08). - const file = path.join(env.logDir, `${entry.time.slice(0, 10)}.log`); - appendFileSync(file, `${line}\n`); -} - -export function createLogger(scope) { - return { - debug: (message, meta) => write('debug', scope, message, meta), - info: (message, meta) => write('info', scope, message, meta), - warn: (message, meta) => write('warn', scope, message, meta), - error: (message, meta) => write('error', scope, message, meta), - }; -} - -export const logger = createLogger('app'); +import { appendFileSync, mkdirSync } from 'node:fs'; +import path from 'node:path'; +import { env, secrets } from '../config/env.js'; + +const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 }; +const threshold = LEVELS[env.logLevel] ?? LEVELS.info; + +mkdirSync(env.logDir, { recursive: true }); + +export function maskSecrets(text) { + return secrets.reduce((masked, secret) => masked.replaceAll(secret, '***'), String(text)); +} + +function serialize(meta) { + if (meta instanceof Error) { + return { name: meta.name, message: meta.message, stack: meta.stack }; + } + return meta; +} + +function write(level, scope, message, meta) { + if (LEVELS[level] < threshold) return; + + const entry = { + time: new Date().toISOString(), + level, + scope, + message, + ...(meta !== undefined && { meta: serialize(meta) }), + }; + const line = maskSecrets(JSON.stringify(entry)); + + const output = level === 'error' || level === 'warn' ? console.error : console.log; + output(line); + + // Technical logs are split per day to simplify retention (M11-T08). + const file = path.join(env.logDir, `${entry.time.slice(0, 10)}.log`); + appendFileSync(file, `${line}\n`); +} + +export function createLogger(scope) { + return { + debug: (message, meta) => write('debug', scope, message, meta), + info: (message, meta) => write('info', scope, message, meta), + warn: (message, meta) => write('warn', scope, message, meta), + error: (message, meta) => write('error', scope, message, meta), + }; +} + +export const logger = createLogger('app'); diff --git a/src/core/permissions.js b/src/core/permissions.js index 0506aab..8458d05 100644 --- a/src/core/permissions.js +++ b/src/core/permissions.js @@ -1,33 +1,33 @@ -import { ACCESS_LEVELS } from '../config/constants.js'; -import { env } from '../config/env.js'; - -/** - * Resolves the highest FWS access level of a guild member (M3-T02). - * @param {import('discord.js').GuildMember} member - */ -export function getAccessLevel(member, roles = env.roles) { - if (!member) return ACCESS_LEVELS.USER; - if (member.guild?.ownerId === member.id) return ACCESS_LEVELS.OWNER; - - const has = (roleId) => Boolean(roleId) && member.roles.cache.has(roleId); - if (has(roles.owner)) return ACCESS_LEVELS.OWNER; - if (has(roles.dev)) return ACCESS_LEVELS.DEV; - if (has(roles.staff)) return ACCESS_LEVELS.STAFF; - return ACCESS_LEVELS.USER; -} - -export function hasAccess(member, requiredLevel = ACCESS_LEVELS.USER, roles = env.roles) { - return getAccessLevel(member, roles) >= requiredLevel; -} - -/** - * Prevents acting on a member whose top role is equal or higher (M3-T05 / M8-T08). - * @param {import('discord.js').GuildMember} actor - * @param {import('discord.js').GuildMember} target - */ -export function canActOn(actor, target) { - if (!actor || !target || actor.id === target.id) return false; - if (target.guild.ownerId === target.id) return false; - if (actor.guild.ownerId === actor.id) return true; - return actor.roles.highest.comparePositionTo(target.roles.highest) > 0; -} +import { ACCESS_LEVELS } from '../config/constants.js'; +import { env } from '../config/env.js'; + +/** + * Resolves the highest FWS access level of a guild member (M3-T02). + * @param {import('discord.js').GuildMember} member + */ +export function getAccessLevel(member, roles = env.roles) { + if (!member) return ACCESS_LEVELS.USER; + if (member.guild?.ownerId === member.id) return ACCESS_LEVELS.OWNER; + + const has = (roleId) => Boolean(roleId) && member.roles.cache.has(roleId); + if (has(roles.owner)) return ACCESS_LEVELS.OWNER; + if (has(roles.dev)) return ACCESS_LEVELS.DEV; + if (has(roles.staff)) return ACCESS_LEVELS.STAFF; + return ACCESS_LEVELS.USER; +} + +export function hasAccess(member, requiredLevel = ACCESS_LEVELS.USER, roles = env.roles) { + return getAccessLevel(member, roles) >= requiredLevel; +} + +/** + * Prevents acting on a member whose top role is equal or higher (M3-T05 / M8-T08). + * @param {import('discord.js').GuildMember} actor + * @param {import('discord.js').GuildMember} target + */ +export function canActOn(actor, target) { + if (!actor || !target || actor.id === target.id) return false; + if (target.guild.ownerId === target.id) return false; + if (actor.guild.ownerId === actor.id) return true; + return actor.roles.highest.comparePositionTo(target.roles.highest) > 0; +} diff --git a/src/database/index.js b/src/database/index.js index 4594a49..6bf67c2 100644 --- a/src/database/index.js +++ b/src/database/index.js @@ -1,63 +1,63 @@ -import { mkdirSync, readdirSync, readFileSync } from 'node:fs'; -import path from 'node:path'; -import { DatabaseSync } from 'node:sqlite'; -import { fileURLToPath } from 'node:url'; -import { env } from '../config/env.js'; -import { createLogger } from '../core/logger.js'; - -const log = createLogger('database'); -const migrationsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'migrations'); - -let db; - -function runMigrations(database) { - database.exec(`CREATE TABLE IF NOT EXISTS schema_migrations ( - name TEXT PRIMARY KEY, - applied_at TEXT NOT NULL DEFAULT (datetime('now')) - )`); - - const applied = new Set( - database - .prepare('SELECT name FROM schema_migrations') - .all() - .map((row) => row.name), - ); - const pending = readdirSync(migrationsDir) - .filter((file) => file.endsWith('.sql') && !applied.has(file)) - .sort(); - - for (const file of pending) { - database.exec('BEGIN'); - try { - database.exec(readFileSync(path.join(migrationsDir, file), 'utf8')); - database.prepare('INSERT INTO schema_migrations (name) VALUES (?)').run(file); - database.exec('COMMIT'); - log.info(`Applied migration ${file}`); - } catch (error) { - database.exec('ROLLBACK'); - throw error; - } - } -} - -export function initDatabase(filePath = env.database.path) { - if (db) return db; - - if (filePath !== ':memory:') { - mkdirSync(path.dirname(filePath), { recursive: true }); - } - db = new DatabaseSync(filePath); - db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;'); - runMigrations(db); - return db; -} - -export function getDatabase() { - if (!db) throw new Error('Database not initialized. Call initDatabase() first.'); - return db; -} - -export function closeDatabase() { - db?.close(); - db = undefined; -} +import { mkdirSync, readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import { fileURLToPath } from 'node:url'; +import { env } from '../config/env.js'; +import { createLogger } from '../core/logger.js'; + +const log = createLogger('database'); +const migrationsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'migrations'); + +let db; + +function runMigrations(database) { + database.exec(`CREATE TABLE IF NOT EXISTS schema_migrations ( + name TEXT PRIMARY KEY, + applied_at TEXT NOT NULL DEFAULT (datetime('now')) + )`); + + const applied = new Set( + database + .prepare('SELECT name FROM schema_migrations') + .all() + .map((row) => row.name), + ); + const pending = readdirSync(migrationsDir) + .filter((file) => file.endsWith('.sql') && !applied.has(file)) + .sort(); + + for (const file of pending) { + database.exec('BEGIN'); + try { + database.exec(readFileSync(path.join(migrationsDir, file), 'utf8')); + database.prepare('INSERT INTO schema_migrations (name) VALUES (?)').run(file); + database.exec('COMMIT'); + log.info(`Applied migration ${file}`); + } catch (error) { + database.exec('ROLLBACK'); + throw error; + } + } +} + +export function initDatabase(filePath = env.database.path) { + if (db) return db; + + if (filePath !== ':memory:') { + mkdirSync(path.dirname(filePath), { recursive: true }); + } + db = new DatabaseSync(filePath); + db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;'); + runMigrations(db); + return db; +} + +export function getDatabase() { + if (!db) throw new Error('Database not initialized. Call initDatabase() first.'); + return db; +} + +export function closeDatabase() { + db?.close(); + db = undefined; +} diff --git a/src/database/migrations/001-initial-schema.sql b/src/database/migrations/001-initial-schema.sql index f87eca1..83cb131 100644 --- a/src/database/migrations/001-initial-schema.sql +++ b/src/database/migrations/001-initial-schema.sql @@ -1,97 +1,97 @@ --- Server settings, isolated per guild (M3-T06) -CREATE TABLE IF NOT EXISTS guild_settings ( - guild_id TEXT NOT NULL, - key TEXT NOT NULL, - value TEXT, - updated_by TEXT, - updated_at TEXT NOT NULL DEFAULT (datetime('now')), - PRIMARY KEY (guild_id, key) -); - --- Notification type -> channel mapping (M9-T01) -CREATE TABLE IF NOT EXISTS notification_channels ( - guild_id TEXT NOT NULL, - type TEXT NOT NULL, - channel_id TEXT NOT NULL, - detail_level TEXT NOT NULL DEFAULT 'normal', - PRIMARY KEY (guild_id, type) -); - --- Ticket categories (M6-T01) and tickets (M6) -CREATE TABLE IF NOT EXISTS ticket_categories ( - guild_id TEXT NOT NULL, - id TEXT NOT NULL, - label TEXT NOT NULL, - description TEXT, - scope TEXT NOT NULL, - PRIMARY KEY (guild_id, id) -); - -CREATE TABLE IF NOT EXISTS tickets ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - guild_id TEXT NOT NULL, - channel_id TEXT UNIQUE, - category_id TEXT NOT NULL, - author_id TEXT NOT NULL, - claimed_by TEXT, - status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')), - created_at TEXT NOT NULL DEFAULT (datetime('now')), - closed_at TEXT, - closed_by TEXT -); --- Prevents duplicate open tickets per author and category (M6-T08) -CREATE UNIQUE INDEX IF NOT EXISTS idx_tickets_open_unique - ON tickets (guild_id, author_id, category_id) WHERE status = 'open'; - --- Moderation actions (M8) -CREATE TABLE IF NOT EXISTS moderation_actions ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - guild_id TEXT NOT NULL, - action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'kick', 'ban', 'clear', 'role')), - target_id TEXT, - moderator_id TEXT NOT NULL, - reason TEXT, - duration_ms INTEGER, - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); -CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id); - --- Polls (M10) -CREATE TABLE IF NOT EXISTS polls ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - guild_id TEXT NOT NULL, - channel_id TEXT NOT NULL, - message_id TEXT UNIQUE, - creator_id TEXT NOT NULL, - question TEXT NOT NULL, - choices TEXT NOT NULL, - ends_at TEXT, - status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')), - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE TABLE IF NOT EXISTS poll_votes ( - poll_id INTEGER NOT NULL REFERENCES polls (id) ON DELETE CASCADE, - user_id TEXT NOT NULL, - choice_index INTEGER NOT NULL, - voted_at TEXT NOT NULL DEFAULT (datetime('now')), - PRIMARY KEY (poll_id, user_id) -); - --- Functional event log (M11-T05) -CREATE TABLE IF NOT EXISTS event_logs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - guild_id TEXT, - type TEXT NOT NULL, - actor_id TEXT, - payload TEXT, - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); -CREATE INDEX IF NOT EXISTS idx_event_logs_created ON event_logs (created_at); - --- Delivered Gitea webhook deliveries, to avoid duplicate notifications (M9-T08) -CREATE TABLE IF NOT EXISTS webhook_deliveries ( - delivery_id TEXT PRIMARY KEY, - event TEXT NOT NULL, - received_at TEXT NOT NULL DEFAULT (datetime('now')) -); +-- Server settings, isolated per guild (M3-T06) +CREATE TABLE IF NOT EXISTS guild_settings ( + guild_id TEXT NOT NULL, + key TEXT NOT NULL, + value TEXT, + updated_by TEXT, + updated_at TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY (guild_id, key) +); + +-- Notification type -> channel mapping (M9-T01) +CREATE TABLE IF NOT EXISTS notification_channels ( + guild_id TEXT NOT NULL, + type TEXT NOT NULL, + channel_id TEXT NOT NULL, + detail_level TEXT NOT NULL DEFAULT 'normal', + PRIMARY KEY (guild_id, type) +); + +-- Ticket categories (M6-T01) and tickets (M6) +CREATE TABLE IF NOT EXISTS ticket_categories ( + guild_id TEXT NOT NULL, + id TEXT NOT NULL, + label TEXT NOT NULL, + description TEXT, + scope TEXT NOT NULL, + PRIMARY KEY (guild_id, id) +); + +CREATE TABLE IF NOT EXISTS tickets ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + guild_id TEXT NOT NULL, + channel_id TEXT UNIQUE, + category_id TEXT NOT NULL, + author_id TEXT NOT NULL, + claimed_by TEXT, + status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')), + created_at TEXT NOT NULL DEFAULT (datetime('now')), + closed_at TEXT, + closed_by TEXT +); +-- Prevents duplicate open tickets per author and category (M6-T08) +CREATE UNIQUE INDEX IF NOT EXISTS idx_tickets_open_unique + ON tickets (guild_id, author_id, category_id) WHERE status = 'open'; + +-- Moderation actions (M8) +CREATE TABLE IF NOT EXISTS moderation_actions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + guild_id TEXT NOT NULL, + action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'kick', 'ban', 'clear', 'role')), + target_id TEXT, + moderator_id TEXT NOT NULL, + reason TEXT, + duration_ms INTEGER, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id); + +-- Polls (M10) +CREATE TABLE IF NOT EXISTS polls ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + guild_id TEXT NOT NULL, + channel_id TEXT NOT NULL, + message_id TEXT UNIQUE, + creator_id TEXT NOT NULL, + question TEXT NOT NULL, + choices TEXT NOT NULL, + ends_at TEXT, + status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')), + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE TABLE IF NOT EXISTS poll_votes ( + poll_id INTEGER NOT NULL REFERENCES polls (id) ON DELETE CASCADE, + user_id TEXT NOT NULL, + choice_index INTEGER NOT NULL, + voted_at TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY (poll_id, user_id) +); + +-- Functional event log (M11-T05) +CREATE TABLE IF NOT EXISTS event_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + guild_id TEXT, + type TEXT NOT NULL, + actor_id TEXT, + payload TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_event_logs_created ON event_logs (created_at); + +-- Delivered Gitea webhook deliveries, to avoid duplicate notifications (M9-T08) +CREATE TABLE IF NOT EXISTS webhook_deliveries ( + delivery_id TEXT PRIMARY KEY, + event TEXT NOT NULL, + received_at TEXT NOT NULL DEFAULT (datetime('now')) +); diff --git a/src/database/migrations/004-voice-triggers.sql b/src/database/migrations/004-voice-triggers.sql index cdb2467..918247c 100644 --- a/src/database/migrations/004-voice-triggers.sql +++ b/src/database/migrations/004-voice-triggers.sql @@ -1,14 +1,14 @@ --- Several "join to create" triggers per guild, each with its own home category (M14) -CREATE TABLE IF NOT EXISTS voice_triggers ( - trigger_id TEXT PRIMARY KEY, - guild_id TEXT NOT NULL, - label TEXT, - category_id TEXT, - template TEXT, - user_limit INTEGER NOT NULL DEFAULT 0, - enabled INTEGER NOT NULL DEFAULT 1, - created_at TEXT NOT NULL DEFAULT (datetime('now')), - updated_at TEXT -); - -CREATE INDEX IF NOT EXISTS idx_voice_triggers_guild ON voice_triggers (guild_id); +-- Several "join to create" triggers per guild, each with its own home category (M14) +CREATE TABLE IF NOT EXISTS voice_triggers ( + trigger_id TEXT PRIMARY KEY, + guild_id TEXT NOT NULL, + label TEXT, + category_id TEXT, + template TEXT, + user_limit INTEGER NOT NULL DEFAULT 0, + enabled INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT +); + +CREATE INDEX IF NOT EXISTS idx_voice_triggers_guild ON voice_triggers (guild_id); diff --git a/src/database/repositories/bot-status-repository.js b/src/database/repositories/bot-status-repository.js index c14f8a5..2b87378 100644 --- a/src/database/repositories/bot-status-repository.js +++ b/src/database/repositories/bot-status-repository.js @@ -1,42 +1,42 @@ -import { getDatabase } from '../index.js'; - -/** Adds a status and returns the stored row, so the command can show its id. */ -export function addBotStatus({ text, type = 'watching', url = null, createdBy = null }) { - const result = getDatabase() - .prepare('INSERT INTO bot_statuses (text, type, url, created_by) VALUES (?, ?, ?, ?)') - .run(text, type, url, createdBy); - return getBotStatus(Number(result.lastInsertRowid)); -} - -export function getBotStatus(id) { - return getDatabase().prepare('SELECT * FROM bot_statuses WHERE id = ?').get(id) ?? null; -} - -/** Every status, disabled ones included, in the order they were added. */ -export function listBotStatuses() { - return getDatabase().prepare('SELECT * FROM bot_statuses ORDER BY id ASC').all(); -} - -/** The statuses the rotation is allowed to show. */ -export function listEnabledBotStatuses() { - return getDatabase().prepare('SELECT * FROM bot_statuses WHERE enabled = 1 ORDER BY id ASC').all(); -} - -export function setBotStatusEnabled(id, enabled) { - return getDatabase() - .prepare('UPDATE bot_statuses SET enabled = ? WHERE id = ?') - .run(enabled ? 1 : 0, id).changes; -} - -export function removeBotStatus(id) { - return getDatabase().prepare('DELETE FROM bot_statuses WHERE id = ?').run(id).changes; -} - -export function clearBotStatuses() { - return getDatabase().prepare('DELETE FROM bot_statuses').run().changes; -} - -export function countBotStatuses() { - const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM bot_statuses').get(); - return row.count; -} +import { getDatabase } from '../index.js'; + +/** Adds a status and returns the stored row, so the command can show its id. */ +export function addBotStatus({ text, type = 'watching', url = null, createdBy = null }) { + const result = getDatabase() + .prepare('INSERT INTO bot_statuses (text, type, url, created_by) VALUES (?, ?, ?, ?)') + .run(text, type, url, createdBy); + return getBotStatus(Number(result.lastInsertRowid)); +} + +export function getBotStatus(id) { + return getDatabase().prepare('SELECT * FROM bot_statuses WHERE id = ?').get(id) ?? null; +} + +/** Every status, disabled ones included, in the order they were added. */ +export function listBotStatuses() { + return getDatabase().prepare('SELECT * FROM bot_statuses ORDER BY id ASC').all(); +} + +/** The statuses the rotation is allowed to show. */ +export function listEnabledBotStatuses() { + return getDatabase().prepare('SELECT * FROM bot_statuses WHERE enabled = 1 ORDER BY id ASC').all(); +} + +export function setBotStatusEnabled(id, enabled) { + return getDatabase() + .prepare('UPDATE bot_statuses SET enabled = ? WHERE id = ?') + .run(enabled ? 1 : 0, id).changes; +} + +export function removeBotStatus(id) { + return getDatabase().prepare('DELETE FROM bot_statuses WHERE id = ?').run(id).changes; +} + +export function clearBotStatuses() { + return getDatabase().prepare('DELETE FROM bot_statuses').run().changes; +} + +export function countBotStatuses() { + const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM bot_statuses').get(); + return row.count; +} diff --git a/src/database/repositories/event-log-repository.js b/src/database/repositories/event-log-repository.js index df59fd0..0390aef 100644 --- a/src/database/repositories/event-log-repository.js +++ b/src/database/repositories/event-log-repository.js @@ -1,13 +1,13 @@ -import { getDatabase } from '../index.js'; - -export function logEvent({ guildId = null, type, actorId = null, payload = null }) { - getDatabase() - .prepare('INSERT INTO event_logs (guild_id, type, actor_id, payload) VALUES (?, ?, ?, ?)') - .run(guildId, type, actorId, payload ? JSON.stringify(payload) : null); -} - -export function purgeEventsOlderThan(days) { - return getDatabase() - .prepare("DELETE FROM event_logs WHERE created_at < datetime('now', ?)") - .run(`-${days} days`).changes; -} +import { getDatabase } from '../index.js'; + +export function logEvent({ guildId = null, type, actorId = null, payload = null }) { + getDatabase() + .prepare('INSERT INTO event_logs (guild_id, type, actor_id, payload) VALUES (?, ?, ?, ?)') + .run(guildId, type, actorId, payload ? JSON.stringify(payload) : null); +} + +export function purgeEventsOlderThan(days) { + return getDatabase() + .prepare("DELETE FROM event_logs WHERE created_at < datetime('now', ?)") + .run(`-${days} days`).changes; +} diff --git a/src/database/repositories/moderation-repository.js b/src/database/repositories/moderation-repository.js index a003e95..c7aa00d 100644 --- a/src/database/repositories/moderation-repository.js +++ b/src/database/repositories/moderation-repository.js @@ -1,50 +1,50 @@ -import { getDatabase } from '../index.js'; - -export function recordAction({ - guildId, - action, - moderatorId, - targetId = null, - reason = null, - durationMs = null, -}) { - getDatabase() - .prepare( - `INSERT INTO moderation_actions (guild_id, action, target_id, moderator_id, reason, duration_ms) - VALUES (?, ?, ?, ?, ?, ?)`, - ) - .run(guildId, action, targetId, moderatorId, reason, durationMs); -} - -export function listActions({ guildId, targetId = null, action = null, limit = 20 }) { - const clauses = ['guild_id = ?']; - const params = [guildId]; - if (targetId) { - clauses.push('target_id = ?'); - params.push(targetId); - } - if (action) { - clauses.push('action = ?'); - params.push(action); - } - params.push(limit); - - return getDatabase() - .prepare(`SELECT * FROM moderation_actions WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) - .all(...params); -} - -export function countActions({ guildId, targetId, action }) { - const row = getDatabase() - .prepare( - 'SELECT COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? AND target_id = ? AND action = ?', - ) - .get(guildId, targetId, action); - return row.count; -} - -export function countByAction(guildId) { - return getDatabase() - .prepare('SELECT action, COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? GROUP BY action') - .all(guildId); -} +import { getDatabase } from '../index.js'; + +export function recordAction({ + guildId, + action, + moderatorId, + targetId = null, + reason = null, + durationMs = null, +}) { + getDatabase() + .prepare( + `INSERT INTO moderation_actions (guild_id, action, target_id, moderator_id, reason, duration_ms) + VALUES (?, ?, ?, ?, ?, ?)`, + ) + .run(guildId, action, targetId, moderatorId, reason, durationMs); +} + +export function listActions({ guildId, targetId = null, action = null, limit = 20 }) { + const clauses = ['guild_id = ?']; + const params = [guildId]; + if (targetId) { + clauses.push('target_id = ?'); + params.push(targetId); + } + if (action) { + clauses.push('action = ?'); + params.push(action); + } + params.push(limit); + + return getDatabase() + .prepare(`SELECT * FROM moderation_actions WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) + .all(...params); +} + +export function countActions({ guildId, targetId, action }) { + const row = getDatabase() + .prepare( + 'SELECT COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? AND target_id = ? AND action = ?', + ) + .get(guildId, targetId, action); + return row.count; +} + +export function countByAction(guildId) { + return getDatabase() + .prepare('SELECT action, COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? GROUP BY action') + .all(guildId); +} diff --git a/src/database/repositories/notification-repository.js b/src/database/repositories/notification-repository.js index 62e0f17..8120c35 100644 --- a/src/database/repositories/notification-repository.js +++ b/src/database/repositories/notification-repository.js @@ -1,34 +1,34 @@ -import { getDatabase } from '../index.js'; - -/** Per-guild override of a notification channel (M9-T01). */ -export function setNotificationChannel({ guildId, type, channelId, detailLevel = 'normal' }) { - getDatabase() - .prepare( - `INSERT INTO notification_channels (guild_id, type, channel_id, detail_level) - VALUES (?, ?, ?, ?) - ON CONFLICT (guild_id, type) DO UPDATE SET - channel_id = excluded.channel_id, - detail_level = excluded.detail_level`, - ) - .run(guildId, type, channelId, detailLevel); -} - -export function getNotificationChannel(guildId, type) { - return ( - getDatabase() - .prepare('SELECT * FROM notification_channels WHERE guild_id = ? AND type = ?') - .get(guildId, type) ?? null - ); -} - -export function listNotificationChannels(guildId) { - return getDatabase() - .prepare('SELECT * FROM notification_channels WHERE guild_id = ? ORDER BY type') - .all(guildId); -} - -export function removeNotificationChannel(guildId, type) { - return getDatabase() - .prepare('DELETE FROM notification_channels WHERE guild_id = ? AND type = ?') - .run(guildId, type).changes; -} +import { getDatabase } from '../index.js'; + +/** Per-guild override of a notification channel (M9-T01). */ +export function setNotificationChannel({ guildId, type, channelId, detailLevel = 'normal' }) { + getDatabase() + .prepare( + `INSERT INTO notification_channels (guild_id, type, channel_id, detail_level) + VALUES (?, ?, ?, ?) + ON CONFLICT (guild_id, type) DO UPDATE SET + channel_id = excluded.channel_id, + detail_level = excluded.detail_level`, + ) + .run(guildId, type, channelId, detailLevel); +} + +export function getNotificationChannel(guildId, type) { + return ( + getDatabase() + .prepare('SELECT * FROM notification_channels WHERE guild_id = ? AND type = ?') + .get(guildId, type) ?? null + ); +} + +export function listNotificationChannels(guildId) { + return getDatabase() + .prepare('SELECT * FROM notification_channels WHERE guild_id = ? ORDER BY type') + .all(guildId); +} + +export function removeNotificationChannel(guildId, type) { + return getDatabase() + .prepare('DELETE FROM notification_channels WHERE guild_id = ? AND type = ?') + .run(guildId, type).changes; +} diff --git a/src/database/repositories/poll-repository.js b/src/database/repositories/poll-repository.js index bc8d811..683eb77 100644 --- a/src/database/repositories/poll-repository.js +++ b/src/database/repositories/poll-repository.js @@ -1,97 +1,97 @@ -import { getDatabase } from '../index.js'; - -export function createPoll({ guildId, channelId, creatorId, question, choices, endsAt = null }) { - const { lastInsertRowid } = getDatabase() - .prepare( - `INSERT INTO polls (guild_id, channel_id, creator_id, question, choices, ends_at) - VALUES (?, ?, ?, ?, ?, ?)`, - ) - .run(guildId, channelId, creatorId, question, JSON.stringify(choices), endsAt); - return Number(lastInsertRowid); -} - -export function attachPollMessage(id, messageId) { - getDatabase().prepare('UPDATE polls SET message_id = ? WHERE id = ?').run(messageId, id); -} - -export function getPoll(id) { - return getDatabase().prepare('SELECT * FROM polls WHERE id = ?').get(id) ?? null; -} - -export function getPollByMessage(messageId) { - return getDatabase().prepare('SELECT * FROM polls WHERE message_id = ?').get(messageId) ?? null; -} - -export function listPolls({ guildId, status = null, limit = 10 }) { - const clauses = ['guild_id = ?']; - const params = [guildId]; - if (status) { - clauses.push('status = ?'); - params.push(status); - } - params.push(limit); - - return getDatabase() - .prepare(`SELECT * FROM polls WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) - .all(...params); -} - -/** Polls whose end date is reached and that are still open (M10-T05). */ -export function listDuePolls(limit = 10) { - return getDatabase() - .prepare( - `SELECT * FROM polls - WHERE status = 'open' AND ends_at IS NOT NULL AND ends_at <= datetime('now') - ORDER BY ends_at ASC LIMIT ?`, - ) - .all(limit); -} - -export function listOpenPolls(limit = 25) { - return getDatabase() - .prepare("SELECT * FROM polls WHERE status = 'open' ORDER BY id ASC LIMIT ?") - .all(limit); -} - -export function listVotes(pollId) { - return getDatabase().prepare('SELECT user_id, choice_index FROM poll_votes WHERE poll_id = ?').all(pollId); -} - -/** Counts votes per choice index: `[{ choice_index, count }]`. */ -export function countVotes(pollId) { - return getDatabase() - .prepare('SELECT choice_index, COUNT(*) AS count FROM poll_votes WHERE poll_id = ? GROUP BY choice_index') - .all(pollId); -} - -/** - * Creates or updates a vote. Returns 'created', 'changed' or 'unchanged' (M10-T04). - */ -export function castVote(pollId, userId, choiceIndex) { - const database = getDatabase(); - const previous = database - .prepare('SELECT choice_index FROM poll_votes WHERE poll_id = ? AND user_id = ?') - .get(pollId, userId); - - if (previous && previous.choice_index === choiceIndex) return 'unchanged'; - - database - .prepare( - `INSERT INTO poll_votes (poll_id, user_id, choice_index) VALUES (?, ?, ?) - ON CONFLICT (poll_id, user_id) DO UPDATE SET choice_index = excluded.choice_index, - voted_at = datetime('now')`, - ) - .run(pollId, userId, choiceIndex); - - return previous ? 'changed' : 'created'; -} - -export function closePoll(id) { - return getDatabase().prepare("UPDATE polls SET status = 'closed' WHERE id = ? AND status = 'open'").run(id) - .changes; -} - -export function countPolls(guildId) { - const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM polls WHERE guild_id = ?').get(guildId); - return row.count; -} +import { getDatabase } from '../index.js'; + +export function createPoll({ guildId, channelId, creatorId, question, choices, endsAt = null }) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO polls (guild_id, channel_id, creator_id, question, choices, ends_at) + VALUES (?, ?, ?, ?, ?, ?)`, + ) + .run(guildId, channelId, creatorId, question, JSON.stringify(choices), endsAt); + return Number(lastInsertRowid); +} + +export function attachPollMessage(id, messageId) { + getDatabase().prepare('UPDATE polls SET message_id = ? WHERE id = ?').run(messageId, id); +} + +export function getPoll(id) { + return getDatabase().prepare('SELECT * FROM polls WHERE id = ?').get(id) ?? null; +} + +export function getPollByMessage(messageId) { + return getDatabase().prepare('SELECT * FROM polls WHERE message_id = ?').get(messageId) ?? null; +} + +export function listPolls({ guildId, status = null, limit = 10 }) { + const clauses = ['guild_id = ?']; + const params = [guildId]; + if (status) { + clauses.push('status = ?'); + params.push(status); + } + params.push(limit); + + return getDatabase() + .prepare(`SELECT * FROM polls WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) + .all(...params); +} + +/** Polls whose end date is reached and that are still open (M10-T05). */ +export function listDuePolls(limit = 10) { + return getDatabase() + .prepare( + `SELECT * FROM polls + WHERE status = 'open' AND ends_at IS NOT NULL AND ends_at <= datetime('now') + ORDER BY ends_at ASC LIMIT ?`, + ) + .all(limit); +} + +export function listOpenPolls(limit = 25) { + return getDatabase() + .prepare("SELECT * FROM polls WHERE status = 'open' ORDER BY id ASC LIMIT ?") + .all(limit); +} + +export function listVotes(pollId) { + return getDatabase().prepare('SELECT user_id, choice_index FROM poll_votes WHERE poll_id = ?').all(pollId); +} + +/** Counts votes per choice index: `[{ choice_index, count }]`. */ +export function countVotes(pollId) { + return getDatabase() + .prepare('SELECT choice_index, COUNT(*) AS count FROM poll_votes WHERE poll_id = ? GROUP BY choice_index') + .all(pollId); +} + +/** + * Creates or updates a vote. Returns 'created', 'changed' or 'unchanged' (M10-T04). + */ +export function castVote(pollId, userId, choiceIndex) { + const database = getDatabase(); + const previous = database + .prepare('SELECT choice_index FROM poll_votes WHERE poll_id = ? AND user_id = ?') + .get(pollId, userId); + + if (previous && previous.choice_index === choiceIndex) return 'unchanged'; + + database + .prepare( + `INSERT INTO poll_votes (poll_id, user_id, choice_index) VALUES (?, ?, ?) + ON CONFLICT (poll_id, user_id) DO UPDATE SET choice_index = excluded.choice_index, + voted_at = datetime('now')`, + ) + .run(pollId, userId, choiceIndex); + + return previous ? 'changed' : 'created'; +} + +export function closePoll(id) { + return getDatabase().prepare("UPDATE polls SET status = 'closed' WHERE id = ? AND status = 'open'").run(id) + .changes; +} + +export function countPolls(guildId) { + const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM polls WHERE guild_id = ?').get(guildId); + return row.count; +} diff --git a/src/database/repositories/settings-repository.js b/src/database/repositories/settings-repository.js index 2ba7e8e..c07bc99 100644 --- a/src/database/repositories/settings-repository.js +++ b/src/database/repositories/settings-repository.js @@ -1,33 +1,33 @@ -import { getDatabase } from '../index.js'; - -export function getSetting(guildId, key, fallback = null) { - const row = getDatabase() - .prepare('SELECT value FROM guild_settings WHERE guild_id = ? AND key = ?') - .get(guildId, key); - return row ? JSON.parse(row.value) : fallback; -} - -/** - * Reads a setting without throwing when the database is not ready (tests, early startup). - * Never use it when a missing database should be an error. - */ -export function resolveSetting(guildId, key, fallback = null) { - try { - return getSetting(guildId, key, fallback); - } catch { - return fallback; - } -} - -export function setSetting(guildId, key, value, updatedBy = null) { - getDatabase() - .prepare( - `INSERT INTO guild_settings (guild_id, key, value, updated_by) - VALUES (?, ?, ?, ?) - ON CONFLICT (guild_id, key) DO UPDATE SET - value = excluded.value, - updated_by = excluded.updated_by, - updated_at = datetime('now')`, - ) - .run(guildId, key, JSON.stringify(value), updatedBy); -} +import { getDatabase } from '../index.js'; + +export function getSetting(guildId, key, fallback = null) { + const row = getDatabase() + .prepare('SELECT value FROM guild_settings WHERE guild_id = ? AND key = ?') + .get(guildId, key); + return row ? JSON.parse(row.value) : fallback; +} + +/** + * Reads a setting without throwing when the database is not ready (tests, early startup). + * Never use it when a missing database should be an error. + */ +export function resolveSetting(guildId, key, fallback = null) { + try { + return getSetting(guildId, key, fallback); + } catch { + return fallback; + } +} + +export function setSetting(guildId, key, value, updatedBy = null) { + getDatabase() + .prepare( + `INSERT INTO guild_settings (guild_id, key, value, updated_by) + VALUES (?, ?, ?, ?) + ON CONFLICT (guild_id, key) DO UPDATE SET + value = excluded.value, + updated_by = excluded.updated_by, + updated_at = datetime('now')`, + ) + .run(guildId, key, JSON.stringify(value), updatedBy); +} diff --git a/src/database/repositories/ticket-repository.js b/src/database/repositories/ticket-repository.js index 9f97d46..8b1d795 100644 --- a/src/database/repositories/ticket-repository.js +++ b/src/database/repositories/ticket-repository.js @@ -1,71 +1,71 @@ -import { getDatabase } from '../index.js'; - -export function createTicket({ guildId, channelId, categoryId, authorId }) { - const { lastInsertRowid } = getDatabase() - .prepare('INSERT INTO tickets (guild_id, channel_id, category_id, author_id) VALUES (?, ?, ?, ?)') - .run(guildId, channelId, categoryId, authorId); - return Number(lastInsertRowid); -} - -export function getTicket(id) { - return getDatabase().prepare('SELECT * FROM tickets WHERE id = ?').get(id) ?? null; -} - -export function getTicketByChannel(channelId) { - return getDatabase().prepare('SELECT * FROM tickets WHERE channel_id = ?').get(channelId) ?? null; -} - -/** Returns the open ticket of an author for a category, if any (M6-T08). */ -export function getOpenTicket({ guildId, authorId, categoryId }) { - return ( - getDatabase() - .prepare( - `SELECT * FROM tickets - WHERE guild_id = ? AND author_id = ? AND category_id = ? AND status = 'open'`, - ) - .get(guildId, authorId, categoryId) ?? null - ); -} - -export function listTickets({ guildId, status = null, authorId = null, limit = 20 }) { - const clauses = ['guild_id = ?']; - const params = [guildId]; - if (status) { - clauses.push('status = ?'); - params.push(status); - } - if (authorId) { - clauses.push('author_id = ?'); - params.push(authorId); - } - params.push(limit); - - return getDatabase() - .prepare(`SELECT * FROM tickets WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) - .all(...params); -} - -export function claimTicket(id, userId) { - return getDatabase() - .prepare( - "UPDATE tickets SET claimed_by = ?, claimed_at = datetime('now') WHERE id = ? AND status = 'open'", - ) - .run(userId, id).changes; -} - -export function closeTicket(id, { closedBy, reason = null }) { - return getDatabase() - .prepare( - `UPDATE tickets - SET status = 'closed', closed_at = datetime('now'), closed_by = ?, close_reason = ? - WHERE id = ? AND status = 'open'`, - ) - .run(closedBy, reason, id).changes; -} - -export function countOpenTickets(guildId) { - const row = getDatabase() - .prepare("SELECT COUNT(*) AS count FROM tickets WHERE guild_id = ? AND status = 'open'") - .get(guildId); - return row.count; -} +import { getDatabase } from '../index.js'; + +export function createTicket({ guildId, channelId, categoryId, authorId }) { + const { lastInsertRowid } = getDatabase() + .prepare('INSERT INTO tickets (guild_id, channel_id, category_id, author_id) VALUES (?, ?, ?, ?)') + .run(guildId, channelId, categoryId, authorId); + return Number(lastInsertRowid); +} + +export function getTicket(id) { + return getDatabase().prepare('SELECT * FROM tickets WHERE id = ?').get(id) ?? null; +} + +export function getTicketByChannel(channelId) { + return getDatabase().prepare('SELECT * FROM tickets WHERE channel_id = ?').get(channelId) ?? null; +} + +/** Returns the open ticket of an author for a category, if any (M6-T08). */ +export function getOpenTicket({ guildId, authorId, categoryId }) { + return ( + getDatabase() + .prepare( + `SELECT * FROM tickets + WHERE guild_id = ? AND author_id = ? AND category_id = ? AND status = 'open'`, + ) + .get(guildId, authorId, categoryId) ?? null + ); +} + +export function listTickets({ guildId, status = null, authorId = null, limit = 20 }) { + const clauses = ['guild_id = ?']; + const params = [guildId]; + if (status) { + clauses.push('status = ?'); + params.push(status); + } + if (authorId) { + clauses.push('author_id = ?'); + params.push(authorId); + } + params.push(limit); + + return getDatabase() + .prepare(`SELECT * FROM tickets WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) + .all(...params); +} + +export function claimTicket(id, userId) { + return getDatabase() + .prepare( + "UPDATE tickets SET claimed_by = ?, claimed_at = datetime('now') WHERE id = ? AND status = 'open'", + ) + .run(userId, id).changes; +} + +export function closeTicket(id, { closedBy, reason = null }) { + return getDatabase() + .prepare( + `UPDATE tickets + SET status = 'closed', closed_at = datetime('now'), closed_by = ?, close_reason = ? + WHERE id = ? AND status = 'open'`, + ) + .run(closedBy, reason, id).changes; +} + +export function countOpenTickets(guildId) { + const row = getDatabase() + .prepare("SELECT COUNT(*) AS count FROM tickets WHERE guild_id = ? AND status = 'open'") + .get(guildId); + return row.count; +} diff --git a/src/database/repositories/voice-repository.js b/src/database/repositories/voice-repository.js index 367ead3..d458ee6 100644 --- a/src/database/repositories/voice-repository.js +++ b/src/database/repositories/voice-repository.js @@ -1,72 +1,72 @@ -import { getDatabase } from '../index.js'; - -export function addVoiceChannel({ channelId, guildId, ownerId, triggerId = null, name, userLimit = 0 }) { - getDatabase() - .prepare( - `INSERT INTO voice_channels (channel_id, guild_id, owner_id, trigger_id, name, user_limit) - VALUES (?, ?, ?, ?, ?, ?) - ON CONFLICT (channel_id) DO UPDATE SET - owner_id = excluded.owner_id, - name = excluded.name`, - ) - .run(channelId, guildId, ownerId, triggerId, name, userLimit); -} - -export function getVoiceChannel(channelId) { - return getDatabase().prepare('SELECT * FROM voice_channels WHERE channel_id = ?').get(channelId) ?? null; -} - -export function listVoiceChannels(guildId) { - return getDatabase() - .prepare('SELECT * FROM voice_channels WHERE guild_id = ? ORDER BY created_at ASC') - .all(guildId); -} - -/** Channels still owned by a member, used to move them back instead of creating another (M14-T03). */ -export function listOwnedVoiceChannels(guildId, ownerId) { - return getDatabase() - .prepare('SELECT * FROM voice_channels WHERE guild_id = ? AND owner_id = ? ORDER BY created_at ASC') - .all(guildId, ownerId); -} - -export function setVoiceOwner(channelId, ownerId) { - return getDatabase() - .prepare('UPDATE voice_channels SET owner_id = ? WHERE channel_id = ?') - .run(ownerId, channelId).changes; -} - -export function setVoiceName(channelId, name) { - return getDatabase().prepare('UPDATE voice_channels SET name = ? WHERE channel_id = ?').run(name, channelId) - .changes; -} - -export function setVoiceLocked(channelId, locked) { - return getDatabase() - .prepare('UPDATE voice_channels SET locked = ? WHERE channel_id = ?') - .run(locked ? 1 : 0, channelId).changes; -} - -export function setVoiceLimit(channelId, userLimit) { - return getDatabase() - .prepare('UPDATE voice_channels SET user_limit = ? WHERE channel_id = ?') - .run(userLimit, channelId).changes; -} - -export function removeVoiceChannel(channelId) { - return getDatabase().prepare('DELETE FROM voice_channels WHERE channel_id = ?').run(channelId).changes; -} - -export function countVoiceChannels(guildId) { - const row = getDatabase() - .prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE guild_id = ?') - .get(guildId); - return row.count; -} - -/** Channels still alive for one trigger, used by the configuration embed (M14-T01). */ -export function countVoiceChannelsByTrigger(triggerId) { - const row = getDatabase() - .prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE trigger_id = ?') - .get(triggerId); - return row.count; -} +import { getDatabase } from '../index.js'; + +export function addVoiceChannel({ channelId, guildId, ownerId, triggerId = null, name, userLimit = 0 }) { + getDatabase() + .prepare( + `INSERT INTO voice_channels (channel_id, guild_id, owner_id, trigger_id, name, user_limit) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (channel_id) DO UPDATE SET + owner_id = excluded.owner_id, + name = excluded.name`, + ) + .run(channelId, guildId, ownerId, triggerId, name, userLimit); +} + +export function getVoiceChannel(channelId) { + return getDatabase().prepare('SELECT * FROM voice_channels WHERE channel_id = ?').get(channelId) ?? null; +} + +export function listVoiceChannels(guildId) { + return getDatabase() + .prepare('SELECT * FROM voice_channels WHERE guild_id = ? ORDER BY created_at ASC') + .all(guildId); +} + +/** Channels still owned by a member, used to move them back instead of creating another (M14-T03). */ +export function listOwnedVoiceChannels(guildId, ownerId) { + return getDatabase() + .prepare('SELECT * FROM voice_channels WHERE guild_id = ? AND owner_id = ? ORDER BY created_at ASC') + .all(guildId, ownerId); +} + +export function setVoiceOwner(channelId, ownerId) { + return getDatabase() + .prepare('UPDATE voice_channels SET owner_id = ? WHERE channel_id = ?') + .run(ownerId, channelId).changes; +} + +export function setVoiceName(channelId, name) { + return getDatabase().prepare('UPDATE voice_channels SET name = ? WHERE channel_id = ?').run(name, channelId) + .changes; +} + +export function setVoiceLocked(channelId, locked) { + return getDatabase() + .prepare('UPDATE voice_channels SET locked = ? WHERE channel_id = ?') + .run(locked ? 1 : 0, channelId).changes; +} + +export function setVoiceLimit(channelId, userLimit) { + return getDatabase() + .prepare('UPDATE voice_channels SET user_limit = ? WHERE channel_id = ?') + .run(userLimit, channelId).changes; +} + +export function removeVoiceChannel(channelId) { + return getDatabase().prepare('DELETE FROM voice_channels WHERE channel_id = ?').run(channelId).changes; +} + +export function countVoiceChannels(guildId) { + const row = getDatabase() + .prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE guild_id = ?') + .get(guildId); + return row.count; +} + +/** Channels still alive for one trigger, used by the configuration embed (M14-T01). */ +export function countVoiceChannelsByTrigger(triggerId) { + const row = getDatabase() + .prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE trigger_id = ?') + .get(triggerId); + return row.count; +} diff --git a/src/database/repositories/voice-trigger-repository.js b/src/database/repositories/voice-trigger-repository.js index cadb246..33b9cf4 100644 --- a/src/database/repositories/voice-trigger-repository.js +++ b/src/database/repositories/voice-trigger-repository.js @@ -1,52 +1,52 @@ -import { getDatabase } from '../index.js'; - -/** - * Declares (or updates) a trigger channel. Every value is explicit: the service merges the - * previous row before writing, so an omitted option keeps its stored value (M14-T01). - */ -export function upsertVoiceTrigger({ - triggerId, - guildId, - label = null, - categoryId = null, - template = null, - userLimit = 0, - enabled = true, -}) { - getDatabase() - .prepare( - `INSERT INTO voice_triggers (trigger_id, guild_id, label, category_id, template, user_limit, enabled) - VALUES (?, ?, ?, ?, ?, ?, ?) - ON CONFLICT (trigger_id) DO UPDATE SET - guild_id = excluded.guild_id, - label = excluded.label, - category_id = excluded.category_id, - template = excluded.template, - user_limit = excluded.user_limit, - enabled = excluded.enabled, - updated_at = datetime('now')`, - ) - .run(triggerId, guildId, label, categoryId, template, userLimit, enabled ? 1 : 0); -} - -export function getVoiceTrigger(triggerId) { - return getDatabase().prepare('SELECT * FROM voice_triggers WHERE trigger_id = ?').get(triggerId) ?? null; -} - -/** All the triggers of a guild, disabled ones included, in creation order. */ -export function listVoiceTriggers(guildId) { - return getDatabase() - .prepare('SELECT * FROM voice_triggers WHERE guild_id = ? ORDER BY created_at ASC, trigger_id ASC') - .all(guildId); -} - -export function removeVoiceTrigger(triggerId) { - return getDatabase().prepare('DELETE FROM voice_triggers WHERE trigger_id = ?').run(triggerId).changes; -} - -export function countVoiceTriggers(guildId) { - const row = getDatabase() - .prepare('SELECT COUNT(*) AS count FROM voice_triggers WHERE guild_id = ?') - .get(guildId); - return row.count; -} +import { getDatabase } from '../index.js'; + +/** + * Declares (or updates) a trigger channel. Every value is explicit: the service merges the + * previous row before writing, so an omitted option keeps its stored value (M14-T01). + */ +export function upsertVoiceTrigger({ + triggerId, + guildId, + label = null, + categoryId = null, + template = null, + userLimit = 0, + enabled = true, +}) { + getDatabase() + .prepare( + `INSERT INTO voice_triggers (trigger_id, guild_id, label, category_id, template, user_limit, enabled) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (trigger_id) DO UPDATE SET + guild_id = excluded.guild_id, + label = excluded.label, + category_id = excluded.category_id, + template = excluded.template, + user_limit = excluded.user_limit, + enabled = excluded.enabled, + updated_at = datetime('now')`, + ) + .run(triggerId, guildId, label, categoryId, template, userLimit, enabled ? 1 : 0); +} + +export function getVoiceTrigger(triggerId) { + return getDatabase().prepare('SELECT * FROM voice_triggers WHERE trigger_id = ?').get(triggerId) ?? null; +} + +/** All the triggers of a guild, disabled ones included, in creation order. */ +export function listVoiceTriggers(guildId) { + return getDatabase() + .prepare('SELECT * FROM voice_triggers WHERE guild_id = ? ORDER BY created_at ASC, trigger_id ASC') + .all(guildId); +} + +export function removeVoiceTrigger(triggerId) { + return getDatabase().prepare('DELETE FROM voice_triggers WHERE trigger_id = ?').run(triggerId).changes; +} + +export function countVoiceTriggers(guildId) { + const row = getDatabase() + .prepare('SELECT COUNT(*) AS count FROM voice_triggers WHERE guild_id = ?') + .get(guildId); + return row.count; +} diff --git a/src/events/client-error.js b/src/events/client-error.js index 372002b..9c6824a 100644 --- a/src/events/client-error.js +++ b/src/events/client-error.js @@ -1,10 +1,10 @@ -import { Events } from 'discord.js'; -import { createLogger } from '../core/logger.js'; - -const log = createLogger('discord'); - -export const name = Events.Error; - -export async function execute(_client, error) { - log.error('Discord client error', error); -} +import { Events } from 'discord.js'; +import { createLogger } from '../core/logger.js'; + +const log = createLogger('discord'); + +export const name = Events.Error; + +export async function execute(_client, error) { + log.error('Discord client error', error); +} diff --git a/src/events/client-ready.js b/src/events/client-ready.js index 6c05fd6..964e69a 100644 --- a/src/events/client-ready.js +++ b/src/events/client-ready.js @@ -1,21 +1,21 @@ -import { Events } from 'discord.js'; -import { createLogger } from '../core/logger.js'; -import { startPollScheduler } from '../services/polls/poll-service.js'; -import { startBotStatusRotation } from '../services/status/bot-status-service.js'; -import { startVoiceJanitor, sweepVoiceChannels } from '../services/voice/voice-service.js'; - -const log = createLogger('discord'); - -export const name = Events.ClientReady; -export const once = true; - -export async function execute(client) { - startPollScheduler(client); - await sweepVoiceChannels(client); - startVoiceJanitor(client); - startBotStatusRotation(client); - log.info(`Connected as ${client.user.tag}`, { - guilds: client.guilds.cache.size, - commands: client.commands.size, - }); -} +import { Events } from 'discord.js'; +import { createLogger } from '../core/logger.js'; +import { startPollScheduler } from '../services/polls/poll-service.js'; +import { startBotStatusRotation } from '../services/status/bot-status-service.js'; +import { startVoiceJanitor, sweepVoiceChannels } from '../services/voice/voice-service.js'; + +const log = createLogger('discord'); + +export const name = Events.ClientReady; +export const once = true; + +export async function execute(client) { + startPollScheduler(client); + await sweepVoiceChannels(client); + startVoiceJanitor(client); + startBotStatusRotation(client); + log.info(`Connected as ${client.user.tag}`, { + guilds: client.guilds.cache.size, + commands: client.commands.size, + }); +} diff --git a/src/events/guild-member-add.js b/src/events/guild-member-add.js index de17058..8b0b8e2 100644 --- a/src/events/guild-member-add.js +++ b/src/events/guild-member-add.js @@ -1,20 +1,20 @@ -import { Events } from 'discord.js'; -import { createLogger } from '../core/logger.js'; -import { - assignMemberRole, - sendWelcome, - sendWelcomeDirectMessage, -} from '../services/members/member-service.js'; - -const log = createLogger('members'); - -export const name = Events.GuildMemberAdd; - -/** Welcome message, resources and default role (M7-T01..T04). */ -export async function execute(client, member) { - log.info('Member joined', { userId: member.id, guildId: member.guild.id }); - - await assignMemberRole(member); - await sendWelcome(client, member); - await sendWelcomeDirectMessage(member); -} +import { Events } from 'discord.js'; +import { createLogger } from '../core/logger.js'; +import { + assignMemberRole, + sendWelcome, + sendWelcomeDirectMessage, +} from '../services/members/member-service.js'; + +const log = createLogger('members'); + +export const name = Events.GuildMemberAdd; + +/** Welcome message, resources and default role (M7-T01..T04). */ +export async function execute(client, member) { + log.info('Member joined', { userId: member.id, guildId: member.guild.id }); + + await assignMemberRole(member); + await sendWelcome(client, member); + await sendWelcomeDirectMessage(member); +} diff --git a/src/events/guild-member-remove.js b/src/events/guild-member-remove.js index 39240f7..586e014 100644 --- a/src/events/guild-member-remove.js +++ b/src/events/guild-member-remove.js @@ -1,13 +1,13 @@ -import { Events } from 'discord.js'; -import { createLogger } from '../core/logger.js'; -import { announceDeparture } from '../services/members/member-service.js'; - -const log = createLogger('members'); - -export const name = Events.GuildMemberRemove; - -/** Announces and records departures (M7-T04). */ -export async function execute(client, member) { - log.info('Member left', { userId: member.id, guildId: member.guild.id }); - await announceDeparture(client, member); -} +import { Events } from 'discord.js'; +import { createLogger } from '../core/logger.js'; +import { announceDeparture } from '../services/members/member-service.js'; + +const log = createLogger('members'); + +export const name = Events.GuildMemberRemove; + +/** Announces and records departures (M7-T04). */ +export async function execute(client, member) { + log.info('Member left', { userId: member.id, guildId: member.guild.id }); + await announceDeparture(client, member); +} diff --git a/src/events/interaction-create.js b/src/events/interaction-create.js index 116b82d..f5e9d88 100644 --- a/src/events/interaction-create.js +++ b/src/events/interaction-create.js @@ -1,88 +1,88 @@ -import { Events, MessageFlags } from 'discord.js'; -import { ACCESS_LABELS } from '../config/constants.js'; -import { PermissionDeniedError, UserFacingError } from '../core/errors.js'; -import { createLogger } from '../core/logger.js'; -import { hasAccess } from '../core/permissions.js'; -import { handleGiteaModal } from '../services/gitea/gitea-modals.js'; -import { handlePollComponent } from '../services/polls/poll-service.js'; -import { handleTicketComponent } from '../services/tickets/ticket-service.js'; -import { handleVoiceComponent, handleVoiceModal } from '../services/voice/voice-service.js'; -import { errorEmbed } from '../ui/embeds.js'; - -const log = createLogger('interactions'); - -export const name = Events.InteractionCreate; - -/** Custom id prefix -> handlers for the message components and the modals. */ -const routes = [ - { prefix: 'ticket:', component: handleTicketComponent }, - { prefix: 'poll:', component: handlePollComponent }, - { prefix: 'voice:', component: handleVoiceComponent, modal: handleVoiceModal }, - { prefix: 'issue:', modal: handleGiteaModal }, - { prefix: 'pr:', modal: handleGiteaModal }, -]; - -async function replyError(interaction, message) { - const payload = { embeds: [errorEmbed(message)], flags: MessageFlags.Ephemeral }; - if (interaction.deferred || interaction.replied) { - await interaction.followUp(payload); - } else { - await interaction.reply(payload); - } -} - -async function runChatInputCommand(interaction) { - const command = interaction.client.commands.get(interaction.commandName); - if (!command) return; - - const subcommand = interaction.options.getSubcommand(false); - const requiredLevel = command.subcommandAccess?.[subcommand] ?? command.access; - if (!hasAccess(interaction.member, requiredLevel)) { - throw new PermissionDeniedError( - `Cette commande demande le niveau **${ACCESS_LABELS[requiredLevel]}**. Si tu en as besoin, demande à une personne du staff : elle peut le faire pour toi.`, - ); - } - await command.execute(interaction); -} - -async function runRoute(interaction, kind) { - const route = routes.find( - ({ prefix, [kind]: handler }) => handler && interaction.customId.startsWith(prefix), - ); - if (!route) { - log.debug(`Ignored ${kind} ${interaction.customId}`); - return; - } - await route[kind](interaction); -} - -export async function execute(_client, interaction) { - try { - if (interaction.isAutocomplete()) { - await interaction.client.commands.get(interaction.commandName)?.autocomplete?.(interaction); - return; - } - if (interaction.isButton() || interaction.isAnySelectMenu()) { - await runRoute(interaction, 'component'); - return; - } - if (interaction.isModalSubmit()) { - await runRoute(interaction, 'modal'); - return; - } - if (!interaction.isChatInputCommand()) return; - - await runChatInputCommand(interaction); - } catch (error) { - if (error instanceof UserFacingError) { - await replyError(interaction, error.message); - return; - } - - log.error(`Interaction failed: ${interaction.commandName ?? interaction.customId ?? 'unknown'}`, error); - await replyError( - interaction, - 'Quelque chose s’est mal passé de mon côté, rien n’est perdu. Réessaie dans un instant — je l’ai noté dans mes logs, l’équipe pourra regarder si ça recommence.', - ).catch(() => {}); - } -} +import { Events, MessageFlags } from 'discord.js'; +import { ACCESS_LABELS } from '../config/constants.js'; +import { PermissionDeniedError, UserFacingError } from '../core/errors.js'; +import { createLogger } from '../core/logger.js'; +import { hasAccess } from '../core/permissions.js'; +import { handleGiteaModal } from '../services/gitea/gitea-modals.js'; +import { handlePollComponent } from '../services/polls/poll-service.js'; +import { handleTicketComponent } from '../services/tickets/ticket-service.js'; +import { handleVoiceComponent, handleVoiceModal } from '../services/voice/voice-service.js'; +import { errorEmbed } from '../ui/embeds.js'; + +const log = createLogger('interactions'); + +export const name = Events.InteractionCreate; + +/** Custom id prefix -> handlers for the message components and the modals. */ +const routes = [ + { prefix: 'ticket:', component: handleTicketComponent }, + { prefix: 'poll:', component: handlePollComponent }, + { prefix: 'voice:', component: handleVoiceComponent, modal: handleVoiceModal }, + { prefix: 'issue:', modal: handleGiteaModal }, + { prefix: 'pr:', modal: handleGiteaModal }, +]; + +async function replyError(interaction, message) { + const payload = { embeds: [errorEmbed(message)], flags: MessageFlags.Ephemeral }; + if (interaction.deferred || interaction.replied) { + await interaction.followUp(payload); + } else { + await interaction.reply(payload); + } +} + +async function runChatInputCommand(interaction) { + const command = interaction.client.commands.get(interaction.commandName); + if (!command) return; + + const subcommand = interaction.options.getSubcommand(false); + const requiredLevel = command.subcommandAccess?.[subcommand] ?? command.access; + if (!hasAccess(interaction.member, requiredLevel)) { + throw new PermissionDeniedError( + `Cette commande demande le niveau **${ACCESS_LABELS[requiredLevel]}**. Si tu en as besoin, demande à une personne du staff : elle peut le faire pour toi.`, + ); + } + await command.execute(interaction); +} + +async function runRoute(interaction, kind) { + const route = routes.find( + ({ prefix, [kind]: handler }) => handler && interaction.customId.startsWith(prefix), + ); + if (!route) { + log.debug(`Ignored ${kind} ${interaction.customId}`); + return; + } + await route[kind](interaction); +} + +export async function execute(_client, interaction) { + try { + if (interaction.isAutocomplete()) { + await interaction.client.commands.get(interaction.commandName)?.autocomplete?.(interaction); + return; + } + if (interaction.isButton() || interaction.isAnySelectMenu()) { + await runRoute(interaction, 'component'); + return; + } + if (interaction.isModalSubmit()) { + await runRoute(interaction, 'modal'); + return; + } + if (!interaction.isChatInputCommand()) return; + + await runChatInputCommand(interaction); + } catch (error) { + if (error instanceof UserFacingError) { + await replyError(interaction, error.message); + return; + } + + log.error(`Interaction failed: ${interaction.commandName ?? interaction.customId ?? 'unknown'}`, error); + await replyError( + interaction, + 'Quelque chose s’est mal passé de mon côté, rien n’est perdu. Réessaie dans un instant — je l’ai noté dans mes logs, l’équipe pourra regarder si ça recommence.', + ).catch(() => {}); + } +} diff --git a/src/events/shard-disconnect.js b/src/events/shard-disconnect.js index 9cbaeb7..149015a 100644 --- a/src/events/shard-disconnect.js +++ b/src/events/shard-disconnect.js @@ -1,11 +1,11 @@ -import { Events } from 'discord.js'; -import { createLogger } from '../core/logger.js'; - -const log = createLogger('discord'); - -// discord.js reconnects automatically with backoff; we only log the lifecycle (M2-T04 / M2-T08). -export const name = Events.ShardDisconnect; - -export async function execute(_client, closeEvent, shardId) { - log.warn('Shard disconnected', { shardId, code: closeEvent?.code }); -} +import { Events } from 'discord.js'; +import { createLogger } from '../core/logger.js'; + +const log = createLogger('discord'); + +// discord.js reconnects automatically with backoff; we only log the lifecycle (M2-T04 / M2-T08). +export const name = Events.ShardDisconnect; + +export async function execute(_client, closeEvent, shardId) { + log.warn('Shard disconnected', { shardId, code: closeEvent?.code }); +} diff --git a/src/events/voice-state-update.js b/src/events/voice-state-update.js index 2e3c6ed..fd43f62 100644 --- a/src/events/voice-state-update.js +++ b/src/events/voice-state-update.js @@ -1,32 +1,32 @@ -import { Events } from 'discord.js'; -import { createLogger } from '../core/logger.js'; -import { cleanupVoiceChannel, createFromTrigger, getVoiceTrigger } from '../services/voice/voice-service.js'; - -const log = createLogger('voice'); - -export const name = Events.VoiceStateUpdate; - -/** - * Joining any of the trigger channels creates a private channel in that trigger's category and - * moves the member in; leaving a temporary channel deletes it once the last member is gone - * (M14-T02 / M14-T04). - */ -export async function execute(_client, oldState, newState) { - const member = newState.member ?? oldState.member; - if (!member || member.user.bot) return; - - try { - const joinedId = - newState.channelId && newState.channelId !== oldState.channelId ? newState.channelId : null; - if (joinedId) { - const trigger = getVoiceTrigger(newState.guild.id, joinedId); - if (trigger) await createFromTrigger(member, trigger); - } - - if (oldState.channelId && oldState.channelId !== newState.channelId) { - await cleanupVoiceChannel(oldState.guild, oldState.channelId); - } - } catch (error) { - log.error('Voice state handling failed', error); - } -} +import { Events } from 'discord.js'; +import { createLogger } from '../core/logger.js'; +import { cleanupVoiceChannel, createFromTrigger, getVoiceTrigger } from '../services/voice/voice-service.js'; + +const log = createLogger('voice'); + +export const name = Events.VoiceStateUpdate; + +/** + * Joining any of the trigger channels creates a private channel in that trigger's category and + * moves the member in; leaving a temporary channel deletes it once the last member is gone + * (M14-T02 / M14-T04). + */ +export async function execute(_client, oldState, newState) { + const member = newState.member ?? oldState.member; + if (!member || member.user.bot) return; + + try { + const joinedId = + newState.channelId && newState.channelId !== oldState.channelId ? newState.channelId : null; + if (joinedId) { + const trigger = getVoiceTrigger(newState.guild.id, joinedId); + if (trigger) await createFromTrigger(member, trigger); + } + + if (oldState.channelId && oldState.channelId !== newState.channelId) { + await cleanupVoiceChannel(oldState.guild, oldState.channelId); + } + } catch (error) { + log.error('Voice state handling failed', error); + } +} diff --git a/src/index.js b/src/index.js index 429666d..548fbf2 100644 --- a/src/index.js +++ b/src/index.js @@ -1,35 +1,35 @@ -import { assertRequiredEnv, env } from './config/env.js'; -import { createClient } from './core/client.js'; -import { loadCommands } from './core/command-loader.js'; -import { registerEvents } from './core/event-loader.js'; -import { logger } from './core/logger.js'; -import { closeDatabase, initDatabase } from './database/index.js'; -import { startWebhookServer } from './webhooks/server.js'; - -assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']); - -initDatabase(); - -const client = createClient(); - -for (const command of await loadCommands()) { - client.commands.set(command.data.name, command); -} -await registerEvents(client); - -const webhookServer = env.webhook.enabled ? startWebhookServer(client) : null; - -process.on('unhandledRejection', (reason) => logger.error('Unhandled promise rejection', reason)); -process.on('uncaughtException', (error) => logger.error('Uncaught exception', error)); - -async function shutdown(signal) { - logger.info(`Received ${signal}, shutting down`); - webhookServer?.close(); - await client.destroy(); - closeDatabase(); - process.exit(0); -} -process.once('SIGINT', shutdown); -process.once('SIGTERM', shutdown); - -await client.login(env.discord.token); +import { assertRequiredEnv, env } from './config/env.js'; +import { createClient } from './core/client.js'; +import { loadCommands } from './core/command-loader.js'; +import { registerEvents } from './core/event-loader.js'; +import { logger } from './core/logger.js'; +import { closeDatabase, initDatabase } from './database/index.js'; +import { startWebhookServer } from './webhooks/server.js'; + +assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']); + +initDatabase(); + +const client = createClient(); + +for (const command of await loadCommands()) { + client.commands.set(command.data.name, command); +} +await registerEvents(client); + +const webhookServer = env.webhook.enabled ? startWebhookServer(client) : null; + +process.on('unhandledRejection', (reason) => logger.error('Unhandled promise rejection', reason)); +process.on('uncaughtException', (error) => logger.error('Uncaught exception', error)); + +async function shutdown(signal) { + logger.info(`Received ${signal}, shutting down`); + webhookServer?.close(); + await client.destroy(); + closeDatabase(); + process.exit(0); +} +process.once('SIGINT', shutdown); +process.once('SIGTERM', shutdown); + +await client.login(env.discord.token); diff --git a/src/services/gitea/gitea-client.js b/src/services/gitea/gitea-client.js index 332a31a..845d9fd 100644 --- a/src/services/gitea/gitea-client.js +++ b/src/services/gitea/gitea-client.js @@ -1,69 +1,69 @@ -import { env } from '../../config/env.js'; -import { ExternalApiError } from '../../core/errors.js'; -import { withRetry } from '../../utils/retry.js'; - -const isTransient = (error) => error.name === 'TimeoutError' || error.status === 429 || error.status >= 500; - -/** Minimal Gitea REST API client (M5-T01). */ -export async function giteaRequest(endpoint, { method = 'GET', body } = {}) { - if (!env.gitea.url || !env.gitea.token) { - throw new ExternalApiError('gitea', 'Gitea is not configured'); - } - - return withRetry( - async () => { - const response = await fetch(`${env.gitea.url}/api/v1${endpoint}`, { - method, - headers: { - Authorization: `token ${env.gitea.token}`, - Accept: 'application/json', - ...(body && { 'Content-Type': 'application/json' }), - }, - body: body ? JSON.stringify(body) : undefined, - signal: AbortSignal.timeout(env.gitea.timeoutMs), - }); - - if (!response.ok) { - const error = new ExternalApiError('gitea', `${method} ${endpoint} failed with ${response.status}`); - error.status = response.status; - throw error; - } - return response.status === 204 ? null : response.json(); - }, - { retries: env.gitea.maxRetries, shouldRetry: isTransient }, - ); -} - -/** True when both the Gitea URL and token are configured (M5-T01). */ -export function isGiteaConfigured() { - return Boolean(env.gitea.url && env.gitea.token); -} - -/** Gitea returns either a bare array or a `{ data: [...] }` wrapper depending on the version. */ -export function asList(payload) { - if (Array.isArray(payload)) return payload; - return Array.isArray(payload?.data) ? payload.data : []; -} - -/** Human readable URL of the configured repository, used in embeds. */ -export function repositoryUrl() { - return env.gitea.url ? `${env.gitea.url}/${env.gitea.owner}/${env.gitea.repo}` : ''; -} - -const repoPath = () => `/repos/${env.gitea.owner}/${env.gitea.repo}`; - -export const gitea = { - listIssues: (params = 'state=open&type=issues&limit=10') => giteaRequest(`${repoPath()}/issues?${params}`), - getIssue: (number) => giteaRequest(`${repoPath()}/issues/${number}`), - createIssue: ({ title, body }) => - giteaRequest(`${repoPath()}/issues`, { method: 'POST', body: { title, body } }), - listPullRequests: (params = 'state=open&limit=10') => giteaRequest(`${repoPath()}/pulls?${params}`), - getPullRequest: (number) => giteaRequest(`${repoPath()}/pulls/${number}`), - createPullRequest: ({ title, body, head, base }) => - giteaRequest(`${repoPath()}/pulls`, { method: 'POST', body: { title, body, head, base } }), - listCommits: (limit = 10) => giteaRequest(`${repoPath()}/commits?limit=${limit}`), - listReleases: (limit = 5) => giteaRequest(`${repoPath()}/releases?limit=${limit}`), - getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`), - getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`), - listBranches: (limit = 20) => giteaRequest(`${repoPath()}/branches?limit=${limit}`), -}; +import { env } from '../../config/env.js'; +import { ExternalApiError } from '../../core/errors.js'; +import { withRetry } from '../../utils/retry.js'; + +const isTransient = (error) => error.name === 'TimeoutError' || error.status === 429 || error.status >= 500; + +/** Minimal Gitea REST API client (M5-T01). */ +export async function giteaRequest(endpoint, { method = 'GET', body } = {}) { + if (!env.gitea.url || !env.gitea.token) { + throw new ExternalApiError('gitea', 'Gitea is not configured'); + } + + return withRetry( + async () => { + const response = await fetch(`${env.gitea.url}/api/v1${endpoint}`, { + method, + headers: { + Authorization: `token ${env.gitea.token}`, + Accept: 'application/json', + ...(body && { 'Content-Type': 'application/json' }), + }, + body: body ? JSON.stringify(body) : undefined, + signal: AbortSignal.timeout(env.gitea.timeoutMs), + }); + + if (!response.ok) { + const error = new ExternalApiError('gitea', `${method} ${endpoint} failed with ${response.status}`); + error.status = response.status; + throw error; + } + return response.status === 204 ? null : response.json(); + }, + { retries: env.gitea.maxRetries, shouldRetry: isTransient }, + ); +} + +/** True when both the Gitea URL and token are configured (M5-T01). */ +export function isGiteaConfigured() { + return Boolean(env.gitea.url && env.gitea.token); +} + +/** Gitea returns either a bare array or a `{ data: [...] }` wrapper depending on the version. */ +export function asList(payload) { + if (Array.isArray(payload)) return payload; + return Array.isArray(payload?.data) ? payload.data : []; +} + +/** Human readable URL of the configured repository, used in embeds. */ +export function repositoryUrl() { + return env.gitea.url ? `${env.gitea.url}/${env.gitea.owner}/${env.gitea.repo}` : ''; +} + +const repoPath = () => `/repos/${env.gitea.owner}/${env.gitea.repo}`; + +export const gitea = { + listIssues: (params = 'state=open&type=issues&limit=10') => giteaRequest(`${repoPath()}/issues?${params}`), + getIssue: (number) => giteaRequest(`${repoPath()}/issues/${number}`), + createIssue: ({ title, body }) => + giteaRequest(`${repoPath()}/issues`, { method: 'POST', body: { title, body } }), + listPullRequests: (params = 'state=open&limit=10') => giteaRequest(`${repoPath()}/pulls?${params}`), + getPullRequest: (number) => giteaRequest(`${repoPath()}/pulls/${number}`), + createPullRequest: ({ title, body, head, base }) => + giteaRequest(`${repoPath()}/pulls`, { method: 'POST', body: { title, body, head, base } }), + listCommits: (limit = 10) => giteaRequest(`${repoPath()}/commits?limit=${limit}`), + listReleases: (limit = 5) => giteaRequest(`${repoPath()}/releases?limit=${limit}`), + getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`), + getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`), + listBranches: (limit = 20) => giteaRequest(`${repoPath()}/branches?limit=${limit}`), +}; diff --git a/src/services/gitea/gitea-embeds.js b/src/services/gitea/gitea-embeds.js index e6fdffd..453a7fe 100644 --- a/src/services/gitea/gitea-embeds.js +++ b/src/services/gitea/gitea-embeds.js @@ -1,97 +1,97 @@ -import { COLORS } from '../../config/constants.js'; -import { baseEmbed } from '../../ui/embeds.js'; - -const DESCRIPTION_MAX = 1500; - -/** Truncates free text coming from the API before it reaches Discord. */ -export function truncate(text, max = DESCRIPTION_MAX) { - const value = String(text ?? '').trim(); - if (!value) return ''; - return value.length > max ? `${value.slice(0, max - 1)}…` : value; -} - -/** Falls back to a neutral word: the value always sits next to a person, never a role. */ -const authorOf = (source) => - source?.user?.login ?? source?.sender?.login ?? source?.author?.name ?? 'compte inconnu'; - -/** Shared header of an issue, used by `/issue` and the webhooks (M5-T02 / M9-T04). */ -export function issueEmbed(issue) { - const embed = baseEmbed(COLORS.gitea) - .setTitle(`#${issue.number} ${issue.title}`) - .setDescription(truncate(issue.body) || 'Aucune description fournie.') - .addFields( - { name: 'Ouverte par', value: authorOf(issue), inline: true }, - { name: 'État', value: issue.state === 'closed' ? 'Fermée' : 'Ouverte', inline: true }, - { name: 'Commentaires', value: String(issue.comments ?? 0), inline: true }, - ); - if (issue.html_url) embed.setURL(issue.html_url); - - const labels = (issue.labels ?? []).map((label) => label.name).filter(Boolean); - if (labels.length > 0) embed.addFields({ name: 'Étiquettes', value: labels.join(', ') }); - return embed; -} - -/** Shared header of a pull request (M5-T04 / M9-T05). */ -export function pullRequestEmbed(pull) { - const state = pull.merged ? 'Fusionnée' : pull.state === 'closed' ? 'Fermée' : 'Ouverte'; - const embed = baseEmbed(COLORS.gitea) - .setTitle(`PR #${pull.number} ${pull.title}`) - .setDescription(truncate(pull.body) || 'Aucune description fournie.') - .addFields( - { name: 'Proposée par', value: authorOf(pull), inline: true }, - { name: 'État', value: state, inline: true }, - { name: 'Branches', value: `${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'}`, inline: true }, - ); - if (pull.html_url) embed.setURL(pull.html_url); - return embed; -} - -/** Release notes, shared by `/fws version`, `/fws changelog` and the webhooks. */ -export function releaseEmbed(release, { withNotes = true } = {}) { - const embed = baseEmbed(COLORS.gitea) - .setTitle(`${release.name || release.tag_name}`) - .addFields( - { name: 'Tag', value: release.tag_name ?? 'inconnu', inline: true }, - { name: 'Publiée par', value: authorOf(release), inline: true }, - { name: 'Pré-version', value: release.prerelease ? 'Oui' : 'Non', inline: true }, - ); - if (release.html_url) embed.setURL(release.html_url); - if (release.published_at) { - const timestamp = Math.floor(new Date(release.published_at).getTime() / 1000); - embed.addFields({ name: 'Date', value: ``, inline: true }); - } - if (withNotes && release.body) embed.setDescription(truncate(release.body, 3900)); - return embed; -} - -/** Push notification: the last commits of a branch (M9-T06). */ -export function pushEmbed(payload, maxCommits = 5) { - const commits = payload.commits ?? []; - const branch = (payload.ref ?? '').replace('refs/heads/', ''); - const lines = commits - .slice(0, maxCommits) - .map((commit) => `\`${String(commit.id).slice(0, 7)}\` ${truncate(commit.message?.split('\n')[0], 90)}`); - const remaining = commits.length - lines.length; - - const embed = baseEmbed(COLORS.gitea) - .setTitle(`Push sur ${branch || 'le dépôt'}`) - .setDescription(lines.join('\n') || 'Aucun commit à afficher pour cet événement.') - .addFields( - { name: 'Poussé par', value: authorOf(payload), inline: true }, - { name: 'Commits', value: String(commits.length), inline: true }, - ); - if (remaining > 0) embed.addFields({ name: 'Et aussi', value: `${remaining} commit(s) de plus` }); - if (payload.repository?.html_url) embed.setURL(payload.repository.html_url); - return embed; -} - -/** Git references created or deleted (`create` / `delete` events). */ -export function refEmbed(payload, action) { - const ref = payload.ref ?? 'inconnu'; - const refType = payload.ref_type ?? 'ref'; - const embed = baseEmbed(COLORS.gitea) - .setTitle(`${action === 'deleted' ? 'Suppression' : 'Création'} de ${refType} : ${ref}`) - .setDescription(`${authorOf(payload)} a ${action === 'deleted' ? 'supprimé' : 'créé'} \`${ref}\`.`); - if (payload.repository?.html_url) embed.setURL(payload.repository.html_url); - return embed; -} +import { COLORS } from '../../config/constants.js'; +import { baseEmbed } from '../../ui/embeds.js'; + +const DESCRIPTION_MAX = 1500; + +/** Truncates free text coming from the API before it reaches Discord. */ +export function truncate(text, max = DESCRIPTION_MAX) { + const value = String(text ?? '').trim(); + if (!value) return ''; + return value.length > max ? `${value.slice(0, max - 1)}…` : value; +} + +/** Falls back to a neutral word: the value always sits next to a person, never a role. */ +const authorOf = (source) => + source?.user?.login ?? source?.sender?.login ?? source?.author?.name ?? 'compte inconnu'; + +/** Shared header of an issue, used by `/issue` and the webhooks (M5-T02 / M9-T04). */ +export function issueEmbed(issue) { + const embed = baseEmbed(COLORS.gitea) + .setTitle(`#${issue.number} ${issue.title}`) + .setDescription(truncate(issue.body) || 'Aucune description fournie.') + .addFields( + { name: 'Ouverte par', value: authorOf(issue), inline: true }, + { name: 'État', value: issue.state === 'closed' ? 'Fermée' : 'Ouverte', inline: true }, + { name: 'Commentaires', value: String(issue.comments ?? 0), inline: true }, + ); + if (issue.html_url) embed.setURL(issue.html_url); + + const labels = (issue.labels ?? []).map((label) => label.name).filter(Boolean); + if (labels.length > 0) embed.addFields({ name: 'Étiquettes', value: labels.join(', ') }); + return embed; +} + +/** Shared header of a pull request (M5-T04 / M9-T05). */ +export function pullRequestEmbed(pull) { + const state = pull.merged ? 'Fusionnée' : pull.state === 'closed' ? 'Fermée' : 'Ouverte'; + const embed = baseEmbed(COLORS.gitea) + .setTitle(`PR #${pull.number} ${pull.title}`) + .setDescription(truncate(pull.body) || 'Aucune description fournie.') + .addFields( + { name: 'Proposée par', value: authorOf(pull), inline: true }, + { name: 'État', value: state, inline: true }, + { name: 'Branches', value: `${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'}`, inline: true }, + ); + if (pull.html_url) embed.setURL(pull.html_url); + return embed; +} + +/** Release notes, shared by `/fws version`, `/fws changelog` and the webhooks. */ +export function releaseEmbed(release, { withNotes = true } = {}) { + const embed = baseEmbed(COLORS.gitea) + .setTitle(`${release.name || release.tag_name}`) + .addFields( + { name: 'Tag', value: release.tag_name ?? 'inconnu', inline: true }, + { name: 'Publiée par', value: authorOf(release), inline: true }, + { name: 'Pré-version', value: release.prerelease ? 'Oui' : 'Non', inline: true }, + ); + if (release.html_url) embed.setURL(release.html_url); + if (release.published_at) { + const timestamp = Math.floor(new Date(release.published_at).getTime() / 1000); + embed.addFields({ name: 'Date', value: ``, inline: true }); + } + if (withNotes && release.body) embed.setDescription(truncate(release.body, 3900)); + return embed; +} + +/** Push notification: the last commits of a branch (M9-T06). */ +export function pushEmbed(payload, maxCommits = 5) { + const commits = payload.commits ?? []; + const branch = (payload.ref ?? '').replace('refs/heads/', ''); + const lines = commits + .slice(0, maxCommits) + .map((commit) => `\`${String(commit.id).slice(0, 7)}\` ${truncate(commit.message?.split('\n')[0], 90)}`); + const remaining = commits.length - lines.length; + + const embed = baseEmbed(COLORS.gitea) + .setTitle(`Push sur ${branch || 'le dépôt'}`) + .setDescription(lines.join('\n') || 'Aucun commit à afficher pour cet événement.') + .addFields( + { name: 'Poussé par', value: authorOf(payload), inline: true }, + { name: 'Commits', value: String(commits.length), inline: true }, + ); + if (remaining > 0) embed.addFields({ name: 'Et aussi', value: `${remaining} commit(s) de plus` }); + if (payload.repository?.html_url) embed.setURL(payload.repository.html_url); + return embed; +} + +/** Git references created or deleted (`create` / `delete` events). */ +export function refEmbed(payload, action) { + const ref = payload.ref ?? 'inconnu'; + const refType = payload.ref_type ?? 'ref'; + const embed = baseEmbed(COLORS.gitea) + .setTitle(`${action === 'deleted' ? 'Suppression' : 'Création'} de ${refType} : ${ref}`) + .setDescription(`${authorOf(payload)} a ${action === 'deleted' ? 'supprimé' : 'créé'} \`${ref}\`.`); + if (payload.repository?.html_url) embed.setURL(payload.repository.html_url); + return embed; +} diff --git a/src/services/gitea/gitea-modals.js b/src/services/gitea/gitea-modals.js index 44c04fa..91463e5 100644 --- a/src/services/gitea/gitea-modals.js +++ b/src/services/gitea/gitea-modals.js @@ -1,152 +1,152 @@ -import { ActionRowBuilder, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js'; -import { ExternalApiError, UserFacingError } from '../../core/errors.js'; -import { createLogger } from '../../core/logger.js'; -import { logEvent } from '../../database/repositories/event-log-repository.js'; -import { linkButtons } from '../../ui/buttons.js'; -import { errorEmbed } from '../../ui/embeds.js'; -import { issueEmbed, pullRequestEmbed } from './gitea-embeds.js'; -import { gitea, isGiteaConfigured } from './gitea-client.js'; -import { consume, remember } from './pending-actions.js'; - -const log = createLogger('gitea'); - -const PR_CONTEXT_TTL_MS = 10 * 60_000; - -/** Fails fast with an actionable message when Gitea is not configured (M5-T01). */ -export function assertGiteaConfigured() { - if (!isGiteaConfigured()) { - throw new UserFacingError( - 'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`. Tout le reste du bot fonctionne sans cela.', - ); - } -} - -function modal(id, title, fields) { - return new ModalBuilder() - .setCustomId(id) - .setTitle(title) - .addComponents( - fields.map((field) => - new ActionRowBuilder().addComponents( - new TextInputBuilder() - .setCustomId(field.id) - .setLabel(field.label) - .setStyle(field.paragraph ? TextInputStyle.Paragraph : TextInputStyle.Short) - .setMaxLength(field.maxLength) - .setRequired(field.required ?? true), - ), - ), - ); -} - -/** `/issue create` collects the title and description through a modal (M5-T03). */ -export async function openIssueModal(interaction) { - assertGiteaConfigured(); - await interaction.showModal( - modal('issue:create', 'Nouvelle issue Gitea', [ - { id: 'title', label: 'Titre', maxLength: 200 }, - { id: 'body', label: 'Description', paragraph: true, maxLength: 4000 }, - ]), - ); -} - -/** `/pr create` keeps the branch options and asks for the title through a modal. */ -export async function openPullRequestModal(interaction) { - assertGiteaConfigured(); - const head = interaction.options.getString('head', true); - const base = interaction.options.getString('base', true); - - remember(`pr:${interaction.user.id}`, { head, base }, { ttlMs: PR_CONTEXT_TTL_MS }); - await interaction.showModal( - modal('pr:create', 'Nouvelle pull request', [ - { id: 'title', label: `Titre (${head} → ${base})`, maxLength: 200 }, - { id: 'body', label: 'Description', paragraph: true, maxLength: 4000, required: false }, - ]), - ); -} - -/** Turns an API failure into a message the user can act on (M5-T08). */ -export async function replyGiteaFailure(interaction, error) { - log.error('Gitea request failed', error); - const detail = - error instanceof ExternalApiError && /not configured/.test(error.message) - ? 'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`.' - : 'Gitea ne répond pas pour le moment. Réessaie dans quelques instants — si ça persiste, préviens l’équipe.'; - const payload = { embeds: [errorEmbed(detail)], flags: MessageFlags.Ephemeral }; - - if (interaction.deferred || interaction.replied) { - await interaction.followUp(payload).catch(() => {}); - } else { - await interaction.reply(payload).catch(() => {}); - } -} - -export async function submitIssueModal(interaction) { - assertGiteaConfigured(); - await interaction.deferReply(); - - try { - const issue = await gitea.createIssue({ - title: interaction.fields.getTextInputValue('title'), - body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`, - }); - logEvent({ - guildId: interaction.guildId, - type: 'gitea.issue.created', - actorId: interaction.user.id, - payload: { number: issue.number }, - }); - await interaction.editReply({ - embeds: [issueEmbed(issue)], - components: linkButtons([{ label: 'Ouvrir sur Gitea', url: issue.html_url }]), - }); - } catch (error) { - await replyGiteaFailure(interaction, error); - } -} - -export async function submitPullRequestModal(interaction) { - assertGiteaConfigured(); - const context = consume(`pr:${interaction.user.id}`); - if (!context) { - throw new UserFacingError( - 'La sélection des branches a expiré : relance `/pr create` pour les choisir à nouveau.', - ); - } - - await interaction.deferReply(); - try { - const pull = await gitea.createPullRequest({ - title: interaction.fields.getTextInputValue('title'), - body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`.trim(), - head: context.head, - base: context.base, - }); - logEvent({ - guildId: interaction.guildId, - type: 'gitea.pull_request.created', - actorId: interaction.user.id, - payload: { number: pull.number, head: context.head, base: context.base }, - }); - await interaction.editReply({ - embeds: [pullRequestEmbed(pull)], - components: linkButtons([{ label: 'Ouvrir sur Gitea', url: pull.html_url }]), - }); - } catch (error) { - await replyGiteaFailure(interaction, error); - } -} - -/** Routes the modal submissions opened by `/issue` and `/pr` (M5-T09). */ -export async function handleGiteaModal(interaction) { - switch (interaction.customId) { - case 'issue:create': - await submitIssueModal(interaction); - return; - case 'pr:create': - await submitPullRequestModal(interaction); - return; - default: - log.debug(`Ignored unknown modal ${interaction.customId}`); - } -} +import { ActionRowBuilder, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js'; +import { ExternalApiError, UserFacingError } from '../../core/errors.js'; +import { createLogger } from '../../core/logger.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { linkButtons } from '../../ui/buttons.js'; +import { errorEmbed } from '../../ui/embeds.js'; +import { issueEmbed, pullRequestEmbed } from './gitea-embeds.js'; +import { gitea, isGiteaConfigured } from './gitea-client.js'; +import { consume, remember } from './pending-actions.js'; + +const log = createLogger('gitea'); + +const PR_CONTEXT_TTL_MS = 10 * 60_000; + +/** Fails fast with an actionable message when Gitea is not configured (M5-T01). */ +export function assertGiteaConfigured() { + if (!isGiteaConfigured()) { + throw new UserFacingError( + 'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`. Tout le reste du bot fonctionne sans cela.', + ); + } +} + +function modal(id, title, fields) { + return new ModalBuilder() + .setCustomId(id) + .setTitle(title) + .addComponents( + fields.map((field) => + new ActionRowBuilder().addComponents( + new TextInputBuilder() + .setCustomId(field.id) + .setLabel(field.label) + .setStyle(field.paragraph ? TextInputStyle.Paragraph : TextInputStyle.Short) + .setMaxLength(field.maxLength) + .setRequired(field.required ?? true), + ), + ), + ); +} + +/** `/issue create` collects the title and description through a modal (M5-T03). */ +export async function openIssueModal(interaction) { + assertGiteaConfigured(); + await interaction.showModal( + modal('issue:create', 'Nouvelle issue Gitea', [ + { id: 'title', label: 'Titre', maxLength: 200 }, + { id: 'body', label: 'Description', paragraph: true, maxLength: 4000 }, + ]), + ); +} + +/** `/pr create` keeps the branch options and asks for the title through a modal. */ +export async function openPullRequestModal(interaction) { + assertGiteaConfigured(); + const head = interaction.options.getString('head', true); + const base = interaction.options.getString('base', true); + + remember(`pr:${interaction.user.id}`, { head, base }, { ttlMs: PR_CONTEXT_TTL_MS }); + await interaction.showModal( + modal('pr:create', 'Nouvelle pull request', [ + { id: 'title', label: `Titre (${head} → ${base})`, maxLength: 200 }, + { id: 'body', label: 'Description', paragraph: true, maxLength: 4000, required: false }, + ]), + ); +} + +/** Turns an API failure into a message the user can act on (M5-T08). */ +export async function replyGiteaFailure(interaction, error) { + log.error('Gitea request failed', error); + const detail = + error instanceof ExternalApiError && /not configured/.test(error.message) + ? 'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`.' + : 'Gitea ne répond pas pour le moment. Réessaie dans quelques instants — si ça persiste, préviens l’équipe.'; + const payload = { embeds: [errorEmbed(detail)], flags: MessageFlags.Ephemeral }; + + if (interaction.deferred || interaction.replied) { + await interaction.followUp(payload).catch(() => {}); + } else { + await interaction.reply(payload).catch(() => {}); + } +} + +export async function submitIssueModal(interaction) { + assertGiteaConfigured(); + await interaction.deferReply(); + + try { + const issue = await gitea.createIssue({ + title: interaction.fields.getTextInputValue('title'), + body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`, + }); + logEvent({ + guildId: interaction.guildId, + type: 'gitea.issue.created', + actorId: interaction.user.id, + payload: { number: issue.number }, + }); + await interaction.editReply({ + embeds: [issueEmbed(issue)], + components: linkButtons([{ label: 'Ouvrir sur Gitea', url: issue.html_url }]), + }); + } catch (error) { + await replyGiteaFailure(interaction, error); + } +} + +export async function submitPullRequestModal(interaction) { + assertGiteaConfigured(); + const context = consume(`pr:${interaction.user.id}`); + if (!context) { + throw new UserFacingError( + 'La sélection des branches a expiré : relance `/pr create` pour les choisir à nouveau.', + ); + } + + await interaction.deferReply(); + try { + const pull = await gitea.createPullRequest({ + title: interaction.fields.getTextInputValue('title'), + body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`.trim(), + head: context.head, + base: context.base, + }); + logEvent({ + guildId: interaction.guildId, + type: 'gitea.pull_request.created', + actorId: interaction.user.id, + payload: { number: pull.number, head: context.head, base: context.base }, + }); + await interaction.editReply({ + embeds: [pullRequestEmbed(pull)], + components: linkButtons([{ label: 'Ouvrir sur Gitea', url: pull.html_url }]), + }); + } catch (error) { + await replyGiteaFailure(interaction, error); + } +} + +/** Routes the modal submissions opened by `/issue` and `/pr` (M5-T09). */ +export async function handleGiteaModal(interaction) { + switch (interaction.customId) { + case 'issue:create': + await submitIssueModal(interaction); + return; + case 'pr:create': + await submitPullRequestModal(interaction); + return; + default: + log.debug(`Ignored unknown modal ${interaction.customId}`); + } +} diff --git a/src/services/gitea/pending-actions.js b/src/services/gitea/pending-actions.js index e8c4c9d..c5edb80 100644 --- a/src/services/gitea/pending-actions.js +++ b/src/services/gitea/pending-actions.js @@ -1,32 +1,32 @@ -/** - * In-memory store for the short-lived context of a modal flow, e.g. the branches - * of `/pr create` which are typed as options but sent with the modal (M5-T04). - * Entries expire on their own and disappear on restart. - */ -const DEFAULT_TTL_MS = 5 * 60_000; - -const entries = new Map(); - -export function remember(key, value, { ttlMs = DEFAULT_TTL_MS, now = Date.now() } = {}) { - entries.set(key, { value, expiresAt: now + ttlMs }); - return value; -} - -/** Returns the stored value and forgets it, or null when missing or expired. */ -export function consume(key, { now = Date.now() } = {}) { - const entry = entries.get(key); - if (!entry) return null; - entries.delete(key); - return entry.expiresAt > now ? entry.value : null; -} - -export function purgeExpired(now = Date.now()) { - for (const [key, entry] of entries) { - if (entry.expiresAt <= now) entries.delete(key); - } - return entries.size; -} - -export function pendingCount() { - return entries.size; -} +/** + * In-memory store for the short-lived context of a modal flow, e.g. the branches + * of `/pr create` which are typed as options but sent with the modal (M5-T04). + * Entries expire on their own and disappear on restart. + */ +const DEFAULT_TTL_MS = 5 * 60_000; + +const entries = new Map(); + +export function remember(key, value, { ttlMs = DEFAULT_TTL_MS, now = Date.now() } = {}) { + entries.set(key, { value, expiresAt: now + ttlMs }); + return value; +} + +/** Returns the stored value and forgets it, or null when missing or expired. */ +export function consume(key, { now = Date.now() } = {}) { + const entry = entries.get(key); + if (!entry) return null; + entries.delete(key); + return entry.expiresAt > now ? entry.value : null; +} + +export function purgeExpired(now = Date.now()) { + for (const [key, entry] of entries) { + if (entry.expiresAt <= now) entries.delete(key); + } + return entries.size; +} + +export function pendingCount() { + return entries.size; +} diff --git a/src/services/members/member-service.js b/src/services/members/member-service.js index f3413bb..6f20982 100644 --- a/src/services/members/member-service.js +++ b/src/services/members/member-service.js @@ -1,115 +1,115 @@ -import { COLORS } from '../../config/constants.js'; -import { env } from '../../config/env.js'; -import { createLogger } from '../../core/logger.js'; -import { logEvent } from '../../database/repositories/event-log-repository.js'; -import { baseEmbed } from '../../ui/embeds.js'; - -const log = createLogger('members'); - -const DEFAULT_WELCOME = 'Bienvenue sur le serveur **FWS** !'; - -async function sendTo(channel) { - return channel?.isSendable() ? channel : null; -} - -/** Sends the welcome embed in `CHANNEL_WELCOME_ID` (M7-T01 / M7-T02). */ -export async function sendWelcome(client, member) { - if (!env.channels.welcome) { - log.debug('No welcome channel configured'); - return; - } - - const channel = await sendTo(await client.channels.fetch(env.channels.welcome).catch(() => null)); - if (!channel) { - log.warn('Welcome channel unavailable', { channelId: env.channels.welcome }); - return; - } - - const embed = baseEmbed(COLORS.primary) - .setTitle('🎉 Nouveau membre') - .setDescription(`${member} vient d’arriver. ${DEFAULT_WELCOME}`) - .addFields({ name: 'Membres', value: String(member.guild.memberCount), inline: true }) - .setThumbnail(member.user.displayAvatarURL({ size: 128 })); - - if (env.channels.rules) { - embed.addFields({ name: 'Règlement', value: `À lire ici : <#${env.channels.rules}>` }); - } - - await channel.send({ content: `${member}`, embeds: [embed] }); - logEvent({ guildId: member.guild.id, type: 'member.welcome', payload: { userId: member.id } }); -} - -/** Gives the default member role (M7-T03). */ -export async function assignMemberRole(member) { - const roleId = env.roles.member; - if (!roleId || member.roles.cache.has(roleId)) return; - - const role = await member.guild.roles.fetch(roleId).catch(() => null); - if (!role) { - log.warn('Default member role not found', { roleId }); - return; - } - if (member.guild.members.me?.roles.highest.comparePositionTo(role) <= 0) { - log.warn('Member role is above the bot role, skipping', { roleId }); - return; - } - - await member.roles.add(role, 'Rôle par défaut à l’arrivée').catch((error) => { - log.warn('Could not assign the member role', error); - }); -} - -/** Welcomes the member in a direct message with the server resources (M7-T02). */ -export async function sendWelcomeDirectMessage(member) { - const links = [ - env.links.website && `[Site officiel](${env.links.website})`, - env.links.docs && `[Documentation](${env.links.docs})`, - env.links.archRepo && `[Dépôt FWS Arch](${env.links.archRepo})`, - ].filter(Boolean); - - const embed = baseEmbed(COLORS.primary) - .setTitle(`Bienvenue sur ${member.guild.name} !`) - .setDescription( - 'Merci d’avoir rejoint la communauté FWS 🌱 Prends un instant pour lire le règlement, ' + - 'puis présente‑toi si tu le souhaites : on adore découvrir les nouvelles personnes.', - ); - if (links.length > 0) embed.addFields({ name: 'Ressources', value: links.join('\n') }); - - await member.send({ embeds: [embed] }).catch(() => { - log.debug('Welcome DM could not be delivered', { userId: member.id }); - }); -} - -/** Logs a departure in the log channel (M7-T04). */ -export async function announceDeparture(client, member) { - const channelId = env.channels.logs || env.channels.modLogs; - if (!channelId) return; - - const channel = await sendTo(await client.channels.fetch(channelId).catch(() => null)); - if (!channel) return; - - const joinedAt = member.joinedTimestamp; - const embed = baseEmbed(COLORS.warning) - .setTitle('👋 Départ d’un membre') - .setDescription(`${member.user.tag} a quitté le serveur.`) - .addFields( - { name: 'Membres', value: String(member.guild.memberCount), inline: true }, - { - name: 'Compte créé', - value: ``, - inline: true, - }, - ) - .setThumbnail(member.user.displayAvatarURL({ size: 128 })); - - if (joinedAt) { - embed.addFields({ name: 'Arrivé', value: ``, inline: true }); - } - - await channel.send({ embeds: [embed] }); - logEvent({ - guildId: member.guild.id, - type: 'member.left', - payload: { userId: member.id, joinedAt: joinedAt ?? null }, - }); -} +import { COLORS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { baseEmbed } from '../../ui/embeds.js'; + +const log = createLogger('members'); + +const DEFAULT_WELCOME = 'Bienvenue sur le serveur **FWS** !'; + +async function sendTo(channel) { + return channel?.isSendable() ? channel : null; +} + +/** Sends the welcome embed in `CHANNEL_WELCOME_ID` (M7-T01 / M7-T02). */ +export async function sendWelcome(client, member) { + if (!env.channels.welcome) { + log.debug('No welcome channel configured'); + return; + } + + const channel = await sendTo(await client.channels.fetch(env.channels.welcome).catch(() => null)); + if (!channel) { + log.warn('Welcome channel unavailable', { channelId: env.channels.welcome }); + return; + } + + const embed = baseEmbed(COLORS.primary) + .setTitle('🎉 Nouveau membre') + .setDescription(`${member} vient d’arriver. ${DEFAULT_WELCOME}`) + .addFields({ name: 'Membres', value: String(member.guild.memberCount), inline: true }) + .setThumbnail(member.user.displayAvatarURL({ size: 128 })); + + if (env.channels.rules) { + embed.addFields({ name: 'Règlement', value: `À lire ici : <#${env.channels.rules}>` }); + } + + await channel.send({ content: `${member}`, embeds: [embed] }); + logEvent({ guildId: member.guild.id, type: 'member.welcome', payload: { userId: member.id } }); +} + +/** Gives the default member role (M7-T03). */ +export async function assignMemberRole(member) { + const roleId = env.roles.member; + if (!roleId || member.roles.cache.has(roleId)) return; + + const role = await member.guild.roles.fetch(roleId).catch(() => null); + if (!role) { + log.warn('Default member role not found', { roleId }); + return; + } + if (member.guild.members.me?.roles.highest.comparePositionTo(role) <= 0) { + log.warn('Member role is above the bot role, skipping', { roleId }); + return; + } + + await member.roles.add(role, 'Rôle par défaut à l’arrivée').catch((error) => { + log.warn('Could not assign the member role', error); + }); +} + +/** Welcomes the member in a direct message with the server resources (M7-T02). */ +export async function sendWelcomeDirectMessage(member) { + const links = [ + env.links.website && `[Site officiel](${env.links.website})`, + env.links.docs && `[Documentation](${env.links.docs})`, + env.links.archRepo && `[Dépôt FWS Arch](${env.links.archRepo})`, + ].filter(Boolean); + + const embed = baseEmbed(COLORS.primary) + .setTitle(`Bienvenue sur ${member.guild.name} !`) + .setDescription( + 'Merci d’avoir rejoint la communauté FWS 🌱 Prends un instant pour lire le règlement, ' + + 'puis présente‑toi si tu le souhaites : on adore découvrir les nouvelles personnes.', + ); + if (links.length > 0) embed.addFields({ name: 'Ressources', value: links.join('\n') }); + + await member.send({ embeds: [embed] }).catch(() => { + log.debug('Welcome DM could not be delivered', { userId: member.id }); + }); +} + +/** Logs a departure in the log channel (M7-T04). */ +export async function announceDeparture(client, member) { + const channelId = env.channels.logs || env.channels.modLogs; + if (!channelId) return; + + const channel = await sendTo(await client.channels.fetch(channelId).catch(() => null)); + if (!channel) return; + + const joinedAt = member.joinedTimestamp; + const embed = baseEmbed(COLORS.warning) + .setTitle('👋 Départ d’un membre') + .setDescription(`${member.user.tag} a quitté le serveur.`) + .addFields( + { name: 'Membres', value: String(member.guild.memberCount), inline: true }, + { + name: 'Compte créé', + value: ``, + inline: true, + }, + ) + .setThumbnail(member.user.displayAvatarURL({ size: 128 })); + + if (joinedAt) { + embed.addFields({ name: 'Arrivé', value: ``, inline: true }); + } + + await channel.send({ embeds: [embed] }); + logEvent({ + guildId: member.guild.id, + type: 'member.left', + payload: { userId: member.id, joinedAt: joinedAt ?? null }, + }); +} diff --git a/src/services/moderation/moderation-service.js b/src/services/moderation/moderation-service.js index 5b05656..b0562f8 100644 --- a/src/services/moderation/moderation-service.js +++ b/src/services/moderation/moderation-service.js @@ -1,132 +1,132 @@ -import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js'; -import { env } from '../../config/env.js'; -import { UserFacingError } from '../../core/errors.js'; -import { canActOn } from '../../core/permissions.js'; -import { logEvent } from '../../database/repositories/event-log-repository.js'; -import { recordAction } from '../../database/repositories/moderation-repository.js'; -import { baseEmbed } from '../../ui/embeds.js'; - -/** - * Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08). - * @param {import('discord.js').ChatInputCommandInteraction} interaction - * @param {import('discord.js').GuildMember} target - */ -export function assertModerationTarget(interaction, target) { - if (!target) { - throw new UserFacingError( - 'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.', - ); - } - if (target.id === interaction.user.id) { - throw new UserFacingError('Tu ne peux pas t’appliquer cette action à toi‑même 😅 Vise un autre membre.'); - } - if (!canActOn(interaction.member, target)) { - throw new UserFacingError( - 'Cette personne a un rôle égal ou supérieur au tien : je ne peux pas la viser. Demande à quelqu’un de plus haut dans la hiérarchie si c’est nécessaire.', - ); - } - - const bot = interaction.guild.members.me; - if (bot && bot.roles.highest.comparePositionTo(target.roles.highest) <= 0) { - throw new UserFacingError( - `Je ne peux pas agir sur ${target.user.tag} : mon rôle est placé plus bas que le sien. Remonte mon rôle dans les paramètres du serveur, et je m’en occupe.`, - ); - } -} - -/** - * Records the action in SQLite and mirrors it in the moderation log channel (M8-T06). - * Call it only once the Discord action has succeeded. - */ -export async function logModerationAction( - interaction, - { action, targetId, reason = null, durationMs = null }, -) { - recordAction({ - guildId: interaction.guildId, - action, - moderatorId: interaction.user.id, - targetId, - reason, - durationMs, - }); - logEvent({ - guildId: interaction.guildId, - type: `moderation.${action}`, - actorId: interaction.user.id, - payload: { targetId, reason, durationMs }, - }); - - const meta = MODERATION_ACTIONS[action]; - await sendModerationLog(interaction.client, interaction.guild, { - action, - color: meta?.color ?? COLORS.moderation, - targetId, - moderatorId: interaction.user.id, - reason, - durationMs, - }); -} - -/** Posts an entry in `CHANNEL_MOD_LOGS_ID`, if configured (M8-T06). */ -export async function sendModerationLog( - client, - guild, - { action, targetId, moderatorId, reason, durationMs }, -) { - if (!env.channels.modLogs) return; - - const channel = await client.channels.fetch(env.channels.modLogs).catch(() => null); - if (!channel?.isSendable()) return; - - const meta = MODERATION_ACTIONS[action]; - const embed = baseEmbed(meta?.color) - .setTitle(`🛡️ Modération — ${meta?.label ?? action}`) - .addFields( - { name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true }, - { name: 'Par', value: `<@${moderatorId}>`, inline: true }, - { name: 'Motif', value: reason || 'Non précisé' }, - ); - if (durationMs) { - embed.addFields({ name: 'Durée', value: formatDuration(durationMs), inline: true }); - } - if (guild) embed.setFooter({ text: `${guild.name} · ${guild.id}` }); - - await channel.send({ embeds: [embed] }).catch(() => {}); -} - -/** Direct message sent to the member who is being moderated (M8-T07). */ -export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) { - const meta = MODERATION_ACTIONS[action]; - const embed = baseEmbed(meta?.color) - .setTitle(`Sanction sur ${guildName}`) - .setDescription( - `Action : **${meta?.label ?? action}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`, - ) - .addFields({ name: 'Motif', value: reason || 'Non précisé' }); - if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) }); - return embed; -} - -/** Human readable duration for embeds: `2 h 30 min`. */ -export function formatDuration(durationMs) { - const minutes = Math.round(durationMs / 60_000); - if (minutes < 60) return `${minutes} min`; - const hours = Math.floor(minutes / 60); - const rest = minutes % 60; - if (hours < 24) return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`; - const days = Math.floor(hours / 24); - const remainingHours = hours % 24; - return remainingHours === 0 ? `${days} j` : `${days} j ${remainingHours} h`; -} - -/** Fetches the member targeted by a command, with a clear error if absent. */ -export async function fetchTargetMember(interaction, userId) { - const member = await interaction.guild.members.fetch(userId).catch(() => null); - if (!member) { - throw new UserFacingError( - 'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.', - ); - } - return member; -} +import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { UserFacingError } from '../../core/errors.js'; +import { canActOn } from '../../core/permissions.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { recordAction } from '../../database/repositories/moderation-repository.js'; +import { baseEmbed } from '../../ui/embeds.js'; + +/** + * Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08). + * @param {import('discord.js').ChatInputCommandInteraction} interaction + * @param {import('discord.js').GuildMember} target + */ +export function assertModerationTarget(interaction, target) { + if (!target) { + throw new UserFacingError( + 'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.', + ); + } + if (target.id === interaction.user.id) { + throw new UserFacingError('Tu ne peux pas t’appliquer cette action à toi‑même 😅 Vise un autre membre.'); + } + if (!canActOn(interaction.member, target)) { + throw new UserFacingError( + 'Cette personne a un rôle égal ou supérieur au tien : je ne peux pas la viser. Demande à quelqu’un de plus haut dans la hiérarchie si c’est nécessaire.', + ); + } + + const bot = interaction.guild.members.me; + if (bot && bot.roles.highest.comparePositionTo(target.roles.highest) <= 0) { + throw new UserFacingError( + `Je ne peux pas agir sur ${target.user.tag} : mon rôle est placé plus bas que le sien. Remonte mon rôle dans les paramètres du serveur, et je m’en occupe.`, + ); + } +} + +/** + * Records the action in SQLite and mirrors it in the moderation log channel (M8-T06). + * Call it only once the Discord action has succeeded. + */ +export async function logModerationAction( + interaction, + { action, targetId, reason = null, durationMs = null }, +) { + recordAction({ + guildId: interaction.guildId, + action, + moderatorId: interaction.user.id, + targetId, + reason, + durationMs, + }); + logEvent({ + guildId: interaction.guildId, + type: `moderation.${action}`, + actorId: interaction.user.id, + payload: { targetId, reason, durationMs }, + }); + + const meta = MODERATION_ACTIONS[action]; + await sendModerationLog(interaction.client, interaction.guild, { + action, + color: meta?.color ?? COLORS.moderation, + targetId, + moderatorId: interaction.user.id, + reason, + durationMs, + }); +} + +/** Posts an entry in `CHANNEL_MOD_LOGS_ID`, if configured (M8-T06). */ +export async function sendModerationLog( + client, + guild, + { action, targetId, moderatorId, reason, durationMs }, +) { + if (!env.channels.modLogs) return; + + const channel = await client.channels.fetch(env.channels.modLogs).catch(() => null); + if (!channel?.isSendable()) return; + + const meta = MODERATION_ACTIONS[action]; + const embed = baseEmbed(meta?.color) + .setTitle(`🛡️ Modération — ${meta?.label ?? action}`) + .addFields( + { name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true }, + { name: 'Par', value: `<@${moderatorId}>`, inline: true }, + { name: 'Motif', value: reason || 'Non précisé' }, + ); + if (durationMs) { + embed.addFields({ name: 'Durée', value: formatDuration(durationMs), inline: true }); + } + if (guild) embed.setFooter({ text: `${guild.name} · ${guild.id}` }); + + await channel.send({ embeds: [embed] }).catch(() => {}); +} + +/** Direct message sent to the member who is being moderated (M8-T07). */ +export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) { + const meta = MODERATION_ACTIONS[action]; + const embed = baseEmbed(meta?.color) + .setTitle(`Sanction sur ${guildName}`) + .setDescription( + `Action : **${meta?.label ?? action}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`, + ) + .addFields({ name: 'Motif', value: reason || 'Non précisé' }); + if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) }); + return embed; +} + +/** Human readable duration for embeds: `2 h 30 min`. */ +export function formatDuration(durationMs) { + const minutes = Math.round(durationMs / 60_000); + if (minutes < 60) return `${minutes} min`; + const hours = Math.floor(minutes / 60); + const rest = minutes % 60; + if (hours < 24) return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`; + const days = Math.floor(hours / 24); + const remainingHours = hours % 24; + return remainingHours === 0 ? `${days} j` : `${days} j ${remainingHours} h`; +} + +/** Fetches the member targeted by a command, with a clear error if absent. */ +export async function fetchTargetMember(interaction, userId) { + const member = await interaction.guild.members.fetch(userId).catch(() => null); + if (!member) { + throw new UserFacingError( + 'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.', + ); + } + return member; +} diff --git a/src/services/notifications/gitea-notifications.js b/src/services/notifications/gitea-notifications.js index 0358d95..06c667d 100644 --- a/src/services/notifications/gitea-notifications.js +++ b/src/services/notifications/gitea-notifications.js @@ -1,31 +1,31 @@ -import { GITEA_EVENT_TYPES } from '../../config/constants.js'; -import { issueEmbed, pullRequestEmbed, pushEmbed, releaseEmbed, refEmbed } from '../gitea/gitea-embeds.js'; - -/** - * Maps a raw Gitea webhook to `{ type, embed }`, or returns null when the event - * should not be published (M9-T03). - */ -export function buildGiteaNotification(event, payload) { - const type = GITEA_EVENT_TYPES[event]; - if (!type) return null; - - switch (event) { - case 'issues': - return { type, embed: issueEmbed(payload.issue ?? payload) }; - case 'pull_request': - return { type, embed: pullRequestEmbed(payload.pull_request ?? payload) }; - case 'push': - if (!payload.commits?.length) return null; - return { type, embed: pushEmbed(payload) }; - case 'create': - case 'delete': - return { - type, - embed: refEmbed(payload, payload.ref_type && event === 'delete' ? 'deleted' : 'created'), - }; - case 'release': - return { type, embed: releaseEmbed(payload.release ?? payload) }; - default: - return null; - } -} +import { GITEA_EVENT_TYPES } from '../../config/constants.js'; +import { issueEmbed, pullRequestEmbed, pushEmbed, releaseEmbed, refEmbed } from '../gitea/gitea-embeds.js'; + +/** + * Maps a raw Gitea webhook to `{ type, embed }`, or returns null when the event + * should not be published (M9-T03). + */ +export function buildGiteaNotification(event, payload) { + const type = GITEA_EVENT_TYPES[event]; + if (!type) return null; + + switch (event) { + case 'issues': + return { type, embed: issueEmbed(payload.issue ?? payload) }; + case 'pull_request': + return { type, embed: pullRequestEmbed(payload.pull_request ?? payload) }; + case 'push': + if (!payload.commits?.length) return null; + return { type, embed: pushEmbed(payload) }; + case 'create': + case 'delete': + return { + type, + embed: refEmbed(payload, payload.ref_type && event === 'delete' ? 'deleted' : 'created'), + }; + case 'release': + return { type, embed: releaseEmbed(payload.release ?? payload) }; + default: + return null; + } +} diff --git a/src/services/notifications/notification-service.js b/src/services/notifications/notification-service.js index faf139a..999824a 100644 --- a/src/services/notifications/notification-service.js +++ b/src/services/notifications/notification-service.js @@ -1,61 +1,61 @@ -import { env } from '../../config/env.js'; -import { createLogger } from '../../core/logger.js'; -import { getNotificationChannel } from '../../database/repositories/notification-repository.js'; -import { errorEmbed } from '../../ui/embeds.js'; - -const log = createLogger('notifications'); - -/** Fallback routing from the environment when the guild has no override (M9-T01). */ -const defaultChannels = { - issues: env.channels.notifIssues, - pull_request: env.channels.notifPullRequests, - push: env.channels.notifCommits, - release: env.channels.notifReleases, - errors: env.channels.notifErrors, - announcements: env.channels.announcements, - community: env.channels.logs, -}; - -/** SQLite override first, then the environment default (M9-T01). */ -export function resolveChannelId(type, guildId = env.discord.guildId) { - try { - if (guildId) { - const override = getNotificationChannel(guildId, type); - if (override?.channel_id) return override.channel_id; - } - } catch { - // The database is unavailable (tests, early startup): use the environment. - } - return defaultChannels[type] ?? null; -} - -/** Sends a notification payload to the channel configured for its type (M9). */ -export async function notify(client, type, payload) { - const channelId = resolveChannelId(type); - if (!channelId) { - log.debug(`No channel configured for notification type ${type}`); - return null; - } - - const channel = await client.channels.fetch(channelId).catch(() => null); - if (!channel?.isSendable()) { - log.warn(`Notification channel unavailable for ${type}`, { channelId }); - return null; - } - return channel.send(payload); -} - -/** Reports an unexpected failure in the technical channel (M9-T07). */ -export async function notifyError(client, error, context = 'application') { - log.error(`Notification error (${context})`, error); - return notify(client, 'errors', { - embeds: [ - errorEmbed( - `Un incident est survenu dans **${context}**. Rien d’inquiétant pour les membres : je continue de fonctionner, mais l’équipe technique gagne à y jeter un œil.`, - ).addFields({ - name: 'Détail', - value: `\`${String(error?.message ?? error).slice(0, 500)}\``, - }), - ], - }); -} +import { env } from '../../config/env.js'; +import { createLogger } from '../../core/logger.js'; +import { getNotificationChannel } from '../../database/repositories/notification-repository.js'; +import { errorEmbed } from '../../ui/embeds.js'; + +const log = createLogger('notifications'); + +/** Fallback routing from the environment when the guild has no override (M9-T01). */ +const defaultChannels = { + issues: env.channels.notifIssues, + pull_request: env.channels.notifPullRequests, + push: env.channels.notifCommits, + release: env.channels.notifReleases, + errors: env.channels.notifErrors, + announcements: env.channels.announcements, + community: env.channels.logs, +}; + +/** SQLite override first, then the environment default (M9-T01). */ +export function resolveChannelId(type, guildId = env.discord.guildId) { + try { + if (guildId) { + const override = getNotificationChannel(guildId, type); + if (override?.channel_id) return override.channel_id; + } + } catch { + // The database is unavailable (tests, early startup): use the environment. + } + return defaultChannels[type] ?? null; +} + +/** Sends a notification payload to the channel configured for its type (M9). */ +export async function notify(client, type, payload) { + const channelId = resolveChannelId(type); + if (!channelId) { + log.debug(`No channel configured for notification type ${type}`); + return null; + } + + const channel = await client.channels.fetch(channelId).catch(() => null); + if (!channel?.isSendable()) { + log.warn(`Notification channel unavailable for ${type}`, { channelId }); + return null; + } + return channel.send(payload); +} + +/** Reports an unexpected failure in the technical channel (M9-T07). */ +export async function notifyError(client, error, context = 'application') { + log.error(`Notification error (${context})`, error); + return notify(client, 'errors', { + embeds: [ + errorEmbed( + `Un incident est survenu dans **${context}**. Rien d’inquiétant pour les membres : je continue de fonctionner, mais l’équipe technique gagne à y jeter un œil.`, + ).addFields({ + name: 'Détail', + value: `\`${String(error?.message ?? error).slice(0, 500)}\``, + }), + ], + }); +} diff --git a/src/services/polls/poll-service.js b/src/services/polls/poll-service.js index e2a0a1d..917cbb9 100644 --- a/src/services/polls/poll-service.js +++ b/src/services/polls/poll-service.js @@ -1,219 +1,219 @@ -import { MessageFlags } from 'discord.js'; -import { COLORS } from '../../config/constants.js'; -import { UserFacingError } from '../../core/errors.js'; -import { createLogger } from '../../core/logger.js'; -import { logEvent } from '../../database/repositories/event-log-repository.js'; -import { - attachPollMessage, - castVote, - closePoll, - countVotes, - createPoll as createPollRow, - getPoll, - listDuePolls, -} from '../../database/repositories/poll-repository.js'; -import { POLL_CHOICES_MAX, pollButtons } from '../../ui/buttons.js'; -import { baseEmbed } from '../../ui/embeds.js'; - -const log = createLogger('polls'); - -const CHOICES_MIN = 2; -const BAR_LENGTH = 12; -const SCHEDULER_INTERVAL_MS = 30_000; - -/** Splits the `choices` option on `;` and validates the count (M10-T01). */ -export function parseChoices(input, { min = CHOICES_MIN, max = POLL_CHOICES_MAX } = {}) { - const choices = String(input) - .split(';') - .map((choice) => choice.trim()) - .filter(Boolean); - - if (choices.length < min || choices.length > max) { - throw new UserFacingError( - `Il faut entre ${min} et ${max} propositions, séparées par des points‑virgules. Exemple : \`Pizza ; Sushis ; Tacos\`.`, - ); - } - if (new Set(choices.map((choice) => choice.toLowerCase())).size !== choices.length) { - throw new UserFacingError( - 'Deux propositions identiques rendraient le vote ambigu : donne un libellé différent à chacune.', - ); - } - return choices; -} - -/** SQLite stores datetimes as UTC `YYYY-MM-DD HH:MM:SS`. */ -export function toSqliteDate(date) { - return date.toISOString().slice(0, 19).replace('T', ' '); -} - -function renderBar(ratio) { - const filled = Math.round(ratio * BAR_LENGTH); - return `${'█'.repeat(filled)}${'░'.repeat(BAR_LENGTH - filled)}`; -} - -/** Results embed, shared by creation, voting and closing (M10-T06). */ -export function buildPollEmbed(poll, counts = countVotes(poll.id)) { - const choices = JSON.parse(poll.choices); - const countFor = (index) => counts.find((row) => row.choice_index === index)?.count ?? 0; - const total = choices.reduce((sum, _choice, index) => sum + countFor(index), 0); - - const lines = choices.map((choice, index) => { - const count = countFor(index); - const percent = total === 0 ? 0 : Math.round((count / total) * 100); - return `**${index + 1}. ${choice}**\n\`${renderBar(total === 0 ? 0 : count / total)}\` ${count} (${percent} %)`; - }); - - const embed = baseEmbed(COLORS.info) - .setTitle(`📊 Sondage #${poll.id} — ${poll.question}`) - .setDescription(lines.join('\n\n')) - .addFields( - { name: 'Votes', value: String(total), inline: true }, - { name: 'Créé par', value: `<@${poll.creator_id}>`, inline: true }, - { name: 'Statut', value: poll.status === 'open' ? 'Ouvert' : 'Fermé', inline: true }, - ); - - if (poll.ends_at) { - const timestamp = Math.floor(new Date(`${poll.ends_at.replace(' ', 'T')}Z`).getTime() / 1000); - embed.addFields({ name: 'Fin', value: ``, inline: true }); - } - if (poll.status === 'closed') { - embed.setColor(COLORS.success); - const best = choices.reduce( - (winner, _choice, index) => (countFor(index) > countFor(winner) ? index : winner), - 0, - ); - const top = countFor(best); - embed.addFields({ - name: 'Résultat', - value: total === 0 || top === 0 ? 'Aucun vote' : `**${choices[best]}** (${top} vote(s))`, - }); - } - return embed; -} - -export function buildPollComponents(poll) { - return poll.status === 'open' ? pollButtons(poll.id, JSON.parse(poll.choices)) : []; -} - -/** Creates the poll message and records it (M10-T01 / M10-T02). */ -export async function createPoll(interaction, { question, choicesInput, minutes = null }) { - const choices = parseChoices(choicesInput); - const endsAt = minutes ? toSqliteDate(new Date(Date.now() + minutes * 60_000)) : null; - - const pollId = createPollRow({ - guildId: interaction.guildId, - channelId: interaction.channelId, - creatorId: interaction.user.id, - question, - choices, - endsAt, - }); - const poll = getPoll(pollId); - - const message = await interaction.channel.send({ - embeds: [buildPollEmbed(poll, [])], - components: buildPollComponents(poll), - }); - attachPollMessage(pollId, message.id); - - logEvent({ - guildId: interaction.guildId, - type: 'poll.created', - actorId: interaction.user.id, - payload: { pollId, choices: choices.length }, - }); - - return pollId; -} - -async function fetchPollMessage(interaction, poll) { - if (!poll.message_id) return null; - return interaction.channel.messages.fetch(poll.message_id).catch(() => null); -} - -/** Closes a poll and freezes its results (M10-T05). */ -export async function closePollById(client, pollId) { - const poll = getPoll(pollId); - if (!poll) { - throw new UserFacingError(`Je ne trouve pas le sondage **#${pollId}** : il a peut‑être été supprimé.`); - } - if (poll.status === 'closed') { - throw new UserFacingError(`Le sondage **#${pollId}** est déjà fermé — les résultats sont figés.`); - } - - closePoll(pollId); - const closed = { ...poll, status: 'closed' }; - - const channel = await client.channels.fetch(poll.channel_id).catch(() => null); - const message = channel?.isSendable() - ? await channel.messages.fetch(poll.message_id).catch(() => null) - : null; - await message?.edit({ embeds: [buildPollEmbed(closed)], components: [] }); - - logEvent({ - guildId: poll.guild_id, - type: 'poll.closed', - payload: { pollId }, - }); - return closed; -} - -/** Registers a vote and refreshes the poll message (M10-T03 / M10-T04). */ -export async function handlePollComponent(interaction) { - const [, rawId, rawIndex] = interaction.customId.split(':'); - const poll = getPoll(Number(rawId)); - if (!poll || poll.status !== 'open') { - throw new UserFacingError('Ce sondage est terminé : les boutons ne prennent plus les votes.'); - } - - const choices = JSON.parse(poll.choices); - const index = Number(rawIndex); - if (!Number.isInteger(index) || index < 0 || index >= choices.length) { - throw new UserFacingError('Cette proposition n’existe plus dans le sondage.'); - } - - const result = castVote(poll.id, interaction.user.id, index); - if (result === 'unchanged') { - await interaction.reply({ - content: `Ton vote est déjà sur **${choices[index]}** — rien n’a bougé.`, - flags: MessageFlags.Ephemeral, - }); - return; - } - - const message = await fetchPollMessage(interaction, poll); - await message?.edit({ embeds: [buildPollEmbed(poll)], components: buildPollComponents(poll) }); - - await interaction.reply({ - content: - result === 'changed' - ? `C’est noté : ton vote va maintenant à **${choices[index]}**.` - : `Merci ! Ton vote est sur **${choices[index]}**.`, - flags: MessageFlags.Ephemeral, - }); -} - -/** Polls expire on their own even without activity (M10-T05). */ -export function startPollScheduler(client) { - const timer = setInterval(async () => { - let due = []; - try { - due = listDuePolls(); - } catch (error) { - log.warn('Could not read the polls to close', error); - return; - } - - for (const poll of due) { - try { - await closePollById(client, poll.id); - log.info(`Closed poll #${poll.id} at its end date`); - } catch (error) { - log.error(`Could not close poll #${poll.id}`, error); - } - } - }, SCHEDULER_INTERVAL_MS); - - timer.unref(); - return timer; -} +import { MessageFlags } from 'discord.js'; +import { COLORS } from '../../config/constants.js'; +import { UserFacingError } from '../../core/errors.js'; +import { createLogger } from '../../core/logger.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { + attachPollMessage, + castVote, + closePoll, + countVotes, + createPoll as createPollRow, + getPoll, + listDuePolls, +} from '../../database/repositories/poll-repository.js'; +import { POLL_CHOICES_MAX, pollButtons } from '../../ui/buttons.js'; +import { baseEmbed } from '../../ui/embeds.js'; + +const log = createLogger('polls'); + +const CHOICES_MIN = 2; +const BAR_LENGTH = 12; +const SCHEDULER_INTERVAL_MS = 30_000; + +/** Splits the `choices` option on `;` and validates the count (M10-T01). */ +export function parseChoices(input, { min = CHOICES_MIN, max = POLL_CHOICES_MAX } = {}) { + const choices = String(input) + .split(';') + .map((choice) => choice.trim()) + .filter(Boolean); + + if (choices.length < min || choices.length > max) { + throw new UserFacingError( + `Il faut entre ${min} et ${max} propositions, séparées par des points‑virgules. Exemple : \`Pizza ; Sushis ; Tacos\`.`, + ); + } + if (new Set(choices.map((choice) => choice.toLowerCase())).size !== choices.length) { + throw new UserFacingError( + 'Deux propositions identiques rendraient le vote ambigu : donne un libellé différent à chacune.', + ); + } + return choices; +} + +/** SQLite stores datetimes as UTC `YYYY-MM-DD HH:MM:SS`. */ +export function toSqliteDate(date) { + return date.toISOString().slice(0, 19).replace('T', ' '); +} + +function renderBar(ratio) { + const filled = Math.round(ratio * BAR_LENGTH); + return `${'█'.repeat(filled)}${'░'.repeat(BAR_LENGTH - filled)}`; +} + +/** Results embed, shared by creation, voting and closing (M10-T06). */ +export function buildPollEmbed(poll, counts = countVotes(poll.id)) { + const choices = JSON.parse(poll.choices); + const countFor = (index) => counts.find((row) => row.choice_index === index)?.count ?? 0; + const total = choices.reduce((sum, _choice, index) => sum + countFor(index), 0); + + const lines = choices.map((choice, index) => { + const count = countFor(index); + const percent = total === 0 ? 0 : Math.round((count / total) * 100); + return `**${index + 1}. ${choice}**\n\`${renderBar(total === 0 ? 0 : count / total)}\` ${count} (${percent} %)`; + }); + + const embed = baseEmbed(COLORS.info) + .setTitle(`📊 Sondage #${poll.id} — ${poll.question}`) + .setDescription(lines.join('\n\n')) + .addFields( + { name: 'Votes', value: String(total), inline: true }, + { name: 'Créé par', value: `<@${poll.creator_id}>`, inline: true }, + { name: 'Statut', value: poll.status === 'open' ? 'Ouvert' : 'Fermé', inline: true }, + ); + + if (poll.ends_at) { + const timestamp = Math.floor(new Date(`${poll.ends_at.replace(' ', 'T')}Z`).getTime() / 1000); + embed.addFields({ name: 'Fin', value: ``, inline: true }); + } + if (poll.status === 'closed') { + embed.setColor(COLORS.success); + const best = choices.reduce( + (winner, _choice, index) => (countFor(index) > countFor(winner) ? index : winner), + 0, + ); + const top = countFor(best); + embed.addFields({ + name: 'Résultat', + value: total === 0 || top === 0 ? 'Aucun vote' : `**${choices[best]}** (${top} vote(s))`, + }); + } + return embed; +} + +export function buildPollComponents(poll) { + return poll.status === 'open' ? pollButtons(poll.id, JSON.parse(poll.choices)) : []; +} + +/** Creates the poll message and records it (M10-T01 / M10-T02). */ +export async function createPoll(interaction, { question, choicesInput, minutes = null }) { + const choices = parseChoices(choicesInput); + const endsAt = minutes ? toSqliteDate(new Date(Date.now() + minutes * 60_000)) : null; + + const pollId = createPollRow({ + guildId: interaction.guildId, + channelId: interaction.channelId, + creatorId: interaction.user.id, + question, + choices, + endsAt, + }); + const poll = getPoll(pollId); + + const message = await interaction.channel.send({ + embeds: [buildPollEmbed(poll, [])], + components: buildPollComponents(poll), + }); + attachPollMessage(pollId, message.id); + + logEvent({ + guildId: interaction.guildId, + type: 'poll.created', + actorId: interaction.user.id, + payload: { pollId, choices: choices.length }, + }); + + return pollId; +} + +async function fetchPollMessage(interaction, poll) { + if (!poll.message_id) return null; + return interaction.channel.messages.fetch(poll.message_id).catch(() => null); +} + +/** Closes a poll and freezes its results (M10-T05). */ +export async function closePollById(client, pollId) { + const poll = getPoll(pollId); + if (!poll) { + throw new UserFacingError(`Je ne trouve pas le sondage **#${pollId}** : il a peut‑être été supprimé.`); + } + if (poll.status === 'closed') { + throw new UserFacingError(`Le sondage **#${pollId}** est déjà fermé — les résultats sont figés.`); + } + + closePoll(pollId); + const closed = { ...poll, status: 'closed' }; + + const channel = await client.channels.fetch(poll.channel_id).catch(() => null); + const message = channel?.isSendable() + ? await channel.messages.fetch(poll.message_id).catch(() => null) + : null; + await message?.edit({ embeds: [buildPollEmbed(closed)], components: [] }); + + logEvent({ + guildId: poll.guild_id, + type: 'poll.closed', + payload: { pollId }, + }); + return closed; +} + +/** Registers a vote and refreshes the poll message (M10-T03 / M10-T04). */ +export async function handlePollComponent(interaction) { + const [, rawId, rawIndex] = interaction.customId.split(':'); + const poll = getPoll(Number(rawId)); + if (!poll || poll.status !== 'open') { + throw new UserFacingError('Ce sondage est terminé : les boutons ne prennent plus les votes.'); + } + + const choices = JSON.parse(poll.choices); + const index = Number(rawIndex); + if (!Number.isInteger(index) || index < 0 || index >= choices.length) { + throw new UserFacingError('Cette proposition n’existe plus dans le sondage.'); + } + + const result = castVote(poll.id, interaction.user.id, index); + if (result === 'unchanged') { + await interaction.reply({ + content: `Ton vote est déjà sur **${choices[index]}** — rien n’a bougé.`, + flags: MessageFlags.Ephemeral, + }); + return; + } + + const message = await fetchPollMessage(interaction, poll); + await message?.edit({ embeds: [buildPollEmbed(poll)], components: buildPollComponents(poll) }); + + await interaction.reply({ + content: + result === 'changed' + ? `C’est noté : ton vote va maintenant à **${choices[index]}**.` + : `Merci ! Ton vote est sur **${choices[index]}**.`, + flags: MessageFlags.Ephemeral, + }); +} + +/** Polls expire on their own even without activity (M10-T05). */ +export function startPollScheduler(client) { + const timer = setInterval(async () => { + let due = []; + try { + due = listDuePolls(); + } catch (error) { + log.warn('Could not read the polls to close', error); + return; + } + + for (const poll of due) { + try { + await closePollById(client, poll.id); + log.info(`Closed poll #${poll.id} at its end date`); + } catch (error) { + log.error(`Could not close poll #${poll.id}`, error); + } + } + }, SCHEDULER_INTERVAL_MS); + + timer.unref(); + return timer; +} diff --git a/src/services/status/bot-status-service.js b/src/services/status/bot-status-service.js index 7ec5696..b4dd22a 100644 --- a/src/services/status/bot-status-service.js +++ b/src/services/status/bot-status-service.js @@ -1,314 +1,314 @@ -import { ActivityType } from 'discord.js'; -import { COLORS } from '../../config/constants.js'; -import { env } from '../../config/env.js'; -import { UserFacingError } from '../../core/errors.js'; -import { createLogger } from '../../core/logger.js'; -import { logEvent } from '../../database/repositories/event-log-repository.js'; -import { - addBotStatus as addBotStatusRow, - clearBotStatuses, - countBotStatuses, - getBotStatus, - listBotStatuses, - listEnabledBotStatuses, - removeBotStatus as removeBotStatusRow, - setBotStatusEnabled, -} from '../../database/repositories/bot-status-repository.js'; -import { resolveSetting, setSetting } from '../../database/repositories/settings-repository.js'; -import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; - -const log = createLogger('status'); - -/** Discord caps an activity name at 128 characters. */ -export const STATUS_TEXT_MAX = 128; -/** Beyond that the picker in `/status list` becomes unreadable; ask for fewer, clearer lines. */ -export const STATUS_MAX = 25; -export const ROTATION_MIN_SECONDS = 5; -export const ROTATION_MAX_SECONDS = 86_400; -/** Key of the rotation delay, stored per guild like the other settings (M15). */ -export const ROTATION_KEY = 'bot.status.interval'; - -/** Shown while the list is empty, so the bot never displays nothing useful. */ -export const FALLBACK_STATUS = Object.freeze({ - id: null, - text: 'les commandes avec /help', - type: 'watching', -}); - -/** - * Accepted activity types. Discord writes the verb itself, so only the label used in the - * embeds lives here; `streaming` is the one type that requires a link. - */ -export const STATUS_TYPES = Object.freeze({ - playing: { label: 'joue à', activity: ActivityType.Playing }, - streaming: { label: 'en direct sur', activity: ActivityType.Streaming, needsUrl: true }, - listening: { label: 'écoute', activity: ActivityType.Listening }, - watching: { label: 'regarde', activity: ActivityType.Watching }, - competing: { label: 'participe à', activity: ActivityType.Competing }, -}); - -/** Choice list for the slash command. */ -export const STATUS_TYPE_CHOICES = Object.freeze( - Object.entries(STATUS_TYPES).map(([value, type]) => ({ name: type.label, value })), -); - -/** Strips control characters without a control-character regex, then collapses the spaces. */ -const clean = (value) => - [...String(value ?? '')] - .map((char) => { - const code = char.codePointAt(0); - return code <= 31 || code === 127 ? ' ' : char; - }) - .join('') - .replace(/\s+/g, ' ') - .trim(); - -export function sanitizeStatusText(value) { - const text = clean(value); - if (!text) { - throw new UserFacingError( - 'Il me manque le texte du statut : écris quelques mots, par exemple « les commandes avec /help ».', - ); - } - if (text.length > STATUS_TEXT_MAX) { - throw new UserFacingError( - `Discord limite un statut à ${STATUS_TEXT_MAX} caractères, et ce texte en fait ${text.length}. Raccourcis‑le un peu.`, - ); - } - return text; -} - -export function normalizeStatusType(value) { - const key = String(value ?? 'watching') - .toLowerCase() - .trim(); - if (!STATUS_TYPES[key]) { - throw new UserFacingError( - `Je ne connais pas ce type de statut. Choisis parmi : ${Object.keys(STATUS_TYPES).join(', ')}.`, - ); - } - return key; -} - -/** Only a streaming status uses a link, and Discord refuses it without a valid URL. */ -export function validateStatusUrl(value, typeKey) { - const url = String(value ?? '').trim(); - if (STATUS_TYPES[typeKey]?.needsUrl && !url) { - throw new UserFacingError( - 'Le type « en direct » a besoin d’un lien (Twitch, YouTube…) : ajoute l’option `url`.', - ); - } - if (!url) return null; - if (!/^https?:\/\/\S+$/i.test(url)) { - throw new UserFacingError('Un lien de diffusion doit commencer par `http://` ou `https://`.'); - } - return url; -} - -/** `45 s`, `5 min`, `2 h 30 min` — used by the embeds of `/status`. */ -export function formatSeconds(seconds) { - const value = Math.max(0, Math.round(Number(seconds) || 0)); - if (value < 60) return `${value} s`; - const minutes = Math.round(value / 60); - if (minutes < 60) return `${minutes} min`; - const hours = Math.floor(minutes / 60); - const rest = minutes % 60; - return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`; -} - -/** Delay used when neither the database nor the environment gives a usable value. */ -const FALLBACK_ROTATION_SECONDS = 60; - -/** The environment default, ignored when it is out of range rather than applied blindly. */ -const envRotationSeconds = () => { - const value = Number(env.bot.statusIntervalSeconds); - return Number.isInteger(value) && value >= ROTATION_MIN_SECONDS && value <= ROTATION_MAX_SECONDS - ? value - : FALLBACK_ROTATION_SECONDS; -}; - -export function clampRotation(value, { strict = false } = {}) { - const seconds = Number(value); - if (!Number.isInteger(seconds) || seconds < ROTATION_MIN_SECONDS || seconds > ROTATION_MAX_SECONDS) { - if (strict) { - throw new UserFacingError( - `Le rythme doit être un nombre de secondes entre ${ROTATION_MIN_SECONDS} et ${ROTATION_MAX_SECONDS} (${formatSeconds(ROTATION_MIN_SECONDS)} à ${formatSeconds(ROTATION_MAX_SECONDS)}).`, - ); - } - return envRotationSeconds(); - } - return seconds; -} - -/** Rotation delay, overridable from Discord; the environment provides the default (M15). */ -export function getRotationSeconds(guildId = env.discord.guildId) { - return clampRotation(resolveSetting(guildId, ROTATION_KEY, env.botStatusIntervalSeconds)); -} - -export function saveRotationSeconds(seconds, guildId = env.discord.guildId, updatedBy = null) { - const value = clampRotation(seconds, { strict: true }); - setSetting(guildId, ROTATION_KEY, value, updatedBy); - return value; -} - -/** Adds a status, or explains why it cannot be added (duplicate text, too many, invalid link). */ -export function addBotStatus({ text, type = 'watching', url = null, createdBy = null } = {}) { - const statusText = sanitizeStatusText(text); - const typeKey = normalizeStatusType(type); - const statusUrl = validateStatusUrl(url, typeKey); - - if (countBotStatuses() >= STATUS_MAX) { - throw new UserFacingError( - `La liste est déjà pleine (${STATUS_MAX} statuts) : supprime‑en un avec \`/status remove\` avant d’en ajouter un autre.`, - ); - } - - let status; - try { - status = addBotStatusRow({ text: statusText, type: typeKey, url: statusUrl, createdBy }); - } catch (error) { - if (!/UNIQUE constraint/i.test(String(error?.message))) throw error; - log.debug('Duplicate status refused', error); - throw new UserFacingError( - `« ${statusText} » est déjà dans la liste : \`/status list\` montre les statuts existants.`, - ); - } - - logEvent({ - guildId: env.discord.guildId, - type: 'bot.status.added', - actorId: createdBy, - payload: { id: status.id }, - }); - return status; -} - -export function removeBotStatus(id) { - const status = getBotStatus(id); - if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`); - removeBotStatusRow(id); - logEvent({ guildId: env.discord.guildId, type: 'bot.status.removed', payload: { id } }); - return status; -} - -export function toggleBotStatus(id, enabled) { - const status = getBotStatus(id); - if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`); - if (Boolean(status.enabled) === enabled) { - throw new UserFacingError( - enabled - ? `Le statut **#${id}** tourne déjà — il n’y a rien à changer.` - : `Le statut **#${id}** est déjà en pause — il n’y a rien à changer.`, - ); - } - - setBotStatusEnabled(id, enabled); - return { ...status, enabled: enabled ? 1 : 0 }; -} - -/** Empties the list; the fallback status takes over immediately. */ -export function clearBotStatusList() { - const removed = clearBotStatuses(); - logEvent({ guildId: env.discord.guildId, type: 'bot.status.cleared', payload: { removed } }); - return removed; -} - -/** - * Next status of the rotation: the enabled ones in insertion order, one after the other. - * Returns `null` when nothing is enabled, so the caller falls back to a default line. - */ -export function selectNextStatus(statuses, lastId = null) { - if (statuses.length === 0) return null; - const index = statuses.findIndex((status) => status.id === lastId); - return statuses[(index + 1) % statuses.length]; -} - -/** Shows one status in Discord. */ -export function applyBotStatus(client, status = FALLBACK_STATUS) { - const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching; - const activity = { name: status.text, type: type.activity }; - if (type.needsUrl && status.url) activity.url = status.url; - - client.user.setPresence({ status: 'online', activities: [activity] }); - return activity; -} - -/** Applies the only enabled status right away, so an addition shows up immediately. */ -export function applyStatusIfAlone(client) { - const statuses = listEnabledBotStatuses(); - if (statuses.length !== 1) return null; - applyBotStatus(client, statuses[0]); - return statuses[0]; -} - -/** Shows the next status and returns it; used by the rotation and by the tests. */ -export function rotateBotStatus(client, lastId = null) { - const status = selectNextStatus(listEnabledBotStatuses(), lastId) ?? FALLBACK_STATUS; - applyBotStatus(client, status); - return status; -} - -/** - * Rotates the statuses forever. The delay is read again on every turn, so `/status interval` - * takes effect without restarting the bot (M15). - */ -export function startBotStatusRotation(client, { guildId = env.discord.guildId } = {}) { - let lastId = null; - let timer = null; - - const tick = () => { - try { - lastId = rotateBotStatus(client, lastId)?.id ?? null; - } catch (error) { - log.warn('Could not rotate the bot status', error); - } - timer = setTimeout(tick, getRotationSeconds(guildId) * 1000); - timer.unref?.(); - }; - - tick(); - return { stop: () => clearTimeout(timer) }; -} - -function describeStatus(status) { - const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching; - const link = type.needsUrl && status.url ? ` · ${status.url}` : ''; - return `« ${status.text} » — ${type.label}${link}`; -} - -/** The list shown by `/status list` (M15). */ -export function statusListEmbed({ guildId = env.discord.guildId, statuses = listBotStatuses() } = {}) { - const embed = baseEmbed(COLORS.primary).setTitle('🎭 Statuts du bot'); - - if (statuses.length === 0) { - return embed.setDescription( - `Aucun statut personnalisé pour le moment : j’affiche « ${FALLBACK_STATUS.text} » en attendant.\n\nAjoute le premier avec \`/status add\`.`, - ); - } - - const active = statuses.filter((status) => status.enabled).length; - embed.setDescription( - `${bullets([ - `**${statuses.length}** statut(s), dont **${active}** en rotation`, - `changement toutes les **${formatSeconds(getRotationSeconds(guildId))}**`, - 'la rotation suit l’ordre d’ajout et saute les statuts en pause', - ])}`, - ); - embed.addFields( - statuses.map((status) => ({ - name: `#${status.id} · ${status.enabled ? '✅ en rotation' : '⛔ en pause'}`, - value: describeStatus(status), - })), - ); - return embed; -} - -/** Confirmation shown after `/status add`, including when the addition changes what is displayed. */ -export function statusAddedEmbed(status, { applied = false } = {}) { - const next = applied - ? 'C’était le premier statut : il s’affiche tout de suite sous le nom du bot.' - : 'Il apparaît dans la rotation ; `/status list` montre l’ensemble.'; - return successEmbed( - `C’est dans la liste : **#${status.id}** — ${describeStatus(status)}.\n\n${next}`, - ).setTitle('✅ Statut ajouté'); -} +import { ActivityType } from 'discord.js'; +import { COLORS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { UserFacingError } from '../../core/errors.js'; +import { createLogger } from '../../core/logger.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { + addBotStatus as addBotStatusRow, + clearBotStatuses, + countBotStatuses, + getBotStatus, + listBotStatuses, + listEnabledBotStatuses, + removeBotStatus as removeBotStatusRow, + setBotStatusEnabled, +} from '../../database/repositories/bot-status-repository.js'; +import { resolveSetting, setSetting } from '../../database/repositories/settings-repository.js'; +import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; + +const log = createLogger('status'); + +/** Discord caps an activity name at 128 characters. */ +export const STATUS_TEXT_MAX = 128; +/** Beyond that the picker in `/status list` becomes unreadable; ask for fewer, clearer lines. */ +export const STATUS_MAX = 25; +export const ROTATION_MIN_SECONDS = 5; +export const ROTATION_MAX_SECONDS = 86_400; +/** Key of the rotation delay, stored per guild like the other settings (M15). */ +export const ROTATION_KEY = 'bot.status.interval'; + +/** Shown while the list is empty, so the bot never displays nothing useful. */ +export const FALLBACK_STATUS = Object.freeze({ + id: null, + text: 'les commandes avec /help', + type: 'watching', +}); + +/** + * Accepted activity types. Discord writes the verb itself, so only the label used in the + * embeds lives here; `streaming` is the one type that requires a link. + */ +export const STATUS_TYPES = Object.freeze({ + playing: { label: 'joue à', activity: ActivityType.Playing }, + streaming: { label: 'en direct sur', activity: ActivityType.Streaming, needsUrl: true }, + listening: { label: 'écoute', activity: ActivityType.Listening }, + watching: { label: 'regarde', activity: ActivityType.Watching }, + competing: { label: 'participe à', activity: ActivityType.Competing }, +}); + +/** Choice list for the slash command. */ +export const STATUS_TYPE_CHOICES = Object.freeze( + Object.entries(STATUS_TYPES).map(([value, type]) => ({ name: type.label, value })), +); + +/** Strips control characters without a control-character regex, then collapses the spaces. */ +const clean = (value) => + [...String(value ?? '')] + .map((char) => { + const code = char.codePointAt(0); + return code <= 31 || code === 127 ? ' ' : char; + }) + .join('') + .replace(/\s+/g, ' ') + .trim(); + +export function sanitizeStatusText(value) { + const text = clean(value); + if (!text) { + throw new UserFacingError( + 'Il me manque le texte du statut : écris quelques mots, par exemple « les commandes avec /help ».', + ); + } + if (text.length > STATUS_TEXT_MAX) { + throw new UserFacingError( + `Discord limite un statut à ${STATUS_TEXT_MAX} caractères, et ce texte en fait ${text.length}. Raccourcis‑le un peu.`, + ); + } + return text; +} + +export function normalizeStatusType(value) { + const key = String(value ?? 'watching') + .toLowerCase() + .trim(); + if (!STATUS_TYPES[key]) { + throw new UserFacingError( + `Je ne connais pas ce type de statut. Choisis parmi : ${Object.keys(STATUS_TYPES).join(', ')}.`, + ); + } + return key; +} + +/** Only a streaming status uses a link, and Discord refuses it without a valid URL. */ +export function validateStatusUrl(value, typeKey) { + const url = String(value ?? '').trim(); + if (STATUS_TYPES[typeKey]?.needsUrl && !url) { + throw new UserFacingError( + 'Le type « en direct » a besoin d’un lien (Twitch, YouTube…) : ajoute l’option `url`.', + ); + } + if (!url) return null; + if (!/^https?:\/\/\S+$/i.test(url)) { + throw new UserFacingError('Un lien de diffusion doit commencer par `http://` ou `https://`.'); + } + return url; +} + +/** `45 s`, `5 min`, `2 h 30 min` — used by the embeds of `/status`. */ +export function formatSeconds(seconds) { + const value = Math.max(0, Math.round(Number(seconds) || 0)); + if (value < 60) return `${value} s`; + const minutes = Math.round(value / 60); + if (minutes < 60) return `${minutes} min`; + const hours = Math.floor(minutes / 60); + const rest = minutes % 60; + return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`; +} + +/** Delay used when neither the database nor the environment gives a usable value. */ +const FALLBACK_ROTATION_SECONDS = 60; + +/** The environment default, ignored when it is out of range rather than applied blindly. */ +const envRotationSeconds = () => { + const value = Number(env.bot.statusIntervalSeconds); + return Number.isInteger(value) && value >= ROTATION_MIN_SECONDS && value <= ROTATION_MAX_SECONDS + ? value + : FALLBACK_ROTATION_SECONDS; +}; + +export function clampRotation(value, { strict = false } = {}) { + const seconds = Number(value); + if (!Number.isInteger(seconds) || seconds < ROTATION_MIN_SECONDS || seconds > ROTATION_MAX_SECONDS) { + if (strict) { + throw new UserFacingError( + `Le rythme doit être un nombre de secondes entre ${ROTATION_MIN_SECONDS} et ${ROTATION_MAX_SECONDS} (${formatSeconds(ROTATION_MIN_SECONDS)} à ${formatSeconds(ROTATION_MAX_SECONDS)}).`, + ); + } + return envRotationSeconds(); + } + return seconds; +} + +/** Rotation delay, overridable from Discord; the environment provides the default (M15). */ +export function getRotationSeconds(guildId = env.discord.guildId) { + return clampRotation(resolveSetting(guildId, ROTATION_KEY, env.botStatusIntervalSeconds)); +} + +export function saveRotationSeconds(seconds, guildId = env.discord.guildId, updatedBy = null) { + const value = clampRotation(seconds, { strict: true }); + setSetting(guildId, ROTATION_KEY, value, updatedBy); + return value; +} + +/** Adds a status, or explains why it cannot be added (duplicate text, too many, invalid link). */ +export function addBotStatus({ text, type = 'watching', url = null, createdBy = null } = {}) { + const statusText = sanitizeStatusText(text); + const typeKey = normalizeStatusType(type); + const statusUrl = validateStatusUrl(url, typeKey); + + if (countBotStatuses() >= STATUS_MAX) { + throw new UserFacingError( + `La liste est déjà pleine (${STATUS_MAX} statuts) : supprime‑en un avec \`/status remove\` avant d’en ajouter un autre.`, + ); + } + + let status; + try { + status = addBotStatusRow({ text: statusText, type: typeKey, url: statusUrl, createdBy }); + } catch (error) { + if (!/UNIQUE constraint/i.test(String(error?.message))) throw error; + log.debug('Duplicate status refused', error); + throw new UserFacingError( + `« ${statusText} » est déjà dans la liste : \`/status list\` montre les statuts existants.`, + ); + } + + logEvent({ + guildId: env.discord.guildId, + type: 'bot.status.added', + actorId: createdBy, + payload: { id: status.id }, + }); + return status; +} + +export function removeBotStatus(id) { + const status = getBotStatus(id); + if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`); + removeBotStatusRow(id); + logEvent({ guildId: env.discord.guildId, type: 'bot.status.removed', payload: { id } }); + return status; +} + +export function toggleBotStatus(id, enabled) { + const status = getBotStatus(id); + if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`); + if (Boolean(status.enabled) === enabled) { + throw new UserFacingError( + enabled + ? `Le statut **#${id}** tourne déjà — il n’y a rien à changer.` + : `Le statut **#${id}** est déjà en pause — il n’y a rien à changer.`, + ); + } + + setBotStatusEnabled(id, enabled); + return { ...status, enabled: enabled ? 1 : 0 }; +} + +/** Empties the list; the fallback status takes over immediately. */ +export function clearBotStatusList() { + const removed = clearBotStatuses(); + logEvent({ guildId: env.discord.guildId, type: 'bot.status.cleared', payload: { removed } }); + return removed; +} + +/** + * Next status of the rotation: the enabled ones in insertion order, one after the other. + * Returns `null` when nothing is enabled, so the caller falls back to a default line. + */ +export function selectNextStatus(statuses, lastId = null) { + if (statuses.length === 0) return null; + const index = statuses.findIndex((status) => status.id === lastId); + return statuses[(index + 1) % statuses.length]; +} + +/** Shows one status in Discord. */ +export function applyBotStatus(client, status = FALLBACK_STATUS) { + const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching; + const activity = { name: status.text, type: type.activity }; + if (type.needsUrl && status.url) activity.url = status.url; + + client.user.setPresence({ status: 'online', activities: [activity] }); + return activity; +} + +/** Applies the only enabled status right away, so an addition shows up immediately. */ +export function applyStatusIfAlone(client) { + const statuses = listEnabledBotStatuses(); + if (statuses.length !== 1) return null; + applyBotStatus(client, statuses[0]); + return statuses[0]; +} + +/** Shows the next status and returns it; used by the rotation and by the tests. */ +export function rotateBotStatus(client, lastId = null) { + const status = selectNextStatus(listEnabledBotStatuses(), lastId) ?? FALLBACK_STATUS; + applyBotStatus(client, status); + return status; +} + +/** + * Rotates the statuses forever. The delay is read again on every turn, so `/status interval` + * takes effect without restarting the bot (M15). + */ +export function startBotStatusRotation(client, { guildId = env.discord.guildId } = {}) { + let lastId = null; + let timer = null; + + const tick = () => { + try { + lastId = rotateBotStatus(client, lastId)?.id ?? null; + } catch (error) { + log.warn('Could not rotate the bot status', error); + } + timer = setTimeout(tick, getRotationSeconds(guildId) * 1000); + timer.unref?.(); + }; + + tick(); + return { stop: () => clearTimeout(timer) }; +} + +function describeStatus(status) { + const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching; + const link = type.needsUrl && status.url ? ` · ${status.url}` : ''; + return `« ${status.text} » — ${type.label}${link}`; +} + +/** The list shown by `/status list` (M15). */ +export function statusListEmbed({ guildId = env.discord.guildId, statuses = listBotStatuses() } = {}) { + const embed = baseEmbed(COLORS.primary).setTitle('🎭 Statuts du bot'); + + if (statuses.length === 0) { + return embed.setDescription( + `Aucun statut personnalisé pour le moment : j’affiche « ${FALLBACK_STATUS.text} » en attendant.\n\nAjoute le premier avec \`/status add\`.`, + ); + } + + const active = statuses.filter((status) => status.enabled).length; + embed.setDescription( + `${bullets([ + `**${statuses.length}** statut(s), dont **${active}** en rotation`, + `changement toutes les **${formatSeconds(getRotationSeconds(guildId))}**`, + 'la rotation suit l’ordre d’ajout et saute les statuts en pause', + ])}`, + ); + embed.addFields( + statuses.map((status) => ({ + name: `#${status.id} · ${status.enabled ? '✅ en rotation' : '⛔ en pause'}`, + value: describeStatus(status), + })), + ); + return embed; +} + +/** Confirmation shown after `/status add`, including when the addition changes what is displayed. */ +export function statusAddedEmbed(status, { applied = false } = {}) { + const next = applied + ? 'C’était le premier statut : il s’affiche tout de suite sous le nom du bot.' + : 'Il apparaît dans la rotation ; `/status list` montre l’ensemble.'; + return successEmbed( + `C’est dans la liste : **#${status.id}** — ${describeStatus(status)}.\n\n${next}`, + ).setTitle('✅ Statut ajouté'); +} diff --git a/src/services/tickets/ticket-service.js b/src/services/tickets/ticket-service.js index 214824e..4666d8c 100644 --- a/src/services/tickets/ticket-service.js +++ b/src/services/tickets/ticket-service.js @@ -1,295 +1,295 @@ -import { ChannelType, PermissionFlagsBits } from 'discord.js'; -import { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js'; -import { env } from '../../config/env.js'; -import { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; -import { createLogger } from '../../core/logger.js'; -import { getAccessLevel } from '../../core/permissions.js'; -import { logEvent } from '../../database/repositories/event-log-repository.js'; -import { - claimTicket as claimTicketRow, - closeTicket as closeTicketRow, - createTicket as createTicketRow, - getTicketByChannel, -} from '../../database/repositories/ticket-repository.js'; -import { ticketButtons } from '../../ui/buttons.js'; -import { baseEmbed, successEmbed } from '../../ui/embeds.js'; - -const log = createLogger('tickets'); - -/** Ticket scope names to the FWS access level they require. */ -const SCOPE_LEVELS = { - staff: ACCESS_LEVELS.STAFF, - dev: ACCESS_LEVELS.DEV, - owner: ACCESS_LEVELS.OWNER, -}; - -export function findCategory(categoryId) { - return TICKET_CATEGORIES.find((category) => category.id === categoryId) ?? null; -} - -/** A member may open a ticket only for a category their access level covers (M6-T02). */ -export function canUseCategory(member, category) { - const level = getAccessLevel(member); - return category.scope.some((scope) => level >= SCOPE_LEVELS[scope]); -} - -/** Static info about a ticket, used by the embeds below. */ -function ticketEmbed(ticket, category) { - const claimed = ticket.claimed_by ? `<@${ticket.claimed_by}>` : 'Personne'; - return baseEmbed(COLORS.ticket) - .setTitle(`🎫 Ticket ${category.label} #${ticket.id}`) - .setDescription( - `<@${ticket.author_id}> décris ta demande ici, avec le plus de détails possible : ` + - 'contexte, étapes pour reproduire, messages d’erreur. Plus tu en dis, plus vite on t’aide.', - ) - .addFields( - { name: 'Catégorie', value: category.label, inline: true }, - { name: 'Statut', value: ticket.status === 'open' ? 'Ouvert' : 'Fermé', inline: true }, - { name: 'Pris en charge par', value: claimed, inline: true }, - ); -} - -function channelName(categoryId, username) { - const slug = username - .toLowerCase() - .normalize('NFD') - .replace(/[\u0300-\u036f]/g, '') - .replace(/[^a-z0-9-]/g, '-') - .replace(/-+/g, '-') - .replace(/^-|-$/g, '') - .slice(0, 40); - return `ticket-${categoryId}-${slug || 'membre'}`.slice(0, 100); -} - -/** Permission overwrites: the author, the staff roles of the scope and the bot (M6-T04). */ -function buildOverwrites(guild, client, category, authorId) { - const allow = [ - PermissionFlagsBits.ViewChannel, - PermissionFlagsBits.SendMessages, - PermissionFlagsBits.ReadMessageHistory, - PermissionFlagsBits.AttachFiles, - ]; - const overwrites = [ - { id: guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel] }, - { id: authorId, allow }, - { id: client.user.id, allow: [...allow, PermissionFlagsBits.ManageChannels] }, - ]; - - for (const scope of category.scope) { - const roleId = env.roles[scope]; - if (roleId) overwrites.push({ id: roleId, allow }); - } - return overwrites; -} - -async function fetchTicketLogChannel(client) { - if (!env.channels.ticketLogs) return null; - const channel = await client.channels.fetch(env.channels.ticketLogs).catch(() => null); - return channel?.isSendable() ? channel : null; -} - -async function logTicket(client, embed) { - const channel = await fetchTicketLogChannel(client); - await channel?.send({ embeds: [embed] }); -} - -/** Opens a private channel for the ticket (M6-T03). */ -export async function createTicket(interaction, categoryId) { - const category = findCategory(categoryId); - if (!category) { - throw new UserFacingError( - 'Je ne connais pas cette catégorie de ticket : `/ticket create` te propose la liste à jour.', - ); - } - if (!canUseCategory(interaction.member, category)) { - throw new UserFacingError( - `La catégorie **${category.label}** est réservée à l’équipe. Tu peux ouvrir un ticket dans une autre catégorie : \`/ticket create\` te montre celles qui te sont ouvertes.`, - ); - } - if (!env.channels.ticketCategory) { - throw new UserFacingError( - 'Les tickets ne sont pas encore installés : il manque `CATEGORY_TICKETS_ID` dans le `.env`. Préviens l’équipe !', - ); - } - - const guild = interaction.guild; - const parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null); - if (parent?.type !== ChannelType.GuildCategory) { - throw new UserFacingError( - '`CATEGORY_TICKETS_ID` ne pointe pas vers une catégorie Discord : je ne peux pas y créer de salon. L’équipe doit corriger le `.env`.', - ); - } - - const channel = await guild.channels.create({ - name: channelName(category.id, interaction.user.username), - type: ChannelType.GuildText, - parent: parent.id, - topic: `Ticket ${category.label} — ${interaction.user.tag}`, - permissionOverwrites: buildOverwrites(guild, interaction.client, category, interaction.user.id), - reason: `Ticket ${category.label} ouvert par ${interaction.user.tag}`, - }); - - let ticket; - try { - ticket = { - id: createTicketRow({ - guildId: guild.id, - channelId: channel.id, - categoryId: category.id, - authorId: interaction.user.id, - }), - guild_id: guild.id, - channel_id: channel.id, - category_id: category.id, - author_id: interaction.user.id, - claimed_by: null, - status: 'open', - }; - } catch (error) { - // The unique index rejects a second open ticket for the same author and category. - await channel.delete('Ticket en doublon').catch(() => {}); - log.warn('Duplicate ticket rejected', error); - throw new UserFacingError( - 'Tu as déjà un ticket ouvert dans cette catégorie : continue dessus, ou ferme‑le avant d’en ouvrir un autre.', - ); - } - - await channel.send({ - content: `<@${ticket.author_id}>`, - embeds: [ticketEmbed(ticket, category)], - components: ticketButtons(), - }); - - logEvent({ - guildId: guild.id, - type: 'ticket.created', - actorId: ticket.author_id, - payload: { ticketId: ticket.id, categoryId: category.id }, - }); - await logTicket( - interaction.client, - baseEmbed(COLORS.ticket) - .setTitle('🎫 Ticket ouvert') - .setDescription(`<#${channel.id}> — ${category.label}`) - .addFields({ name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true }), - ); - - return channel; -} - -/** Resolves the ticket of the current channel, or throws a user facing error. */ -export async function getChannelTicket(interaction) { - const ticket = getTicketByChannel(interaction.channelId); - if (!ticket) { - throw new UserFacingError( - 'Cette action se lance depuis un salon de ticket : ouvre‑en un avec `/ticket create`, ou place‑toi dans le bon salon.', - ); - } - if (ticket.status !== 'open') { - throw new UserFacingError('Ce ticket est déjà fermé : il n’y a plus rien à faire ici.'); - } - return ticket; -} - -export async function claimTicket(interaction) { - const ticket = await getChannelTicket(interaction); - if (ticket.claimed_by === interaction.user.id) { - throw new UserFacingError('Tu as déjà ce ticket en charge — il n’y a rien à changer.'); - } - - claimTicketRow(ticket.id, interaction.user.id); - logEvent({ - guildId: ticket.guild_id, - type: 'ticket.claimed', - actorId: interaction.user.id, - payload: { ticketId: ticket.id }, - }); - - await interaction.reply({ - embeds: [successEmbed(`C’est noté : <@${interaction.user.id}> prend ce ticket en charge. Merci !`)], - }); - await logTicket( - interaction.client, - baseEmbed(COLORS.ticket) - .setTitle('🎫 Ticket pris en charge') - .setDescription(`#${ticket.id} — <#${ticket.channel_id}>`) - .addFields({ name: 'Avec', value: `<@${interaction.user.id}>`, inline: true }), - ); -} - -/** Closes the ticket: the author or any staff member may do it (M6-T06 / M6-T07). */ -export async function closeTicket(interaction, reason = null) { - const ticket = await getChannelTicket(interaction); - const isStaff = getAccessLevel(interaction.member) >= ACCESS_LEVELS.STAFF; - if (interaction.user.id !== ticket.author_id && !isStaff) { - throw new PermissionDeniedError( - 'Seules la personne qui a ouvert ce ticket et l’équipe peuvent le fermer. Si besoin, demande‑le dans le salon.', - ); - } - - closeTicketRow(ticket.id, { closedBy: interaction.user.id, reason }); - logEvent({ - guildId: ticket.guild_id, - type: 'ticket.closed', - actorId: interaction.user.id, - payload: { ticketId: ticket.id, reason }, - }); - - await interaction.reply({ - embeds: [ - successEmbed( - `Ticket fermé par <@${interaction.user.id}> — merci ! Le salon disparaît dans 10 secondes, tu as le temps de copier ce qui t’intéresse.`, - ), - ], - }); - await logTicket( - interaction.client, - baseEmbed(COLORS.ticket) - .setTitle('🎫 Ticket fermé') - .setDescription(`#${ticket.id} — ${findCategory(ticket.category_id)?.label ?? ticket.category_id}`) - .addFields( - { name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true }, - { name: 'Fermé par', value: `<@${interaction.user.id}>`, inline: true }, - { name: 'Motif', value: reason || 'Non précisé' }, - ), - ); - - const channel = interaction.channel; - setTimeout(() => channel?.delete(`Ticket #${ticket.id} fermé`).catch(() => {}), 10_000).unref(); -} - -/** Grants a staff member access to the ticket channel (M6-T07). */ -export async function addParticipant(interaction, userId) { - const ticket = await getChannelTicket(interaction); - if (userId === ticket.author_id || userId === ticket.claimed_by) { - throw new UserFacingError('Cette personne est déjà dans le ticket — pas besoin de l’ajouter.'); - } - - await interaction.channel.permissionOverwrites.edit(userId, { - ViewChannel: true, - SendMessages: true, - ReadMessageHistory: true, - }); - - logEvent({ - guildId: ticket.guild_id, - type: 'ticket.participant.added', - actorId: interaction.user.id, - payload: { ticketId: ticket.id, userId }, - }); - await interaction.reply({ embeds: [successEmbed(`C’est noté : <@${userId}> rejoint ce ticket.`)] }); -} - -/** Routes the buttons posted in ticket channels. */ -export async function handleTicketComponent(interaction) { - switch (interaction.customId) { - case 'ticket:claim': - await claimTicket(interaction); - return; - case 'ticket:close': - await closeTicket(interaction); - return; - default: - log.debug(`Ignored unknown ticket component ${interaction.customId}`); - } -} +import { ChannelType, PermissionFlagsBits } from 'discord.js'; +import { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; +import { createLogger } from '../../core/logger.js'; +import { getAccessLevel } from '../../core/permissions.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { + claimTicket as claimTicketRow, + closeTicket as closeTicketRow, + createTicket as createTicketRow, + getTicketByChannel, +} from '../../database/repositories/ticket-repository.js'; +import { ticketButtons } from '../../ui/buttons.js'; +import { baseEmbed, successEmbed } from '../../ui/embeds.js'; + +const log = createLogger('tickets'); + +/** Ticket scope names to the FWS access level they require. */ +const SCOPE_LEVELS = { + staff: ACCESS_LEVELS.STAFF, + dev: ACCESS_LEVELS.DEV, + owner: ACCESS_LEVELS.OWNER, +}; + +export function findCategory(categoryId) { + return TICKET_CATEGORIES.find((category) => category.id === categoryId) ?? null; +} + +/** A member may open a ticket only for a category their access level covers (M6-T02). */ +export function canUseCategory(member, category) { + const level = getAccessLevel(member); + return category.scope.some((scope) => level >= SCOPE_LEVELS[scope]); +} + +/** Static info about a ticket, used by the embeds below. */ +function ticketEmbed(ticket, category) { + const claimed = ticket.claimed_by ? `<@${ticket.claimed_by}>` : 'Personne'; + return baseEmbed(COLORS.ticket) + .setTitle(`🎫 Ticket ${category.label} #${ticket.id}`) + .setDescription( + `<@${ticket.author_id}> décris ta demande ici, avec le plus de détails possible : ` + + 'contexte, étapes pour reproduire, messages d’erreur. Plus tu en dis, plus vite on t’aide.', + ) + .addFields( + { name: 'Catégorie', value: category.label, inline: true }, + { name: 'Statut', value: ticket.status === 'open' ? 'Ouvert' : 'Fermé', inline: true }, + { name: 'Pris en charge par', value: claimed, inline: true }, + ); +} + +function channelName(categoryId, username) { + const slug = username + .toLowerCase() + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .replace(/[^a-z0-9-]/g, '-') + .replace(/-+/g, '-') + .replace(/^-|-$/g, '') + .slice(0, 40); + return `ticket-${categoryId}-${slug || 'membre'}`.slice(0, 100); +} + +/** Permission overwrites: the author, the staff roles of the scope and the bot (M6-T04). */ +function buildOverwrites(guild, client, category, authorId) { + const allow = [ + PermissionFlagsBits.ViewChannel, + PermissionFlagsBits.SendMessages, + PermissionFlagsBits.ReadMessageHistory, + PermissionFlagsBits.AttachFiles, + ]; + const overwrites = [ + { id: guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel] }, + { id: authorId, allow }, + { id: client.user.id, allow: [...allow, PermissionFlagsBits.ManageChannels] }, + ]; + + for (const scope of category.scope) { + const roleId = env.roles[scope]; + if (roleId) overwrites.push({ id: roleId, allow }); + } + return overwrites; +} + +async function fetchTicketLogChannel(client) { + if (!env.channels.ticketLogs) return null; + const channel = await client.channels.fetch(env.channels.ticketLogs).catch(() => null); + return channel?.isSendable() ? channel : null; +} + +async function logTicket(client, embed) { + const channel = await fetchTicketLogChannel(client); + await channel?.send({ embeds: [embed] }); +} + +/** Opens a private channel for the ticket (M6-T03). */ +export async function createTicket(interaction, categoryId) { + const category = findCategory(categoryId); + if (!category) { + throw new UserFacingError( + 'Je ne connais pas cette catégorie de ticket : `/ticket create` te propose la liste à jour.', + ); + } + if (!canUseCategory(interaction.member, category)) { + throw new UserFacingError( + `La catégorie **${category.label}** est réservée à l’équipe. Tu peux ouvrir un ticket dans une autre catégorie : \`/ticket create\` te montre celles qui te sont ouvertes.`, + ); + } + if (!env.channels.ticketCategory) { + throw new UserFacingError( + 'Les tickets ne sont pas encore installés : il manque `CATEGORY_TICKETS_ID` dans le `.env`. Préviens l’équipe !', + ); + } + + const guild = interaction.guild; + const parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null); + if (parent?.type !== ChannelType.GuildCategory) { + throw new UserFacingError( + '`CATEGORY_TICKETS_ID` ne pointe pas vers une catégorie Discord : je ne peux pas y créer de salon. L’équipe doit corriger le `.env`.', + ); + } + + const channel = await guild.channels.create({ + name: channelName(category.id, interaction.user.username), + type: ChannelType.GuildText, + parent: parent.id, + topic: `Ticket ${category.label} — ${interaction.user.tag}`, + permissionOverwrites: buildOverwrites(guild, interaction.client, category, interaction.user.id), + reason: `Ticket ${category.label} ouvert par ${interaction.user.tag}`, + }); + + let ticket; + try { + ticket = { + id: createTicketRow({ + guildId: guild.id, + channelId: channel.id, + categoryId: category.id, + authorId: interaction.user.id, + }), + guild_id: guild.id, + channel_id: channel.id, + category_id: category.id, + author_id: interaction.user.id, + claimed_by: null, + status: 'open', + }; + } catch (error) { + // The unique index rejects a second open ticket for the same author and category. + await channel.delete('Ticket en doublon').catch(() => {}); + log.warn('Duplicate ticket rejected', error); + throw new UserFacingError( + 'Tu as déjà un ticket ouvert dans cette catégorie : continue dessus, ou ferme‑le avant d’en ouvrir un autre.', + ); + } + + await channel.send({ + content: `<@${ticket.author_id}>`, + embeds: [ticketEmbed(ticket, category)], + components: ticketButtons(), + }); + + logEvent({ + guildId: guild.id, + type: 'ticket.created', + actorId: ticket.author_id, + payload: { ticketId: ticket.id, categoryId: category.id }, + }); + await logTicket( + interaction.client, + baseEmbed(COLORS.ticket) + .setTitle('🎫 Ticket ouvert') + .setDescription(`<#${channel.id}> — ${category.label}`) + .addFields({ name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true }), + ); + + return channel; +} + +/** Resolves the ticket of the current channel, or throws a user facing error. */ +export async function getChannelTicket(interaction) { + const ticket = getTicketByChannel(interaction.channelId); + if (!ticket) { + throw new UserFacingError( + 'Cette action se lance depuis un salon de ticket : ouvre‑en un avec `/ticket create`, ou place‑toi dans le bon salon.', + ); + } + if (ticket.status !== 'open') { + throw new UserFacingError('Ce ticket est déjà fermé : il n’y a plus rien à faire ici.'); + } + return ticket; +} + +export async function claimTicket(interaction) { + const ticket = await getChannelTicket(interaction); + if (ticket.claimed_by === interaction.user.id) { + throw new UserFacingError('Tu as déjà ce ticket en charge — il n’y a rien à changer.'); + } + + claimTicketRow(ticket.id, interaction.user.id); + logEvent({ + guildId: ticket.guild_id, + type: 'ticket.claimed', + actorId: interaction.user.id, + payload: { ticketId: ticket.id }, + }); + + await interaction.reply({ + embeds: [successEmbed(`C’est noté : <@${interaction.user.id}> prend ce ticket en charge. Merci !`)], + }); + await logTicket( + interaction.client, + baseEmbed(COLORS.ticket) + .setTitle('🎫 Ticket pris en charge') + .setDescription(`#${ticket.id} — <#${ticket.channel_id}>`) + .addFields({ name: 'Avec', value: `<@${interaction.user.id}>`, inline: true }), + ); +} + +/** Closes the ticket: the author or any staff member may do it (M6-T06 / M6-T07). */ +export async function closeTicket(interaction, reason = null) { + const ticket = await getChannelTicket(interaction); + const isStaff = getAccessLevel(interaction.member) >= ACCESS_LEVELS.STAFF; + if (interaction.user.id !== ticket.author_id && !isStaff) { + throw new PermissionDeniedError( + 'Seules la personne qui a ouvert ce ticket et l’équipe peuvent le fermer. Si besoin, demande‑le dans le salon.', + ); + } + + closeTicketRow(ticket.id, { closedBy: interaction.user.id, reason }); + logEvent({ + guildId: ticket.guild_id, + type: 'ticket.closed', + actorId: interaction.user.id, + payload: { ticketId: ticket.id, reason }, + }); + + await interaction.reply({ + embeds: [ + successEmbed( + `Ticket fermé par <@${interaction.user.id}> — merci ! Le salon disparaît dans 10 secondes, tu as le temps de copier ce qui t’intéresse.`, + ), + ], + }); + await logTicket( + interaction.client, + baseEmbed(COLORS.ticket) + .setTitle('🎫 Ticket fermé') + .setDescription(`#${ticket.id} — ${findCategory(ticket.category_id)?.label ?? ticket.category_id}`) + .addFields( + { name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true }, + { name: 'Fermé par', value: `<@${interaction.user.id}>`, inline: true }, + { name: 'Motif', value: reason || 'Non précisé' }, + ), + ); + + const channel = interaction.channel; + setTimeout(() => channel?.delete(`Ticket #${ticket.id} fermé`).catch(() => {}), 10_000).unref(); +} + +/** Grants a staff member access to the ticket channel (M6-T07). */ +export async function addParticipant(interaction, userId) { + const ticket = await getChannelTicket(interaction); + if (userId === ticket.author_id || userId === ticket.claimed_by) { + throw new UserFacingError('Cette personne est déjà dans le ticket — pas besoin de l’ajouter.'); + } + + await interaction.channel.permissionOverwrites.edit(userId, { + ViewChannel: true, + SendMessages: true, + ReadMessageHistory: true, + }); + + logEvent({ + guildId: ticket.guild_id, + type: 'ticket.participant.added', + actorId: interaction.user.id, + payload: { ticketId: ticket.id, userId }, + }); + await interaction.reply({ embeds: [successEmbed(`C’est noté : <@${userId}> rejoint ce ticket.`)] }); +} + +/** Routes the buttons posted in ticket channels. */ +export async function handleTicketComponent(interaction) { + switch (interaction.customId) { + case 'ticket:claim': + await claimTicket(interaction); + return; + case 'ticket:close': + await closeTicket(interaction); + return; + default: + log.debug(`Ignored unknown ticket component ${interaction.customId}`); + } +} diff --git a/src/services/voice/voice-service.js b/src/services/voice/voice-service.js index 65ac55f..344a892 100644 --- a/src/services/voice/voice-service.js +++ b/src/services/voice/voice-service.js @@ -1,1001 +1,1001 @@ -import { - ActionRowBuilder, - ChannelType, - MessageFlags, - ModalBuilder, - PermissionFlagsBits, - TextInputBuilder, - TextInputStyle, -} from 'discord.js'; -import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; -import { env } from '../../config/env.js'; -import { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; -import { createLogger } from '../../core/logger.js'; -import { getAccessLevel } from '../../core/permissions.js'; -import { logEvent } from '../../database/repositories/event-log-repository.js'; -import { resolveSetting } from '../../database/repositories/settings-repository.js'; -import { - addVoiceChannel, - countVoiceChannels, - countVoiceChannelsByTrigger, - getVoiceChannel, - listOwnedVoiceChannels, - listVoiceChannels, - removeVoiceChannel, - setVoiceLimit, - setVoiceLocked, - setVoiceName, - setVoiceOwner, -} from '../../database/repositories/voice-repository.js'; -import { - listVoiceTriggers, - removeVoiceTrigger as deleteVoiceTriggerRow, - upsertVoiceTrigger, -} from '../../database/repositories/voice-trigger-repository.js'; -import { voicePanelComponents } from '../../ui/buttons.js'; -import { baseEmbed, successEmbed } from '../../ui/embeds.js'; - -const log = createLogger('voice'); - -export const DEFAULT_TEMPLATE = '🔊 Salon de {user}'; -/** Discord caps the user limit of a voice channel at 99 (0 means unlimited). */ -export const LIMIT_MAX = 99; -export const NAME_MAX = 100; -/** - * Delay before an empty temporary channel is deleted, so a quick move does not destroy a channel - * its owner customised. `VOICE_EMPTY_GRACE_MS=0` deletes it as soon as it is empty (M14-T04). - */ -const EMPTY_GRACE_MS = Math.max(0, env.voice.emptyGraceMs); -/** Interval of the safety net that catches the channels an event could not clean up. */ -const SWEEP_INTERVAL_MS = 60_000; - -/** Creation in flight per member, to never create two channels for the same person (M14-T02). */ -const pendingCreations = new Set(); -/** Channel id -> panel message id, so buttons can be refreshed after a change (M14-T05). */ -const panelMessages = new Map(); - -const VIEW = PermissionFlagsBits.ViewChannel; -const CONNECT = PermissionFlagsBits.Connect; -const SPEAK = PermissionFlagsBits.Speak; -const MEMBER_ALLOW = [VIEW, CONNECT, SPEAK]; -const OWNER_ALLOW = [...MEMBER_ALLOW, PermissionFlagsBits.ManageChannels, PermissionFlagsBits.MoveMembers]; -/** Named form required by `permissionOverwrites.edit()` (permission bits are not keys). */ -const OWNER_OVERWRITE = Object.freeze({ - ViewChannel: true, - Connect: true, - Speak: true, - ManageChannels: true, - MoveMembers: true, -}); - -/** Strips control characters without a control-character regex, then collapses spaces. */ -const clean = (value) => - [...String(value ?? '')] - .map((char) => { - const code = char.codePointAt(0); - return code <= 31 || code === 127 ? ' ' : char; - }) - .join('') - .replace(/\s+/g, ' ') - .trim(); - -/** Channel names are normalised and truncated before they reach Discord (M14-T08). */ -export function sanitizeChannelName(value) { - const name = clean(value); - if (!name) throw new UserFacingError('Il me manque un nom : écris au moins un caractère pour ton salon.'); - return name.slice(0, NAME_MAX); -} - -/** `🔊 Salon de {user}` -> the name of the channel created for a member. */ -export function buildChannelName(template, member) { - const replaced = String(template || DEFAULT_TEMPLATE).replaceAll( - '{user}', - member.displayName ?? member.user?.username ?? '', - ); - return clean(replaced).slice(0, NAME_MAX) || '🔊 Salon vocal'; -} - -/** `0` means unlimited; anything outside 0..99 is rejected or ignored (M14-T06). */ -export function clampLimit(value, { strict = false } = {}) { - const limit = Number(value); - if (!Number.isInteger(limit) || limit < 0 || limit > LIMIT_MAX) { - if (strict) { - throw new UserFacingError( - `Indique un nombre entre 0 (aucune limite) et ${LIMIT_MAX}. Par exemple 5 pour cinq places.`, - ); - } - return 0; - } - return limit; -} - -/** Index of the last slot of a category once the new channel is part of it (M14-T02). */ -export function bottomPosition(childCount) { - return Math.max(0, Number(childCount) - 1); -} - -/** - * Every trigger channel declared for a guild, so one server can host several of them - * ("dev", "sio", …), each with its own home category (M14-T01). Triggers written by the - * single-trigger version and the environment are still accepted as fallbacks. - */ -export function getVoiceTriggers(guildId) { - const triggers = new Map(); - - let rows = []; - try { - rows = listVoiceTriggers(guildId); - } catch (error) { - log.warn('Could not read the voice triggers', error); - } - - for (const row of rows) { - triggers.set(row.trigger_id, { - triggerId: row.trigger_id, - label: row.label || null, - categoryId: row.category_id || null, - template: row.template || DEFAULT_TEMPLATE, - userLimit: clampLimit(row.user_limit), - enabled: Boolean(row.enabled), - source: 'database', - }); - } - - const legacyId = resolveSetting(guildId, 'voice.trigger', null); - if (legacyId && !triggers.has(legacyId)) { - triggers.set(legacyId, { - triggerId: legacyId, - label: null, - categoryId: resolveSetting(guildId, 'voice.category', env.channels.voiceCategory) || null, - template: resolveSetting(guildId, 'voice.template', DEFAULT_TEMPLATE) || DEFAULT_TEMPLATE, - userLimit: clampLimit(resolveSetting(guildId, 'voice.limit', 0)), - enabled: true, - source: 'settings', - }); - } - - const envId = env.channels.voiceTrigger; - if (envId && !triggers.has(envId)) { - triggers.set(envId, { - triggerId: envId, - label: null, - categoryId: env.channels.voiceCategory || null, - template: DEFAULT_TEMPLATE, - userLimit: 0, - enabled: true, - source: 'env', - }); - } - - return [...triggers.values()]; -} - -/** Any declared trigger, disabled ones included, so the commands can report and toggle them. */ -export function findTrigger(guildId, triggerId) { - return getVoiceTriggers(guildId).find((trigger) => trigger.triggerId === triggerId) ?? null; -} - -/** An enabled trigger: joining it creates a temporary channel (M14-T02). */ -export function getVoiceTrigger(guildId, triggerId) { - const trigger = findTrigger(guildId, triggerId); - return trigger?.enabled ? trigger : null; -} - -export function isTriggerChannel(guildId, channelId) { - return getVoiceTrigger(guildId, channelId) !== null; -} - -/** Triggers with the number of channels they currently host, for the configuration embed. */ -export function listTriggerSummaries(guildId) { - return getVoiceTriggers(guildId).map((trigger) => ({ - ...trigger, - activeChannels: countVoiceChannelsByTrigger(trigger.triggerId), - })); -} - -/** Declares or updates a trigger; an omitted field keeps its stored value (M14-T01). */ -export function saveVoiceTrigger(guildId, patch, updatedBy = null) { - const existing = patch.triggerId ? findTrigger(guildId, patch.triggerId) : null; - - upsertVoiceTrigger({ - triggerId: patch.triggerId, - guildId, - label: patch.label ?? existing?.label ?? null, - categoryId: patch.categoryId ?? existing?.categoryId ?? null, - template: patch.template ?? existing?.template ?? DEFAULT_TEMPLATE, - userLimit: clampLimit(patch.userLimit ?? existing?.userLimit ?? 0), - enabled: patch.enabled ?? existing?.enabled ?? true, - }); - - logEvent({ - guildId, - type: 'voice.trigger.saved', - actorId: updatedBy, - payload: { triggerId: patch.triggerId }, - }); - return findTrigger(guildId, patch.triggerId); -} - -/** Writes the trigger before toggling it, so an environment fallback can be switched off. */ -export function setTriggerEnabled(guildId, triggerId, enabled) { - const trigger = findTrigger(guildId, triggerId); - if (!trigger) - throw new UserFacingError('Ce salon n’est pas un déclencheur : ajoute-le d’abord avec `/voice setup`.'); - if (trigger.enabled === enabled) { - throw new UserFacingError( - enabled - ? 'Ce déclencheur est déjà actif — il n’y a rien à changer.' - : 'Ce déclencheur est déjà désactivé — il n’y a rien à changer.', - ); - } - - upsertVoiceTrigger({ - triggerId, - guildId, - label: trigger.label, - categoryId: trigger.categoryId, - template: trigger.template, - userLimit: trigger.userLimit, - enabled, - }); - logEvent({ guildId, type: 'voice.trigger.toggled', payload: { triggerId, enabled } }); - return findTrigger(guildId, triggerId); -} - -/** Removes a trigger declared from Discord; the ones coming from the environment cannot be deleted. */ -export function removeVoiceTriggerConfig(guildId, triggerId) { - const trigger = findTrigger(guildId, triggerId); - if (!trigger) - throw new UserFacingError('Ce salon n’est pas un déclencheur : il n’y a donc rien à supprimer.'); - if (trigger.source !== 'database') { - throw new UserFacingError( - 'Ce déclencheur vient des variables d’environnement (`CHANNEL_VOICE_TRIGGER_ID`) : je ne peux pas le supprimer d’ici. Retire‑le du `.env`, ou mets‑le en pause avec `/voice triggers disable`.', - ); - } - - deleteVoiceTriggerRow(triggerId); - logEvent({ guildId, type: 'voice.trigger.removed', payload: { triggerId } }); -} - -export function isStaff(member, roles = env.roles) { - return getAccessLevel(member, roles) >= ACCESS_LEVELS.STAFF; -} - -export function isManagedChannel(channelId) { - return Boolean(getVoiceChannel(channelId)); -} - -/** Embed shown in the panel and by `/voice info` (M14-T05). */ -export function voicePanelEmbed(channel, row) { - const ownerId = row?.owner_id ?? null; - return baseEmbed(COLORS.primary) - .setTitle(`Gestion de ${channel.name}`) - .setDescription( - 'Les boutons ci-dessous agissent sur ce salon seulement. Tu retrouves exactement les mêmes options dans `/voice`.', - ) - .addFields( - { name: 'Propriétaire', value: ownerId ? `<@${ownerId}>` : 'Personne', inline: true }, - { name: 'Statut', value: row?.locked ? '🔒 Verrouillé' : '🔓 Ouvert', inline: true }, - { name: 'Limite', value: row?.user_limit ? `${row.user_limit} places` : 'Illimitée', inline: true }, - { - name: 'Membres', - value: row?.user_limit ? `${channel.members.size} / ${row.user_limit}` : String(channel.members.size), - inline: true, - }, - ); -} - -export function voiceInfoEmbed(channel, row) { - const embed = baseEmbed(COLORS.primary) - .setTitle(channel.name) - .addFields( - { name: 'Propriétaire', value: row?.owner_id ? `<@${row.owner_id}>` : 'Personne', inline: true }, - { name: 'Statut', value: row?.locked ? '🔒 Verrouillé' : '🔓 Ouvert', inline: true }, - { name: 'Limite', value: row?.user_limit ? `${row.user_limit} places` : 'Illimitée', inline: true }, - { - name: 'Membres', - value: - channel.members.size === 0 - ? 'Aucun' - : channel.members - .first(10) - .map((member) => `<@${member.id}>`) - .join(', '), - }, - ) - .addFields({ name: 'Créé', value: ``, inline: true }); - - if (row?.trigger_id) - embed.setFooter({ text: `Salon temporaire · créé depuis le déclencheur ${row.trigger_id}` }); - return embed; -} - -/** Posts the control panel in the text chat of the voice channel (M14-T05). */ -async function postPanel(channel, row) { - if (!channel.isSendable?.()) return; - - const message = await channel - .send({ - embeds: [voicePanelEmbed(channel, row)], - components: voicePanelComponents({ locked: Boolean(row.locked) }), - }) - .catch((error) => { - log.warn('Could not post the voice panel', error); - return null; - }); - if (message) panelMessages.set(channel.id, message.id); -} - -/** Refreshes the panel buttons after a change, best effort (M14-T05). */ -export async function refreshPanel(channel) { - const messageId = panelMessages.get(channel.id); - const row = getVoiceChannel(channel.id); - if (!messageId || !row || !channel.isSendable?.()) return; - - const message = await channel.messages.fetch(messageId).catch(() => null); - await message - ?.edit({ - embeds: [voicePanelEmbed(channel, row)], - components: voicePanelComponents({ locked: Boolean(row.locked) }), - }) - .catch(() => {}); -} - -/** Drops a channel from the database and from the panel cache. */ -function forgetVoiceChannel(channelId) { - removeVoiceChannel(channelId); - panelMessages.delete(channelId); -} - -/** - * The channel an owner can be moved back into: only one created from the same trigger, so that - * each trigger keeps its own channel in its own category (M14-T03). Rows of vanished channels - * are dropped along the way, whichever trigger they came from. - */ -async function findReusableChannel(guild, ownerId, triggerId) { - for (const row of listOwnedVoiceChannels(guild.id, ownerId)) { - const channel = guild.channels.cache.get(row.channel_id); - if (!channel) { - forgetVoiceChannel(row.channel_id); - continue; - } - if (row.trigger_id !== triggerId) continue; - - const full = channel.userLimit > 0 && channel.members.size >= channel.userLimit; - if (!full) return { channel, row }; - } - return null; -} - -/** New channels are appended below the ones already sitting in the target category (M14-T02). */ -async function placeAtBottomOfCategory(channel) { - if (!channel.parentId) return; - - const siblings = channel.guild.channels.cache.filter( - (candidate) => candidate.parentId === channel.parentId, - ); - const target = bottomPosition(siblings.size); - if (channel.position === target) return; - - await channel - .setPosition(target, { reason: 'Nouveau salon en bas de sa catégorie' }) - .catch((error) => log.warn('Could not move the new channel to the bottom of its category', error)); -} - -function buildOverwrites(guild, client, ownerId) { - return [ - { id: guild.roles.everyone.id, allow: MEMBER_ALLOW }, - { id: ownerId, allow: OWNER_ALLOW }, - { id: client.user.id, allow: OWNER_ALLOW }, - ]; -} - -/** - * Called when a member joins a trigger channel: creates their channel in the category of that - * trigger, below the channels already there, or moves them back into the one they already own - * (M14-T02 / M14-T03). - */ -export async function createFromTrigger(member, trigger) { - if (!trigger?.triggerId || pendingCreations.has(member.id)) return null; - - const reusable = await findReusableChannel(member.guild, member.id, trigger.triggerId); - if (reusable) { - await member.voice - .setChannel(reusable.channel, 'Retour dans son salon vocal temporaire') - .catch((error) => log.warn('Could not move the member back into their channel', error)); - return reusable.channel; - } - - pendingCreations.add(member.id); - try { - const parent = trigger.categoryId - ? await member.guild.channels.fetch(trigger.categoryId).catch(() => null) - : null; - - const channel = await member.guild.channels.create({ - name: buildChannelName(trigger.template, member), - type: ChannelType.GuildVoice, - userLimit: trigger.userLimit, - ...(parent?.type === ChannelType.GuildCategory && { parent: parent.id }), - reason: `Salon vocal temporaire de ${member.user.tag}`, - permissionOverwrites: buildOverwrites(member.guild, member.client, member.id), - }); - - await placeAtBottomOfCategory(channel); - - addVoiceChannel({ - channelId: channel.id, - guildId: member.guild.id, - ownerId: member.id, - triggerId: trigger.triggerId, - name: channel.name, - userLimit: trigger.userLimit, - }); - - await member.voice - .setChannel(channel, 'Salon vocal temporaire créé') - .catch((error) => log.warn('Could not move the member into their new channel', error)); - - await postPanel(channel, getVoiceChannel(channel.id)); - logEvent({ - guildId: member.guild.id, - type: 'voice.created', - actorId: member.id, - payload: { channelId: channel.id, ownerId: member.id }, - }); - return channel; - } finally { - pendingCreations.delete(member.id); - } -} - -/** - * Deletes a temporary channel. The row is only dropped once the channel is really gone, so that a - * failed API call leaves a channel the sweep can retry instead of an orphaned room (M14-T04). - */ -export async function deleteVoiceChannel(channel, reason = 'Salon vocal temporaire supprimé') { - try { - await channel.delete(reason); - } catch (error) { - if (!(await isChannelGone(channel, error))) { - log.warn('Could not delete the voice channel', error); - return false; - } - } - - forgetVoiceChannel(channel.id); - return true; -} - -/** A 404 or an unknown-channel error means the channel is already deleted, whatever the cause. */ -async function isChannelGone(channel, error) { - const codes = [error?.code, String(error?.code ?? '')]; - if (error?.status === 404 || codes.includes(10003)) return true; - - const fresh = await channel.guild.channels.fetch(channel.id).catch(() => null); - return fresh === null; -} - -/** Resolves a channel from the cache or the API, or `null` when it does not exist anymore. */ -async function resolveChannel(guild, channelId) { - return guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null)); -} - -/** - * Deletes an empty temporary channel after a short grace period, so that a member moving between - * channels does not lose the one they customised (M14-T04). - */ -export async function cleanupVoiceChannel(guild, channelId, { graceMs = EMPTY_GRACE_MS } = {}) { - const row = getVoiceChannel(channelId); - if (!row) return; - - const channel = await resolveChannel(guild, channelId); - if (!channel) { - forgetVoiceChannel(channelId); - return; - } - if (channel.members.size > 0) return; - - const removeEmptyChannel = async () => { - const fresh = await resolveChannel(guild, channelId); - if (!fresh) { - forgetVoiceChannel(channelId); - return; - } - if (fresh.members.size > 0) return; - - if (await deleteVoiceChannel(fresh, 'Salon vocal temporaire vide')) { - logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId } }); - } - }; - - if (graceMs <= 0) { - await removeEmptyChannel().catch((error) => log.warn('Could not clean up an empty voice channel', error)); - return; - } - - setTimeout( - () => removeEmptyChannel().catch((error) => log.warn('Could not clean up an empty voice channel', error)), - graceMs, - ).unref(); -} - -/** - * Forgets the channels that no longer exist and deletes the ones with nobody left in them - * (M14-T04 / M14-T07). Run at startup and then every minute: the voice state event is the fast - * path, this sweep is the guarantee when an event is missed or a deletion failed. - */ -export async function sweepVoiceChannels(client) { - for (const guild of client.guilds.cache.values()) { - let rows = []; - try { - rows = listVoiceChannels(guild.id); - } catch (error) { - log.warn('Could not read the stored voice channels', error); - continue; - } - - for (const row of rows) { - const channel = await resolveChannel(guild, row.channel_id); - if (!channel) { - forgetVoiceChannel(row.channel_id); - continue; - } - if (channel.members.size > 0) continue; - - if (await deleteVoiceChannel(channel, 'Salon vocal temporaire vide')) { - log.info(`Deleted the empty temporary channel ${row.channel_id}`); - logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId: row.channel_id } }); - } - } - } -} - -/** Starts the periodic sweep; the returned interval can be cleared to stop it (M14-T04). */ -export function startVoiceJanitor(client, intervalMs = SWEEP_INTERVAL_MS) { - const timer = setInterval(() => { - sweepVoiceChannels(client).catch((error) => log.error('Voice channel sweep failed', error)); - }, intervalMs); - timer.unref?.(); - return timer; -} - -export function activeChannelCount(guildId) { - return countVoiceChannels(guildId); -} - -/** Channel of the interaction itself, when it is a temporary voice channel (panel buttons and modals). */ -function managedChannelOf(interaction) { - return interaction.channelId && isManagedChannel(interaction.channelId) ? interaction.channelId : null; -} - -/** - * Resolves the temporary channel an action applies to: the explicit option first, then the - * channel the interaction happened in (panel, modal), then the voice channel of the caller (M14-T05). - */ -export async function resolveManagedChannel(interaction, { channelId = null } = {}) { - const id = channelId ?? managedChannelOf(interaction) ?? interaction.member?.voice?.channelId ?? null; - const row = id ? getVoiceChannel(id) : null; - if (!row) { - throw new UserFacingError( - 'Je ne trouve pas ton salon temporaire : entre dans ton salon vocal, puis relance la commande — ou indique‑le avec l’option `channel`.', - ); - } - if (channelId && channelId !== interaction.member?.voice?.channelId && !isStaff(interaction.member)) { - // An explicit channel is a staff convenience only: a member manages their own channel. - throw new PermissionDeniedError( - 'C’est réservé à l’équipe : chaque personne gère son propre salon. Tu peux modifier le tien, sans option `channel`.', - ); - } - - const channel = await interaction.guild.channels.fetch(row.channel_id).catch(() => null); - if (!channel) { - forgetVoiceChannel(row.channel_id); - throw new UserFacingError('Ce salon n’existe plus — il a sûrement déjà été supprimé.'); - } - return { channel, row }; -} - -/** Only the owner may manage a channel; staff can always step in (M14-T06). */ -export function assertVoiceOwner(interaction, row, action = 'gérer ce salon') { - if (row.owner_id === interaction.user.id || isStaff(interaction.member)) return; - throw new PermissionDeniedError( - `Ce salon appartient à <@${row.owner_id}> : seule cette personne (ou l’équipe) peut ${action}.`, - ); -} - -const ephemeral = (payload) => ({ ...payload, flags: MessageFlags.Ephemeral }); - -export async function renameChannel(interaction, name) { - const { channel, row } = await resolveManagedChannel(interaction); - assertVoiceOwner(interaction, row, 'renommer le salon'); - - const sanitized = sanitizeChannelName(name); - await channel.setName(sanitized, `Renommé par ${interaction.user.tag}`); - setVoiceName(channel.id, sanitized); - await refreshPanel(channel); - - await interaction.reply( - ephemeral({ embeds: [successEmbed(`Ton salon s’appelle maintenant **${sanitized}**.`)] }), - ); -} - -export async function setChannelLimit(interaction, limit) { - const { channel, row } = await resolveManagedChannel(interaction); - assertVoiceOwner(interaction, row, 'changer la limite'); - - const value = clampLimit(limit, { strict: true }); - await channel.setUserLimit(value, `Limite modifiée par ${interaction.user.tag}`); - setVoiceLimit(channel.id, value); - await refreshPanel(channel); - - await interaction.reply( - ephemeral({ - embeds: [ - successEmbed( - value === 0 - ? 'Ton salon n’a plus de limite de places : tout le monde peut entrer.' - : `Ton salon accueille maintenant **${value} personnes**.`, - ), - ], - }), - ); -} - -export async function toggleLock(interaction, { locked = null } = {}) { - const { channel, row } = await resolveManagedChannel(interaction); - assertVoiceOwner(interaction, row, 'verrouiller le salon'); - - const next = locked === null ? !row.locked : Boolean(locked); - if (next === Boolean(row.locked)) { - throw new UserFacingError( - next - ? 'Ton salon est déjà verrouillé — il n’y a rien à changer.' - : 'Ton salon est déjà ouvert — il n’y a rien à changer.', - ); - } - await channel.permissionOverwrites.edit( - interaction.guild.roles.everyone.id, - { Connect: next ? false : null }, - { reason: `${next ? 'Verrouillé' : 'Déverrouillé'} par ${interaction.user.tag}` }, - ); - setVoiceLocked(channel.id, next); - await refreshPanel(channel); - - await interaction.reply( - ephemeral({ - embeds: [ - successEmbed( - next - ? '🔒 Salon verrouillé : seules les personnes que tu autorises peuvent entrer.' - : '🔓 Salon ouvert : tout le monde peut entrer.', - ), - ], - }), - ); -} - -export async function permitUser(interaction, userId) { - const { channel, row } = await resolveManagedChannel(interaction); - assertVoiceOwner(interaction, row, 'autoriser un membre'); - - await channel.permissionOverwrites.edit( - userId, - { ViewChannel: true, Connect: true }, - { - reason: `Autorisé par ${interaction.user.tag}`, - }, - ); - await interaction.reply( - ephemeral({ embeds: [successEmbed(`C’est noté : <@${userId}> peut entrer dans ton salon.`)] }), - ); -} - -export async function rejectUser(interaction, userId) { - const { channel, row } = await resolveManagedChannel(interaction); - assertVoiceOwner(interaction, row, 'refuser un membre'); - - await channel.permissionOverwrites.edit( - userId, - { ViewChannel: false, Connect: false }, - { - reason: `Refusé par ${interaction.user.tag}`, - }, - ); - const member = channel.members.get(userId); - await member?.voice.disconnect(`Refusé par ${interaction.user.tag}`).catch(() => {}); - - await interaction.reply( - ephemeral({ embeds: [successEmbed(`C’est noté : <@${userId}> ne peut plus entrer dans ton salon.`)] }), - ); -} - -export async function kickUser(interaction, userId) { - const { channel, row } = await resolveManagedChannel(interaction); - assertVoiceOwner(interaction, row, 'exclure un membre'); - - const member = channel.members.get(userId); - if (!member) throw new UserFacingError('Ce membre n’est pas dans ton salon — il n’y a rien à faire.'); - if (member.id === row.owner_id) - throw new UserFacingError('Impossible : la personne propriétaire du salon ne peut pas en être exclue.'); - - await member.voice.disconnect(`Exclu par ${interaction.user.tag}`); - await interaction.reply( - ephemeral({ embeds: [successEmbed(`<@${userId}> ne fait plus partie de ton salon.`)] }), - ); -} - -export async function transferOwnership(interaction, userId) { - const { channel, row } = await resolveManagedChannel(interaction); - assertVoiceOwner(interaction, row, 'transférer le salon'); - - const member = channel.members.get(userId); - if (!member) - throw new UserFacingError( - 'Cette personne doit déjà être dans le salon pour en devenir propriétaire : invite‑la, puis relance la commande.', - ); - if (member.id === row.owner_id) - throw new UserFacingError('Cette personne est déjà propriétaire de ce salon.'); - - await channel.permissionOverwrites - .edit(row.owner_id, { ManageChannels: null, MoveMembers: null }, { reason: 'Nouveau propriétaire' }) - .catch(() => {}); - await channel.permissionOverwrites.edit(member.id, OWNER_OVERWRITE, { - reason: `Salon transféré par ${interaction.user.tag}`, - }); - - setVoiceOwner(channel.id, member.id); - await refreshPanel(channel); - logEvent({ - guildId: interaction.guildId, - type: 'voice.transferred', - actorId: interaction.user.id, - payload: { channelId: channel.id, ownerId: member.id }, - }); - - await interaction.reply( - ephemeral({ - embeds: [ - successEmbed(`<@${member.id}> est désormais propriétaire de **${channel.name}**. Bonne session !`), - ], - }), - ); -} - -/** A member may take over a channel whose owner is gone (M14-T03). */ -export async function claimOwnership(interaction) { - const { channel, row } = await resolveManagedChannel(interaction); - if (row.owner_id === interaction.user.id) { - throw new UserFacingError('Tu es déjà propriétaire de ce salon — tout est en ordre.'); - } - if (channel.members.has(row.owner_id)) { - throw new UserFacingError( - 'La personne propriétaire est encore dans le salon : ce salon n’est pas abandonné.', - ); - } - if (!channel.members.has(interaction.user.id)) { - throw new UserFacingError( - 'Entre d’abord dans le salon, puis relance la commande : la propriété se réclame depuis l’intérieur.', - ); - } - - await channel.permissionOverwrites.edit(interaction.user.id, OWNER_OVERWRITE, { - reason: `Salon réclamé par ${interaction.user.tag}`, - }); - setVoiceOwner(channel.id, interaction.user.id); - await refreshPanel(channel); - logEvent({ - guildId: interaction.guildId, - type: 'voice.claimed', - actorId: interaction.user.id, - payload: { channelId: channel.id }, - }); - - await interaction.reply( - ephemeral({ embeds: [successEmbed('Tu es désormais propriétaire de ce salon. Amuse‑toi bien !')] }), - ); -} - -export async function removeChannel(interaction, { channelId = null } = {}) { - const { channel, row } = await resolveManagedChannel(interaction, { channelId }); - assertVoiceOwner(interaction, row, 'supprimer le salon'); - - await interaction.reply( - ephemeral({ - embeds: [ - successEmbed(`Le salon **${channel.name}** disparaît dans 3 secondes. Merci pour la session !`), - ], - }), - ); - logEvent({ - guildId: interaction.guildId, - type: 'voice.deleted', - actorId: interaction.user.id, - payload: { channelId: channel.id }, - }); - setTimeout( - () => deleteVoiceChannel(channel, `Supprimé par ${interaction.user.tag}`).catch(() => {}), - 3_000, - ).unref(); -} - -export async function showInfo(interaction, { channelId = null } = {}) { - const { channel, row } = await resolveManagedChannel(interaction, { channelId }); - await interaction.reply(ephemeral({ embeds: [voiceInfoEmbed(channel, row)] })); -} - -/** Embed published in a trigger channel to explain the "join to create" flow (M14-T01). */ -function triggerPanelEmbed(trigger, channel) { - return baseEmbed(COLORS.primary) - .setTitle('🎧 Salons vocaux temporaires') - .setDescription( - `Rejoins ${channel} pour obtenir ton propre salon vocal.\n\n` + - 'Tu en deviens le propriétaire : renomme-le, limite le nombre de places, verrouille-le, ' + - 'autorise ou exclus des membres, ou transfère-le — depuis les boutons du salon ou les commandes `/voice`.', - ) - .addFields( - { - name: 'Catégorie', - value: trigger.categoryId ? `<#${trigger.categoryId}>` : 'Celle du salon déclencheur', - inline: true, - }, - { - name: 'Limite par défaut', - value: trigger.userLimit ? `${trigger.userLimit} places` : 'Illimitée', - inline: true, - }, - ); -} - -/** - * Publishes the explanation panel in one trigger, or in every enabled trigger of the guild - * when no trigger is given (M14-T01). - */ -export async function postSetupPanel(interaction, { triggerId = null } = {}) { - const triggers = getVoiceTriggers(interaction.guildId).filter( - (trigger) => trigger.enabled && (!triggerId || trigger.triggerId === triggerId), - ); - if (triggers.length === 0) { - throw new UserFacingError( - triggerId - ? 'Ce salon n’est pas un déclencheur actif : configure‑le avec `/voice setup`.' - : 'Aucun salon vocal déclencheur n’est configuré : lance `/voice setup`.', - ); - } - - const published = []; - for (const trigger of triggers) { - const channel = await interaction.guild.channels.fetch(trigger.triggerId).catch(() => null); - if (!channel?.isVoiceBased?.() || !channel.isSendable()) { - log.warn(`Skipped the panel of ${trigger.triggerId}: not a sendable voice channel`); - continue; - } - - await channel.send({ embeds: [triggerPanelEmbed(trigger, channel)] }).catch((error) => { - log.warn('Could not publish the voice panel', error); - }); - published.push(trigger.triggerId); - } - - if (published.length === 0) { - throw new UserFacingError( - 'Aucun panneau n’a pu être publié : vérifie que je peux écrire dans les salons déclencheurs.', - ); - } - - await interaction.reply( - ephemeral({ - embeds: [successEmbed(`Panneau publié dans ${published.map((id) => `<#${id}>`).join(', ')}.`)], - }), - ); -} - -/** Button and select menu routing (M14-T05). */ -export async function handleVoiceComponent(interaction) { - const action = interaction.customId.split(':')[1]; - - if (interaction.isUserSelectMenu()) { - const userId = interaction.values[0]; - switch (action) { - case 'permit': - await permitUser(interaction, userId); - return; - case 'kick': - await kickUser(interaction, userId); - return; - case 'transfer': - await transferOwnership(interaction, userId); - return; - default: - log.debug(`Ignored voice select ${interaction.customId}`); - return; - } - } - - switch (action) { - case 'rename': - await openRenameModal(interaction); - return; - case 'limit': - await openLimitModal(interaction); - return; - case 'lock': - await toggleLock(interaction); - return; - case 'claim': - await claimOwnership(interaction); - return; - case 'info': - await showInfo(interaction); - return; - case 'delete': - await removeChannel(interaction); - return; - default: - log.debug(`Ignored voice component ${interaction.customId}`); - } -} - -async function openRenameModal(interaction) { - const { channel, row } = await resolveManagedChannel(interaction); - assertVoiceOwner(interaction, row, 'renommer le salon'); - - await interaction.showModal( - new ModalBuilder() - .setCustomId('voice:rename:modal') - .setTitle('Renommer le salon') - .addComponents( - new ActionRowBuilder().addComponents( - new TextInputBuilder() - .setCustomId('name') - .setLabel('Nouveau nom') - .setStyle(TextInputStyle.Short) - .setMaxLength(NAME_MAX) - .setValue(channel.name.slice(0, NAME_MAX)) - .setRequired(true), - ), - ), - ); -} - -async function openLimitModal(interaction) { - const { row } = await resolveManagedChannel(interaction); - assertVoiceOwner(interaction, row, 'changer la limite'); - - await interaction.showModal( - new ModalBuilder() - .setCustomId('voice:limit:modal') - .setTitle('Limite de places') - .addComponents( - new ActionRowBuilder().addComponents( - new TextInputBuilder() - .setCustomId('limit') - .setLabel(`Entre 0 (illimité) et ${LIMIT_MAX}`) - .setStyle(TextInputStyle.Short) - .setMaxLength(2) - .setValue(String(row.user_limit ?? 0)) - .setRequired(true), - ), - ), - ); -} - -/** Modal submissions opened from the panel (M14-T05). */ -export async function handleVoiceModal(interaction) { - if (interaction.customId === 'voice:rename:modal') { - await renameChannel(interaction, interaction.fields.getTextInputValue('name')); - return; - } - - if (interaction.customId === 'voice:limit:modal') { - const raw = interaction.fields.getTextInputValue('limit').trim(); - const limit = Number.parseInt(raw, 10); - if (!/^\d{1,2}$/.test(raw)) { - throw new UserFacingError(`Indique un nombre entier entre 0 (illimité) et ${LIMIT_MAX}.`); - } - await setChannelLimit(interaction, limit); - return; - } - - log.debug(`Ignored voice modal ${interaction.customId}`); -} +import { + ActionRowBuilder, + ChannelType, + MessageFlags, + ModalBuilder, + PermissionFlagsBits, + TextInputBuilder, + TextInputStyle, +} from 'discord.js'; +import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; +import { env } from '../../config/env.js'; +import { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; +import { createLogger } from '../../core/logger.js'; +import { getAccessLevel } from '../../core/permissions.js'; +import { logEvent } from '../../database/repositories/event-log-repository.js'; +import { resolveSetting } from '../../database/repositories/settings-repository.js'; +import { + addVoiceChannel, + countVoiceChannels, + countVoiceChannelsByTrigger, + getVoiceChannel, + listOwnedVoiceChannels, + listVoiceChannels, + removeVoiceChannel, + setVoiceLimit, + setVoiceLocked, + setVoiceName, + setVoiceOwner, +} from '../../database/repositories/voice-repository.js'; +import { + listVoiceTriggers, + removeVoiceTrigger as deleteVoiceTriggerRow, + upsertVoiceTrigger, +} from '../../database/repositories/voice-trigger-repository.js'; +import { voicePanelComponents } from '../../ui/buttons.js'; +import { baseEmbed, successEmbed } from '../../ui/embeds.js'; + +const log = createLogger('voice'); + +export const DEFAULT_TEMPLATE = '🔊 Salon de {user}'; +/** Discord caps the user limit of a voice channel at 99 (0 means unlimited). */ +export const LIMIT_MAX = 99; +export const NAME_MAX = 100; +/** + * Delay before an empty temporary channel is deleted, so a quick move does not destroy a channel + * its owner customised. `VOICE_EMPTY_GRACE_MS=0` deletes it as soon as it is empty (M14-T04). + */ +const EMPTY_GRACE_MS = Math.max(0, env.voice.emptyGraceMs); +/** Interval of the safety net that catches the channels an event could not clean up. */ +const SWEEP_INTERVAL_MS = 60_000; + +/** Creation in flight per member, to never create two channels for the same person (M14-T02). */ +const pendingCreations = new Set(); +/** Channel id -> panel message id, so buttons can be refreshed after a change (M14-T05). */ +const panelMessages = new Map(); + +const VIEW = PermissionFlagsBits.ViewChannel; +const CONNECT = PermissionFlagsBits.Connect; +const SPEAK = PermissionFlagsBits.Speak; +const MEMBER_ALLOW = [VIEW, CONNECT, SPEAK]; +const OWNER_ALLOW = [...MEMBER_ALLOW, PermissionFlagsBits.ManageChannels, PermissionFlagsBits.MoveMembers]; +/** Named form required by `permissionOverwrites.edit()` (permission bits are not keys). */ +const OWNER_OVERWRITE = Object.freeze({ + ViewChannel: true, + Connect: true, + Speak: true, + ManageChannels: true, + MoveMembers: true, +}); + +/** Strips control characters without a control-character regex, then collapses spaces. */ +const clean = (value) => + [...String(value ?? '')] + .map((char) => { + const code = char.codePointAt(0); + return code <= 31 || code === 127 ? ' ' : char; + }) + .join('') + .replace(/\s+/g, ' ') + .trim(); + +/** Channel names are normalised and truncated before they reach Discord (M14-T08). */ +export function sanitizeChannelName(value) { + const name = clean(value); + if (!name) throw new UserFacingError('Il me manque un nom : écris au moins un caractère pour ton salon.'); + return name.slice(0, NAME_MAX); +} + +/** `🔊 Salon de {user}` -> the name of the channel created for a member. */ +export function buildChannelName(template, member) { + const replaced = String(template || DEFAULT_TEMPLATE).replaceAll( + '{user}', + member.displayName ?? member.user?.username ?? '', + ); + return clean(replaced).slice(0, NAME_MAX) || '🔊 Salon vocal'; +} + +/** `0` means unlimited; anything outside 0..99 is rejected or ignored (M14-T06). */ +export function clampLimit(value, { strict = false } = {}) { + const limit = Number(value); + if (!Number.isInteger(limit) || limit < 0 || limit > LIMIT_MAX) { + if (strict) { + throw new UserFacingError( + `Indique un nombre entre 0 (aucune limite) et ${LIMIT_MAX}. Par exemple 5 pour cinq places.`, + ); + } + return 0; + } + return limit; +} + +/** Index of the last slot of a category once the new channel is part of it (M14-T02). */ +export function bottomPosition(childCount) { + return Math.max(0, Number(childCount) - 1); +} + +/** + * Every trigger channel declared for a guild, so one server can host several of them + * ("dev", "sio", …), each with its own home category (M14-T01). Triggers written by the + * single-trigger version and the environment are still accepted as fallbacks. + */ +export function getVoiceTriggers(guildId) { + const triggers = new Map(); + + let rows = []; + try { + rows = listVoiceTriggers(guildId); + } catch (error) { + log.warn('Could not read the voice triggers', error); + } + + for (const row of rows) { + triggers.set(row.trigger_id, { + triggerId: row.trigger_id, + label: row.label || null, + categoryId: row.category_id || null, + template: row.template || DEFAULT_TEMPLATE, + userLimit: clampLimit(row.user_limit), + enabled: Boolean(row.enabled), + source: 'database', + }); + } + + const legacyId = resolveSetting(guildId, 'voice.trigger', null); + if (legacyId && !triggers.has(legacyId)) { + triggers.set(legacyId, { + triggerId: legacyId, + label: null, + categoryId: resolveSetting(guildId, 'voice.category', env.channels.voiceCategory) || null, + template: resolveSetting(guildId, 'voice.template', DEFAULT_TEMPLATE) || DEFAULT_TEMPLATE, + userLimit: clampLimit(resolveSetting(guildId, 'voice.limit', 0)), + enabled: true, + source: 'settings', + }); + } + + const envId = env.channels.voiceTrigger; + if (envId && !triggers.has(envId)) { + triggers.set(envId, { + triggerId: envId, + label: null, + categoryId: env.channels.voiceCategory || null, + template: DEFAULT_TEMPLATE, + userLimit: 0, + enabled: true, + source: 'env', + }); + } + + return [...triggers.values()]; +} + +/** Any declared trigger, disabled ones included, so the commands can report and toggle them. */ +export function findTrigger(guildId, triggerId) { + return getVoiceTriggers(guildId).find((trigger) => trigger.triggerId === triggerId) ?? null; +} + +/** An enabled trigger: joining it creates a temporary channel (M14-T02). */ +export function getVoiceTrigger(guildId, triggerId) { + const trigger = findTrigger(guildId, triggerId); + return trigger?.enabled ? trigger : null; +} + +export function isTriggerChannel(guildId, channelId) { + return getVoiceTrigger(guildId, channelId) !== null; +} + +/** Triggers with the number of channels they currently host, for the configuration embed. */ +export function listTriggerSummaries(guildId) { + return getVoiceTriggers(guildId).map((trigger) => ({ + ...trigger, + activeChannels: countVoiceChannelsByTrigger(trigger.triggerId), + })); +} + +/** Declares or updates a trigger; an omitted field keeps its stored value (M14-T01). */ +export function saveVoiceTrigger(guildId, patch, updatedBy = null) { + const existing = patch.triggerId ? findTrigger(guildId, patch.triggerId) : null; + + upsertVoiceTrigger({ + triggerId: patch.triggerId, + guildId, + label: patch.label ?? existing?.label ?? null, + categoryId: patch.categoryId ?? existing?.categoryId ?? null, + template: patch.template ?? existing?.template ?? DEFAULT_TEMPLATE, + userLimit: clampLimit(patch.userLimit ?? existing?.userLimit ?? 0), + enabled: patch.enabled ?? existing?.enabled ?? true, + }); + + logEvent({ + guildId, + type: 'voice.trigger.saved', + actorId: updatedBy, + payload: { triggerId: patch.triggerId }, + }); + return findTrigger(guildId, patch.triggerId); +} + +/** Writes the trigger before toggling it, so an environment fallback can be switched off. */ +export function setTriggerEnabled(guildId, triggerId, enabled) { + const trigger = findTrigger(guildId, triggerId); + if (!trigger) + throw new UserFacingError('Ce salon n’est pas un déclencheur : ajoute-le d’abord avec `/voice setup`.'); + if (trigger.enabled === enabled) { + throw new UserFacingError( + enabled + ? 'Ce déclencheur est déjà actif — il n’y a rien à changer.' + : 'Ce déclencheur est déjà désactivé — il n’y a rien à changer.', + ); + } + + upsertVoiceTrigger({ + triggerId, + guildId, + label: trigger.label, + categoryId: trigger.categoryId, + template: trigger.template, + userLimit: trigger.userLimit, + enabled, + }); + logEvent({ guildId, type: 'voice.trigger.toggled', payload: { triggerId, enabled } }); + return findTrigger(guildId, triggerId); +} + +/** Removes a trigger declared from Discord; the ones coming from the environment cannot be deleted. */ +export function removeVoiceTriggerConfig(guildId, triggerId) { + const trigger = findTrigger(guildId, triggerId); + if (!trigger) + throw new UserFacingError('Ce salon n’est pas un déclencheur : il n’y a donc rien à supprimer.'); + if (trigger.source !== 'database') { + throw new UserFacingError( + 'Ce déclencheur vient des variables d’environnement (`CHANNEL_VOICE_TRIGGER_ID`) : je ne peux pas le supprimer d’ici. Retire‑le du `.env`, ou mets‑le en pause avec `/voice triggers disable`.', + ); + } + + deleteVoiceTriggerRow(triggerId); + logEvent({ guildId, type: 'voice.trigger.removed', payload: { triggerId } }); +} + +export function isStaff(member, roles = env.roles) { + return getAccessLevel(member, roles) >= ACCESS_LEVELS.STAFF; +} + +export function isManagedChannel(channelId) { + return Boolean(getVoiceChannel(channelId)); +} + +/** Embed shown in the panel and by `/voice info` (M14-T05). */ +export function voicePanelEmbed(channel, row) { + const ownerId = row?.owner_id ?? null; + return baseEmbed(COLORS.primary) + .setTitle(`Gestion de ${channel.name}`) + .setDescription( + 'Les boutons ci-dessous agissent sur ce salon seulement. Tu retrouves exactement les mêmes options dans `/voice`.', + ) + .addFields( + { name: 'Propriétaire', value: ownerId ? `<@${ownerId}>` : 'Personne', inline: true }, + { name: 'Statut', value: row?.locked ? '🔒 Verrouillé' : '🔓 Ouvert', inline: true }, + { name: 'Limite', value: row?.user_limit ? `${row.user_limit} places` : 'Illimitée', inline: true }, + { + name: 'Membres', + value: row?.user_limit ? `${channel.members.size} / ${row.user_limit}` : String(channel.members.size), + inline: true, + }, + ); +} + +export function voiceInfoEmbed(channel, row) { + const embed = baseEmbed(COLORS.primary) + .setTitle(channel.name) + .addFields( + { name: 'Propriétaire', value: row?.owner_id ? `<@${row.owner_id}>` : 'Personne', inline: true }, + { name: 'Statut', value: row?.locked ? '🔒 Verrouillé' : '🔓 Ouvert', inline: true }, + { name: 'Limite', value: row?.user_limit ? `${row.user_limit} places` : 'Illimitée', inline: true }, + { + name: 'Membres', + value: + channel.members.size === 0 + ? 'Aucun' + : channel.members + .first(10) + .map((member) => `<@${member.id}>`) + .join(', '), + }, + ) + .addFields({ name: 'Créé', value: ``, inline: true }); + + if (row?.trigger_id) + embed.setFooter({ text: `Salon temporaire · créé depuis le déclencheur ${row.trigger_id}` }); + return embed; +} + +/** Posts the control panel in the text chat of the voice channel (M14-T05). */ +async function postPanel(channel, row) { + if (!channel.isSendable?.()) return; + + const message = await channel + .send({ + embeds: [voicePanelEmbed(channel, row)], + components: voicePanelComponents({ locked: Boolean(row.locked) }), + }) + .catch((error) => { + log.warn('Could not post the voice panel', error); + return null; + }); + if (message) panelMessages.set(channel.id, message.id); +} + +/** Refreshes the panel buttons after a change, best effort (M14-T05). */ +export async function refreshPanel(channel) { + const messageId = panelMessages.get(channel.id); + const row = getVoiceChannel(channel.id); + if (!messageId || !row || !channel.isSendable?.()) return; + + const message = await channel.messages.fetch(messageId).catch(() => null); + await message + ?.edit({ + embeds: [voicePanelEmbed(channel, row)], + components: voicePanelComponents({ locked: Boolean(row.locked) }), + }) + .catch(() => {}); +} + +/** Drops a channel from the database and from the panel cache. */ +function forgetVoiceChannel(channelId) { + removeVoiceChannel(channelId); + panelMessages.delete(channelId); +} + +/** + * The channel an owner can be moved back into: only one created from the same trigger, so that + * each trigger keeps its own channel in its own category (M14-T03). Rows of vanished channels + * are dropped along the way, whichever trigger they came from. + */ +async function findReusableChannel(guild, ownerId, triggerId) { + for (const row of listOwnedVoiceChannels(guild.id, ownerId)) { + const channel = guild.channels.cache.get(row.channel_id); + if (!channel) { + forgetVoiceChannel(row.channel_id); + continue; + } + if (row.trigger_id !== triggerId) continue; + + const full = channel.userLimit > 0 && channel.members.size >= channel.userLimit; + if (!full) return { channel, row }; + } + return null; +} + +/** New channels are appended below the ones already sitting in the target category (M14-T02). */ +async function placeAtBottomOfCategory(channel) { + if (!channel.parentId) return; + + const siblings = channel.guild.channels.cache.filter( + (candidate) => candidate.parentId === channel.parentId, + ); + const target = bottomPosition(siblings.size); + if (channel.position === target) return; + + await channel + .setPosition(target, { reason: 'Nouveau salon en bas de sa catégorie' }) + .catch((error) => log.warn('Could not move the new channel to the bottom of its category', error)); +} + +function buildOverwrites(guild, client, ownerId) { + return [ + { id: guild.roles.everyone.id, allow: MEMBER_ALLOW }, + { id: ownerId, allow: OWNER_ALLOW }, + { id: client.user.id, allow: OWNER_ALLOW }, + ]; +} + +/** + * Called when a member joins a trigger channel: creates their channel in the category of that + * trigger, below the channels already there, or moves them back into the one they already own + * (M14-T02 / M14-T03). + */ +export async function createFromTrigger(member, trigger) { + if (!trigger?.triggerId || pendingCreations.has(member.id)) return null; + + const reusable = await findReusableChannel(member.guild, member.id, trigger.triggerId); + if (reusable) { + await member.voice + .setChannel(reusable.channel, 'Retour dans son salon vocal temporaire') + .catch((error) => log.warn('Could not move the member back into their channel', error)); + return reusable.channel; + } + + pendingCreations.add(member.id); + try { + const parent = trigger.categoryId + ? await member.guild.channels.fetch(trigger.categoryId).catch(() => null) + : null; + + const channel = await member.guild.channels.create({ + name: buildChannelName(trigger.template, member), + type: ChannelType.GuildVoice, + userLimit: trigger.userLimit, + ...(parent?.type === ChannelType.GuildCategory && { parent: parent.id }), + reason: `Salon vocal temporaire de ${member.user.tag}`, + permissionOverwrites: buildOverwrites(member.guild, member.client, member.id), + }); + + await placeAtBottomOfCategory(channel); + + addVoiceChannel({ + channelId: channel.id, + guildId: member.guild.id, + ownerId: member.id, + triggerId: trigger.triggerId, + name: channel.name, + userLimit: trigger.userLimit, + }); + + await member.voice + .setChannel(channel, 'Salon vocal temporaire créé') + .catch((error) => log.warn('Could not move the member into their new channel', error)); + + await postPanel(channel, getVoiceChannel(channel.id)); + logEvent({ + guildId: member.guild.id, + type: 'voice.created', + actorId: member.id, + payload: { channelId: channel.id, ownerId: member.id }, + }); + return channel; + } finally { + pendingCreations.delete(member.id); + } +} + +/** + * Deletes a temporary channel. The row is only dropped once the channel is really gone, so that a + * failed API call leaves a channel the sweep can retry instead of an orphaned room (M14-T04). + */ +export async function deleteVoiceChannel(channel, reason = 'Salon vocal temporaire supprimé') { + try { + await channel.delete(reason); + } catch (error) { + if (!(await isChannelGone(channel, error))) { + log.warn('Could not delete the voice channel', error); + return false; + } + } + + forgetVoiceChannel(channel.id); + return true; +} + +/** A 404 or an unknown-channel error means the channel is already deleted, whatever the cause. */ +async function isChannelGone(channel, error) { + const codes = [error?.code, String(error?.code ?? '')]; + if (error?.status === 404 || codes.includes(10003)) return true; + + const fresh = await channel.guild.channels.fetch(channel.id).catch(() => null); + return fresh === null; +} + +/** Resolves a channel from the cache or the API, or `null` when it does not exist anymore. */ +async function resolveChannel(guild, channelId) { + return guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null)); +} + +/** + * Deletes an empty temporary channel after a short grace period, so that a member moving between + * channels does not lose the one they customised (M14-T04). + */ +export async function cleanupVoiceChannel(guild, channelId, { graceMs = EMPTY_GRACE_MS } = {}) { + const row = getVoiceChannel(channelId); + if (!row) return; + + const channel = await resolveChannel(guild, channelId); + if (!channel) { + forgetVoiceChannel(channelId); + return; + } + if (channel.members.size > 0) return; + + const removeEmptyChannel = async () => { + const fresh = await resolveChannel(guild, channelId); + if (!fresh) { + forgetVoiceChannel(channelId); + return; + } + if (fresh.members.size > 0) return; + + if (await deleteVoiceChannel(fresh, 'Salon vocal temporaire vide')) { + logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId } }); + } + }; + + if (graceMs <= 0) { + await removeEmptyChannel().catch((error) => log.warn('Could not clean up an empty voice channel', error)); + return; + } + + setTimeout( + () => removeEmptyChannel().catch((error) => log.warn('Could not clean up an empty voice channel', error)), + graceMs, + ).unref(); +} + +/** + * Forgets the channels that no longer exist and deletes the ones with nobody left in them + * (M14-T04 / M14-T07). Run at startup and then every minute: the voice state event is the fast + * path, this sweep is the guarantee when an event is missed or a deletion failed. + */ +export async function sweepVoiceChannels(client) { + for (const guild of client.guilds.cache.values()) { + let rows = []; + try { + rows = listVoiceChannels(guild.id); + } catch (error) { + log.warn('Could not read the stored voice channels', error); + continue; + } + + for (const row of rows) { + const channel = await resolveChannel(guild, row.channel_id); + if (!channel) { + forgetVoiceChannel(row.channel_id); + continue; + } + if (channel.members.size > 0) continue; + + if (await deleteVoiceChannel(channel, 'Salon vocal temporaire vide')) { + log.info(`Deleted the empty temporary channel ${row.channel_id}`); + logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId: row.channel_id } }); + } + } + } +} + +/** Starts the periodic sweep; the returned interval can be cleared to stop it (M14-T04). */ +export function startVoiceJanitor(client, intervalMs = SWEEP_INTERVAL_MS) { + const timer = setInterval(() => { + sweepVoiceChannels(client).catch((error) => log.error('Voice channel sweep failed', error)); + }, intervalMs); + timer.unref?.(); + return timer; +} + +export function activeChannelCount(guildId) { + return countVoiceChannels(guildId); +} + +/** Channel of the interaction itself, when it is a temporary voice channel (panel buttons and modals). */ +function managedChannelOf(interaction) { + return interaction.channelId && isManagedChannel(interaction.channelId) ? interaction.channelId : null; +} + +/** + * Resolves the temporary channel an action applies to: the explicit option first, then the + * channel the interaction happened in (panel, modal), then the voice channel of the caller (M14-T05). + */ +export async function resolveManagedChannel(interaction, { channelId = null } = {}) { + const id = channelId ?? managedChannelOf(interaction) ?? interaction.member?.voice?.channelId ?? null; + const row = id ? getVoiceChannel(id) : null; + if (!row) { + throw new UserFacingError( + 'Je ne trouve pas ton salon temporaire : entre dans ton salon vocal, puis relance la commande — ou indique‑le avec l’option `channel`.', + ); + } + if (channelId && channelId !== interaction.member?.voice?.channelId && !isStaff(interaction.member)) { + // An explicit channel is a staff convenience only: a member manages their own channel. + throw new PermissionDeniedError( + 'C’est réservé à l’équipe : chaque personne gère son propre salon. Tu peux modifier le tien, sans option `channel`.', + ); + } + + const channel = await interaction.guild.channels.fetch(row.channel_id).catch(() => null); + if (!channel) { + forgetVoiceChannel(row.channel_id); + throw new UserFacingError('Ce salon n’existe plus — il a sûrement déjà été supprimé.'); + } + return { channel, row }; +} + +/** Only the owner may manage a channel; staff can always step in (M14-T06). */ +export function assertVoiceOwner(interaction, row, action = 'gérer ce salon') { + if (row.owner_id === interaction.user.id || isStaff(interaction.member)) return; + throw new PermissionDeniedError( + `Ce salon appartient à <@${row.owner_id}> : seule cette personne (ou l’équipe) peut ${action}.`, + ); +} + +const ephemeral = (payload) => ({ ...payload, flags: MessageFlags.Ephemeral }); + +export async function renameChannel(interaction, name) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'renommer le salon'); + + const sanitized = sanitizeChannelName(name); + await channel.setName(sanitized, `Renommé par ${interaction.user.tag}`); + setVoiceName(channel.id, sanitized); + await refreshPanel(channel); + + await interaction.reply( + ephemeral({ embeds: [successEmbed(`Ton salon s’appelle maintenant **${sanitized}**.`)] }), + ); +} + +export async function setChannelLimit(interaction, limit) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'changer la limite'); + + const value = clampLimit(limit, { strict: true }); + await channel.setUserLimit(value, `Limite modifiée par ${interaction.user.tag}`); + setVoiceLimit(channel.id, value); + await refreshPanel(channel); + + await interaction.reply( + ephemeral({ + embeds: [ + successEmbed( + value === 0 + ? 'Ton salon n’a plus de limite de places : tout le monde peut entrer.' + : `Ton salon accueille maintenant **${value} personnes**.`, + ), + ], + }), + ); +} + +export async function toggleLock(interaction, { locked = null } = {}) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'verrouiller le salon'); + + const next = locked === null ? !row.locked : Boolean(locked); + if (next === Boolean(row.locked)) { + throw new UserFacingError( + next + ? 'Ton salon est déjà verrouillé — il n’y a rien à changer.' + : 'Ton salon est déjà ouvert — il n’y a rien à changer.', + ); + } + await channel.permissionOverwrites.edit( + interaction.guild.roles.everyone.id, + { Connect: next ? false : null }, + { reason: `${next ? 'Verrouillé' : 'Déverrouillé'} par ${interaction.user.tag}` }, + ); + setVoiceLocked(channel.id, next); + await refreshPanel(channel); + + await interaction.reply( + ephemeral({ + embeds: [ + successEmbed( + next + ? '🔒 Salon verrouillé : seules les personnes que tu autorises peuvent entrer.' + : '🔓 Salon ouvert : tout le monde peut entrer.', + ), + ], + }), + ); +} + +export async function permitUser(interaction, userId) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'autoriser un membre'); + + await channel.permissionOverwrites.edit( + userId, + { ViewChannel: true, Connect: true }, + { + reason: `Autorisé par ${interaction.user.tag}`, + }, + ); + await interaction.reply( + ephemeral({ embeds: [successEmbed(`C’est noté : <@${userId}> peut entrer dans ton salon.`)] }), + ); +} + +export async function rejectUser(interaction, userId) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'refuser un membre'); + + await channel.permissionOverwrites.edit( + userId, + { ViewChannel: false, Connect: false }, + { + reason: `Refusé par ${interaction.user.tag}`, + }, + ); + const member = channel.members.get(userId); + await member?.voice.disconnect(`Refusé par ${interaction.user.tag}`).catch(() => {}); + + await interaction.reply( + ephemeral({ embeds: [successEmbed(`C’est noté : <@${userId}> ne peut plus entrer dans ton salon.`)] }), + ); +} + +export async function kickUser(interaction, userId) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'exclure un membre'); + + const member = channel.members.get(userId); + if (!member) throw new UserFacingError('Ce membre n’est pas dans ton salon — il n’y a rien à faire.'); + if (member.id === row.owner_id) + throw new UserFacingError('Impossible : la personne propriétaire du salon ne peut pas en être exclue.'); + + await member.voice.disconnect(`Exclu par ${interaction.user.tag}`); + await interaction.reply( + ephemeral({ embeds: [successEmbed(`<@${userId}> ne fait plus partie de ton salon.`)] }), + ); +} + +export async function transferOwnership(interaction, userId) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'transférer le salon'); + + const member = channel.members.get(userId); + if (!member) + throw new UserFacingError( + 'Cette personne doit déjà être dans le salon pour en devenir propriétaire : invite‑la, puis relance la commande.', + ); + if (member.id === row.owner_id) + throw new UserFacingError('Cette personne est déjà propriétaire de ce salon.'); + + await channel.permissionOverwrites + .edit(row.owner_id, { ManageChannels: null, MoveMembers: null }, { reason: 'Nouveau propriétaire' }) + .catch(() => {}); + await channel.permissionOverwrites.edit(member.id, OWNER_OVERWRITE, { + reason: `Salon transféré par ${interaction.user.tag}`, + }); + + setVoiceOwner(channel.id, member.id); + await refreshPanel(channel); + logEvent({ + guildId: interaction.guildId, + type: 'voice.transferred', + actorId: interaction.user.id, + payload: { channelId: channel.id, ownerId: member.id }, + }); + + await interaction.reply( + ephemeral({ + embeds: [ + successEmbed(`<@${member.id}> est désormais propriétaire de **${channel.name}**. Bonne session !`), + ], + }), + ); +} + +/** A member may take over a channel whose owner is gone (M14-T03). */ +export async function claimOwnership(interaction) { + const { channel, row } = await resolveManagedChannel(interaction); + if (row.owner_id === interaction.user.id) { + throw new UserFacingError('Tu es déjà propriétaire de ce salon — tout est en ordre.'); + } + if (channel.members.has(row.owner_id)) { + throw new UserFacingError( + 'La personne propriétaire est encore dans le salon : ce salon n’est pas abandonné.', + ); + } + if (!channel.members.has(interaction.user.id)) { + throw new UserFacingError( + 'Entre d’abord dans le salon, puis relance la commande : la propriété se réclame depuis l’intérieur.', + ); + } + + await channel.permissionOverwrites.edit(interaction.user.id, OWNER_OVERWRITE, { + reason: `Salon réclamé par ${interaction.user.tag}`, + }); + setVoiceOwner(channel.id, interaction.user.id); + await refreshPanel(channel); + logEvent({ + guildId: interaction.guildId, + type: 'voice.claimed', + actorId: interaction.user.id, + payload: { channelId: channel.id }, + }); + + await interaction.reply( + ephemeral({ embeds: [successEmbed('Tu es désormais propriétaire de ce salon. Amuse‑toi bien !')] }), + ); +} + +export async function removeChannel(interaction, { channelId = null } = {}) { + const { channel, row } = await resolveManagedChannel(interaction, { channelId }); + assertVoiceOwner(interaction, row, 'supprimer le salon'); + + await interaction.reply( + ephemeral({ + embeds: [ + successEmbed(`Le salon **${channel.name}** disparaît dans 3 secondes. Merci pour la session !`), + ], + }), + ); + logEvent({ + guildId: interaction.guildId, + type: 'voice.deleted', + actorId: interaction.user.id, + payload: { channelId: channel.id }, + }); + setTimeout( + () => deleteVoiceChannel(channel, `Supprimé par ${interaction.user.tag}`).catch(() => {}), + 3_000, + ).unref(); +} + +export async function showInfo(interaction, { channelId = null } = {}) { + const { channel, row } = await resolveManagedChannel(interaction, { channelId }); + await interaction.reply(ephemeral({ embeds: [voiceInfoEmbed(channel, row)] })); +} + +/** Embed published in a trigger channel to explain the "join to create" flow (M14-T01). */ +function triggerPanelEmbed(trigger, channel) { + return baseEmbed(COLORS.primary) + .setTitle('🎧 Salons vocaux temporaires') + .setDescription( + `Rejoins ${channel} pour obtenir ton propre salon vocal.\n\n` + + 'Tu en deviens le propriétaire : renomme-le, limite le nombre de places, verrouille-le, ' + + 'autorise ou exclus des membres, ou transfère-le — depuis les boutons du salon ou les commandes `/voice`.', + ) + .addFields( + { + name: 'Catégorie', + value: trigger.categoryId ? `<#${trigger.categoryId}>` : 'Celle du salon déclencheur', + inline: true, + }, + { + name: 'Limite par défaut', + value: trigger.userLimit ? `${trigger.userLimit} places` : 'Illimitée', + inline: true, + }, + ); +} + +/** + * Publishes the explanation panel in one trigger, or in every enabled trigger of the guild + * when no trigger is given (M14-T01). + */ +export async function postSetupPanel(interaction, { triggerId = null } = {}) { + const triggers = getVoiceTriggers(interaction.guildId).filter( + (trigger) => trigger.enabled && (!triggerId || trigger.triggerId === triggerId), + ); + if (triggers.length === 0) { + throw new UserFacingError( + triggerId + ? 'Ce salon n’est pas un déclencheur actif : configure‑le avec `/voice setup`.' + : 'Aucun salon vocal déclencheur n’est configuré : lance `/voice setup`.', + ); + } + + const published = []; + for (const trigger of triggers) { + const channel = await interaction.guild.channels.fetch(trigger.triggerId).catch(() => null); + if (!channel?.isVoiceBased?.() || !channel.isSendable()) { + log.warn(`Skipped the panel of ${trigger.triggerId}: not a sendable voice channel`); + continue; + } + + await channel.send({ embeds: [triggerPanelEmbed(trigger, channel)] }).catch((error) => { + log.warn('Could not publish the voice panel', error); + }); + published.push(trigger.triggerId); + } + + if (published.length === 0) { + throw new UserFacingError( + 'Aucun panneau n’a pu être publié : vérifie que je peux écrire dans les salons déclencheurs.', + ); + } + + await interaction.reply( + ephemeral({ + embeds: [successEmbed(`Panneau publié dans ${published.map((id) => `<#${id}>`).join(', ')}.`)], + }), + ); +} + +/** Button and select menu routing (M14-T05). */ +export async function handleVoiceComponent(interaction) { + const action = interaction.customId.split(':')[1]; + + if (interaction.isUserSelectMenu()) { + const userId = interaction.values[0]; + switch (action) { + case 'permit': + await permitUser(interaction, userId); + return; + case 'kick': + await kickUser(interaction, userId); + return; + case 'transfer': + await transferOwnership(interaction, userId); + return; + default: + log.debug(`Ignored voice select ${interaction.customId}`); + return; + } + } + + switch (action) { + case 'rename': + await openRenameModal(interaction); + return; + case 'limit': + await openLimitModal(interaction); + return; + case 'lock': + await toggleLock(interaction); + return; + case 'claim': + await claimOwnership(interaction); + return; + case 'info': + await showInfo(interaction); + return; + case 'delete': + await removeChannel(interaction); + return; + default: + log.debug(`Ignored voice component ${interaction.customId}`); + } +} + +async function openRenameModal(interaction) { + const { channel, row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'renommer le salon'); + + await interaction.showModal( + new ModalBuilder() + .setCustomId('voice:rename:modal') + .setTitle('Renommer le salon') + .addComponents( + new ActionRowBuilder().addComponents( + new TextInputBuilder() + .setCustomId('name') + .setLabel('Nouveau nom') + .setStyle(TextInputStyle.Short) + .setMaxLength(NAME_MAX) + .setValue(channel.name.slice(0, NAME_MAX)) + .setRequired(true), + ), + ), + ); +} + +async function openLimitModal(interaction) { + const { row } = await resolveManagedChannel(interaction); + assertVoiceOwner(interaction, row, 'changer la limite'); + + await interaction.showModal( + new ModalBuilder() + .setCustomId('voice:limit:modal') + .setTitle('Limite de places') + .addComponents( + new ActionRowBuilder().addComponents( + new TextInputBuilder() + .setCustomId('limit') + .setLabel(`Entre 0 (illimité) et ${LIMIT_MAX}`) + .setStyle(TextInputStyle.Short) + .setMaxLength(2) + .setValue(String(row.user_limit ?? 0)) + .setRequired(true), + ), + ), + ); +} + +/** Modal submissions opened from the panel (M14-T05). */ +export async function handleVoiceModal(interaction) { + if (interaction.customId === 'voice:rename:modal') { + await renameChannel(interaction, interaction.fields.getTextInputValue('name')); + return; + } + + if (interaction.customId === 'voice:limit:modal') { + const raw = interaction.fields.getTextInputValue('limit').trim(); + const limit = Number.parseInt(raw, 10); + if (!/^\d{1,2}$/.test(raw)) { + throw new UserFacingError(`Indique un nombre entier entre 0 (illimité) et ${LIMIT_MAX}.`); + } + await setChannelLimit(interaction, limit); + return; + } + + log.debug(`Ignored voice modal ${interaction.customId}`); +} diff --git a/src/ui/buttons.js b/src/ui/buttons.js index 5bc08d3..97bf5b1 100644 --- a/src/ui/buttons.js +++ b/src/ui/buttons.js @@ -1,99 +1,99 @@ -import { ActionRowBuilder, ButtonBuilder, ButtonStyle, UserSelectMenuBuilder } from 'discord.js'; - -/** Discord label and custom id limits. */ -const LABEL_MAX = 80; -export const POLL_CHOICES_MAX = 10; - -function truncate(text, max) { - return text.length > max ? `${text.slice(0, max - 1)}…` : text; -} - -/** Builds a row of link buttons, skipping links without a URL (M12-T03). */ -export function linkButtons(links) { - const buttons = links - .filter((link) => link.url) - .slice(0, 5) - .map((link) => new ButtonBuilder().setStyle(ButtonStyle.Link).setLabel(link.label).setURL(link.url)); - - return buttons.length > 0 ? [new ActionRowBuilder().addComponents(buttons)] : []; -} - -/** Claim / close controls posted in a ticket channel (M6-T05 / M6-T06). */ -export function ticketButtons() { - return [ - new ActionRowBuilder().addComponents( - new ButtonBuilder() - .setCustomId('ticket:claim') - .setLabel('Prendre en charge') - .setStyle(ButtonStyle.Primary), - new ButtonBuilder().setCustomId('ticket:close').setLabel('Fermer').setStyle(ButtonStyle.Danger), - ), - ]; -} - -/** - * Control panel posted in a temporary voice channel (M14-T05): - * buttons for the whole channel, select menus for a specific member. - */ -export function voicePanelComponents({ locked = false } = {}) { - return [ - new ActionRowBuilder().addComponents( - new ButtonBuilder() - .setCustomId('voice:rename') - .setLabel('Renommer') - .setEmoji('✏️') - .setStyle(ButtonStyle.Secondary), - new ButtonBuilder() - .setCustomId('voice:limit') - .setLabel('Limiter') - .setEmoji('👥') - .setStyle(ButtonStyle.Secondary), - new ButtonBuilder() - .setCustomId('voice:lock') - .setLabel(locked ? 'Déverrouiller' : 'Verrouiller') - .setEmoji(locked ? '🔓' : '🔒') - .setStyle(locked ? ButtonStyle.Success : ButtonStyle.Secondary), - new ButtonBuilder() - .setCustomId('voice:claim') - .setLabel('Réclamer') - .setEmoji('👑') - .setStyle(ButtonStyle.Primary), - new ButtonBuilder() - .setCustomId('voice:delete') - .setLabel('Supprimer') - .setEmoji('🗑️') - .setStyle(ButtonStyle.Danger), - ), - memberSelect('voice:permit', 'Autoriser un membre à rejoindre...'), - memberSelect('voice:kick', 'Exclure un membre du salon...'), - memberSelect('voice:transfer', 'Transférer la propriété du salon...'), - ]; -} - -function memberSelect(customId, placeholder) { - return new ActionRowBuilder().addComponents( - new UserSelectMenuBuilder() - .setCustomId(customId) - .setPlaceholder(placeholder) - .setMinValues(1) - .setMaxValues(1), - ); -} - -/** One button per choice, 5 per row at most (M10-T02). */ -export function pollButtons(pollId, choices) { - const rows = []; - for (let start = 0; start < Math.min(choices.length, POLL_CHOICES_MAX); start += 5) { - rows.push( - new ActionRowBuilder().addComponents( - choices.slice(start, start + 5).map((choice, offset) => - new ButtonBuilder() - .setCustomId(`poll:${pollId}:${start + offset}`) - .setLabel(truncate(choice, LABEL_MAX)) - .setStyle(ButtonStyle.Secondary), - ), - ), - ); - } - return rows; -} +import { ActionRowBuilder, ButtonBuilder, ButtonStyle, UserSelectMenuBuilder } from 'discord.js'; + +/** Discord label and custom id limits. */ +const LABEL_MAX = 80; +export const POLL_CHOICES_MAX = 10; + +function truncate(text, max) { + return text.length > max ? `${text.slice(0, max - 1)}…` : text; +} + +/** Builds a row of link buttons, skipping links without a URL (M12-T03). */ +export function linkButtons(links) { + const buttons = links + .filter((link) => link.url) + .slice(0, 5) + .map((link) => new ButtonBuilder().setStyle(ButtonStyle.Link).setLabel(link.label).setURL(link.url)); + + return buttons.length > 0 ? [new ActionRowBuilder().addComponents(buttons)] : []; +} + +/** Claim / close controls posted in a ticket channel (M6-T05 / M6-T06). */ +export function ticketButtons() { + return [ + new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId('ticket:claim') + .setLabel('Prendre en charge') + .setStyle(ButtonStyle.Primary), + new ButtonBuilder().setCustomId('ticket:close').setLabel('Fermer').setStyle(ButtonStyle.Danger), + ), + ]; +} + +/** + * Control panel posted in a temporary voice channel (M14-T05): + * buttons for the whole channel, select menus for a specific member. + */ +export function voicePanelComponents({ locked = false } = {}) { + return [ + new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId('voice:rename') + .setLabel('Renommer') + .setEmoji('✏️') + .setStyle(ButtonStyle.Secondary), + new ButtonBuilder() + .setCustomId('voice:limit') + .setLabel('Limiter') + .setEmoji('👥') + .setStyle(ButtonStyle.Secondary), + new ButtonBuilder() + .setCustomId('voice:lock') + .setLabel(locked ? 'Déverrouiller' : 'Verrouiller') + .setEmoji(locked ? '🔓' : '🔒') + .setStyle(locked ? ButtonStyle.Success : ButtonStyle.Secondary), + new ButtonBuilder() + .setCustomId('voice:claim') + .setLabel('Réclamer') + .setEmoji('👑') + .setStyle(ButtonStyle.Primary), + new ButtonBuilder() + .setCustomId('voice:delete') + .setLabel('Supprimer') + .setEmoji('🗑️') + .setStyle(ButtonStyle.Danger), + ), + memberSelect('voice:permit', 'Autoriser un membre à rejoindre...'), + memberSelect('voice:kick', 'Exclure un membre du salon...'), + memberSelect('voice:transfer', 'Transférer la propriété du salon...'), + ]; +} + +function memberSelect(customId, placeholder) { + return new ActionRowBuilder().addComponents( + new UserSelectMenuBuilder() + .setCustomId(customId) + .setPlaceholder(placeholder) + .setMinValues(1) + .setMaxValues(1), + ); +} + +/** One button per choice, 5 per row at most (M10-T02). */ +export function pollButtons(pollId, choices) { + const rows = []; + for (let start = 0; start < Math.min(choices.length, POLL_CHOICES_MAX); start += 5) { + rows.push( + new ActionRowBuilder().addComponents( + choices.slice(start, start + 5).map((choice, offset) => + new ButtonBuilder() + .setCustomId(`poll:${pollId}:${start + offset}`) + .setLabel(truncate(choice, LABEL_MAX)) + .setStyle(ButtonStyle.Secondary), + ), + ), + ); + } + return rows; +} diff --git a/src/ui/embeds.js b/src/ui/embeds.js index 610f2b1..d4e2c79 100644 --- a/src/ui/embeds.js +++ b/src/ui/embeds.js @@ -1,55 +1,55 @@ -import { EmbedBuilder } from 'discord.js'; -import { BOT_NAME, COLORS } from '../config/constants.js'; - -/** - * Bot voice — one tone everywhere (M12-T02). Every user-facing string in the project follows - * these rules, so the messages stay consistent as commands are added: - * - * - Informal French, short sentences, active voice; never a reproach or irony. - * - The title states the outcome, the description says what to do next. - * - One emoji per title, never decorative inside the body. - * - No gendered agreement on a person: "tu es propriétaire", "ce membre", "l'équipe", - * "la personne" — never "il / elle", "cher / chère", "ravi·e". - * - An error explains the cause, recalls the rule and offers the way out. - * - Same vocabulary across modules: équipe, membre, salon, ticket, motif. - */ -export const TONE = Object.freeze({ - success: '✅ C’est fait', - error: '❌ Oups', - warning: '⚠️ Attention', - advice: '💡 Bon à savoir', -}); - -/** Base embed with the shared FWS-Bot visual identity (M12-T02). */ -export function baseEmbed(color = COLORS.primary) { - return new EmbedBuilder().setColor(color).setFooter({ text: BOT_NAME }).setTimestamp(); -} - -export function infoEmbed(title, description) { - return baseEmbed(COLORS.info).setTitle(title).setDescription(description); -} - -export function successEmbed(description, { title = TONE.success } = {}) { - return baseEmbed(COLORS.success).setTitle(title).setDescription(description); -} - -export function warningEmbed(description, { title = TONE.warning } = {}) { - return baseEmbed(COLORS.warning).setTitle(title).setDescription(description); -} - -export function errorEmbed(description, { title = TONE.error } = {}) { - return baseEmbed(COLORS.error).setTitle(title).setDescription(description); -} - -/** Uniform list marker, so every embed lists things the same way. */ -export function bullets(lines) { - return lines - .filter(Boolean) - .map((line) => `• ${line}`) - .join('\n'); -} - -/** Adds the "what you can do now" line that most replies end with. */ -export function withHint(description, hint) { - return hint ? `${description}\n\n${hint}` : description; -} +import { EmbedBuilder } from 'discord.js'; +import { BOT_NAME, COLORS } from '../config/constants.js'; + +/** + * Bot voice — one tone everywhere (M12-T02). Every user-facing string in the project follows + * these rules, so the messages stay consistent as commands are added: + * + * - Informal French, short sentences, active voice; never a reproach or irony. + * - The title states the outcome, the description says what to do next. + * - One emoji per title, never decorative inside the body. + * - No gendered agreement on a person: "tu es propriétaire", "ce membre", "l'équipe", + * "la personne" — never "il / elle", "cher / chère", "ravi·e". + * - An error explains the cause, recalls the rule and offers the way out. + * - Same vocabulary across modules: équipe, membre, salon, ticket, motif. + */ +export const TONE = Object.freeze({ + success: '✅ C’est fait', + error: '❌ Oups', + warning: '⚠️ Attention', + advice: '💡 Bon à savoir', +}); + +/** Base embed with the shared FWS-Bot visual identity (M12-T02). */ +export function baseEmbed(color = COLORS.primary) { + return new EmbedBuilder().setColor(color).setFooter({ text: BOT_NAME }).setTimestamp(); +} + +export function infoEmbed(title, description) { + return baseEmbed(COLORS.info).setTitle(title).setDescription(description); +} + +export function successEmbed(description, { title = TONE.success } = {}) { + return baseEmbed(COLORS.success).setTitle(title).setDescription(description); +} + +export function warningEmbed(description, { title = TONE.warning } = {}) { + return baseEmbed(COLORS.warning).setTitle(title).setDescription(description); +} + +export function errorEmbed(description, { title = TONE.error } = {}) { + return baseEmbed(COLORS.error).setTitle(title).setDescription(description); +} + +/** Uniform list marker, so every embed lists things the same way. */ +export function bullets(lines) { + return lines + .filter(Boolean) + .map((line) => `• ${line}`) + .join('\n'); +} + +/** Adds the "what you can do now" line that most replies end with. */ +export function withHint(description, hint) { + return hint ? `${description}\n\n${hint}` : description; +} diff --git a/src/utils/cooldown.js b/src/utils/cooldown.js index 150aa1b..3404b3d 100644 --- a/src/utils/cooldown.js +++ b/src/utils/cooldown.js @@ -1,18 +1,18 @@ -/** In-memory guard against duplicate actions within a time window (M13-T08). */ -export function createCooldown(windowMs) { - const entries = new Map(); - - return { - /** Returns true when the key is free, and locks it for `windowMs`. */ - acquire(key) { - const now = Date.now(); - const expiresAt = entries.get(key); - if (expiresAt && expiresAt > now) return false; - entries.set(key, now + windowMs); - return true; - }, - release(key) { - entries.delete(key); - }, - }; -} +/** In-memory guard against duplicate actions within a time window (M13-T08). */ +export function createCooldown(windowMs) { + const entries = new Map(); + + return { + /** Returns true when the key is free, and locks it for `windowMs`. */ + acquire(key) { + const now = Date.now(); + const expiresAt = entries.get(key); + if (expiresAt && expiresAt > now) return false; + entries.set(key, now + windowMs); + return true; + }, + release(key) { + entries.delete(key); + }, + }; +} diff --git a/src/utils/retry.js b/src/utils/retry.js index 5b56f0a..b0a60b3 100644 --- a/src/utils/retry.js +++ b/src/utils/retry.js @@ -1,19 +1,19 @@ -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - -/** - * Retries an async operation with exponential backoff (M13-T05). - * `shouldRetry` decides whether an error is transient. - */ -export async function withRetry( - operation, - { retries = 2, baseDelayMs = 500, shouldRetry = () => true } = {}, -) { - for (let attempt = 0; ; attempt += 1) { - try { - return await operation(attempt); - } catch (error) { - if (attempt >= retries || !shouldRetry(error)) throw error; - await sleep(baseDelayMs * 2 ** attempt); - } - } -} +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** + * Retries an async operation with exponential backoff (M13-T05). + * `shouldRetry` decides whether an error is transient. + */ +export async function withRetry( + operation, + { retries = 2, baseDelayMs = 500, shouldRetry = () => true } = {}, +) { + for (let attempt = 0; ; attempt += 1) { + try { + return await operation(attempt); + } catch (error) { + if (attempt >= retries || !shouldRetry(error)) throw error; + await sleep(baseDelayMs * 2 ** attempt); + } + } +} diff --git a/src/webhooks/gitea-webhook.js b/src/webhooks/gitea-webhook.js index 5f6a634..12dd1bc 100644 --- a/src/webhooks/gitea-webhook.js +++ b/src/webhooks/gitea-webhook.js @@ -1,69 +1,69 @@ -import { createHmac, timingSafeEqual } from 'node:crypto'; -import { env } from '../config/env.js'; -import { createLogger } from '../core/logger.js'; -import { getDatabase } from '../database/index.js'; -import { logEvent } from '../database/repositories/event-log-repository.js'; -import { buildGiteaNotification } from '../services/notifications/gitea-notifications.js'; -import { notify } from '../services/notifications/notification-service.js'; - -const log = createLogger('webhooks'); - -export function isValidSignature(rawBody, signature, secret = env.webhook.secret) { - if (!secret || !signature) return false; - const expected = Buffer.from(createHmac('sha256', secret).update(rawBody).digest('hex')); - const received = Buffer.from(signature); - return expected.length === received.length && timingSafeEqual(expected, received); -} - -/** Returns true the first time a delivery id is seen (M9-T08). */ -function markDelivered(deliveryId, event) { - const result = getDatabase() - .prepare('INSERT OR IGNORE INTO webhook_deliveries (delivery_id, event) VALUES (?, ?)') - .run(deliveryId, event); - return result.changes > 0; -} - -/** Validates, deduplicates and publishes a Gitea webhook. Returns the HTTP status code. */ -export async function handleGiteaWebhook(client, headers, rawBody) { - if (!isValidSignature(rawBody, headers['x-gitea-signature'])) { - log.warn('Rejected webhook with invalid signature'); - return 401; - } - - const event = headers['x-gitea-event']; - const deliveryId = headers['x-gitea-delivery']; - if (!event || !deliveryId) return 400; - if (!markDelivered(deliveryId, event)) return 200; - - let payload; - try { - payload = JSON.parse(rawBody.toString('utf8')); - } catch { - log.warn('Rejected webhook with invalid JSON body', { deliveryId, event }); - return 400; - } - - log.info(`Received Gitea event ${event}`, { - deliveryId, - repository: payload.repository?.full_name, - }); - - const notification = buildGiteaNotification(event, payload); - if (!notification) { - log.debug(`No notification mapping for Gitea event ${event}`); - return 202; - } - - logEvent({ - guildId: env.discord.guildId || null, - type: `gitea.${event}`, - payload: { deliveryId, type: notification.type }, - }); - - await notify(client, notification.type, { - embeds: [notification.embed], - content: payload.repository?.full_name ? `**${payload.repository.full_name}**` : undefined, - }).catch((error) => log.error('Could not publish the Gitea notification', error)); - - return 202; -} +import { createHmac, timingSafeEqual } from 'node:crypto'; +import { env } from '../config/env.js'; +import { createLogger } from '../core/logger.js'; +import { getDatabase } from '../database/index.js'; +import { logEvent } from '../database/repositories/event-log-repository.js'; +import { buildGiteaNotification } from '../services/notifications/gitea-notifications.js'; +import { notify } from '../services/notifications/notification-service.js'; + +const log = createLogger('webhooks'); + +export function isValidSignature(rawBody, signature, secret = env.webhook.secret) { + if (!secret || !signature) return false; + const expected = Buffer.from(createHmac('sha256', secret).update(rawBody).digest('hex')); + const received = Buffer.from(signature); + return expected.length === received.length && timingSafeEqual(expected, received); +} + +/** Returns true the first time a delivery id is seen (M9-T08). */ +function markDelivered(deliveryId, event) { + const result = getDatabase() + .prepare('INSERT OR IGNORE INTO webhook_deliveries (delivery_id, event) VALUES (?, ?)') + .run(deliveryId, event); + return result.changes > 0; +} + +/** Validates, deduplicates and publishes a Gitea webhook. Returns the HTTP status code. */ +export async function handleGiteaWebhook(client, headers, rawBody) { + if (!isValidSignature(rawBody, headers['x-gitea-signature'])) { + log.warn('Rejected webhook with invalid signature'); + return 401; + } + + const event = headers['x-gitea-event']; + const deliveryId = headers['x-gitea-delivery']; + if (!event || !deliveryId) return 400; + if (!markDelivered(deliveryId, event)) return 200; + + let payload; + try { + payload = JSON.parse(rawBody.toString('utf8')); + } catch { + log.warn('Rejected webhook with invalid JSON body', { deliveryId, event }); + return 400; + } + + log.info(`Received Gitea event ${event}`, { + deliveryId, + repository: payload.repository?.full_name, + }); + + const notification = buildGiteaNotification(event, payload); + if (!notification) { + log.debug(`No notification mapping for Gitea event ${event}`); + return 202; + } + + logEvent({ + guildId: env.discord.guildId || null, + type: `gitea.${event}`, + payload: { deliveryId, type: notification.type }, + }); + + await notify(client, notification.type, { + embeds: [notification.embed], + content: payload.repository?.full_name ? `**${payload.repository.full_name}**` : undefined, + }).catch((error) => log.error('Could not publish the Gitea notification', error)); + + return 202; +} diff --git a/src/webhooks/server.js b/src/webhooks/server.js index 353d033..8b33a12 100644 --- a/src/webhooks/server.js +++ b/src/webhooks/server.js @@ -1,49 +1,49 @@ -import { createServer } from 'node:http'; -import { env } from '../config/env.js'; -import { createLogger } from '../core/logger.js'; -import { handleGiteaWebhook } from './gitea-webhook.js'; - -const log = createLogger('webhooks'); -const MAX_BODY_BYTES = 1024 * 1024; - -function readBody(request) { - return new Promise((resolve, reject) => { - const chunks = []; - let size = 0; - request.on('data', (chunk) => { - size += chunk.length; - if (size > MAX_BODY_BYTES) { - reject(new Error('Payload too large')); - request.destroy(); - return; - } - chunks.push(chunk); - }); - request.on('end', () => resolve(Buffer.concat(chunks))); - request.on('error', reject); - }); -} - -/** HTTP server receiving Gitea webhook events (M9-T02). */ -export function startWebhookServer(client) { - const server = createServer(async (request, response) => { - if (request.method !== 'POST' || request.url !== env.webhook.path) { - response.writeHead(404).end(); - return; - } - - try { - const rawBody = await readBody(request); - const status = await handleGiteaWebhook(client, request.headers, rawBody); - response.writeHead(status).end(); - } catch (error) { - log.error('Webhook handling failed', error); - response.writeHead(500).end(); - } - }); - - server.listen(env.webhook.port, env.webhook.host, () => { - log.info(`Webhook server listening on ${env.webhook.host}:${env.webhook.port}${env.webhook.path}`); - }); - return server; -} +import { createServer } from 'node:http'; +import { env } from '../config/env.js'; +import { createLogger } from '../core/logger.js'; +import { handleGiteaWebhook } from './gitea-webhook.js'; + +const log = createLogger('webhooks'); +const MAX_BODY_BYTES = 1024 * 1024; + +function readBody(request) { + return new Promise((resolve, reject) => { + const chunks = []; + let size = 0; + request.on('data', (chunk) => { + size += chunk.length; + if (size > MAX_BODY_BYTES) { + reject(new Error('Payload too large')); + request.destroy(); + return; + } + chunks.push(chunk); + }); + request.on('end', () => resolve(Buffer.concat(chunks))); + request.on('error', reject); + }); +} + +/** HTTP server receiving Gitea webhook events (M9-T02). */ +export function startWebhookServer(client) { + const server = createServer(async (request, response) => { + if (request.method !== 'POST' || request.url !== env.webhook.path) { + response.writeHead(404).end(); + return; + } + + try { + const rawBody = await readBody(request); + const status = await handleGiteaWebhook(client, request.headers, rawBody); + response.writeHead(status).end(); + } catch (error) { + log.error('Webhook handling failed', error); + response.writeHead(500).end(); + } + }); + + server.listen(env.webhook.port, env.webhook.host, () => { + log.info(`Webhook server listening on ${env.webhook.host}:${env.webhook.port}${env.webhook.path}`); + }); + return server; +} diff --git a/tests/bot-status.test.js b/tests/bot-status.test.js index 891fbb0..17abaf5 100644 --- a/tests/bot-status.test.js +++ b/tests/bot-status.test.js @@ -1,222 +1,222 @@ -import assert from 'node:assert/strict'; -import { after, before, beforeEach, describe, it } from 'node:test'; -import { UserFacingError } from '../src/core/errors.js'; -import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; -import { - addBotStatus as addRow, - countBotStatuses, - getBotStatus, - listBotStatuses, - listEnabledBotStatuses, - removeBotStatus, - setBotStatusEnabled, -} from '../src/database/repositories/bot-status-repository.js'; -import { setSetting } from '../src/database/repositories/settings-repository.js'; -import { - addBotStatus, - applyStatusIfAlone, - clampRotation, - clearBotStatusList, - FALLBACK_STATUS, - formatSeconds, - getRotationSeconds, - normalizeStatusType, - ROTATION_KEY, - ROTATION_MAX_SECONDS, - ROTATION_MIN_SECONDS, - rotateBotStatus, - sanitizeStatusText, - saveRotationSeconds, - selectNextStatus, - STATUS_MAX, - STATUS_TEXT_MAX, - statusListEmbed, - toggleBotStatus, - validateStatusUrl, -} from '../src/services/status/bot-status-service.js'; - -const GUILD = 'g'; - -describe('bot status repository', () => { - before(() => initDatabase(':memory:')); - after(() => closeDatabase()); - beforeEach(() => getDatabase().exec('DELETE FROM bot_statuses')); - - it('stores a status and reads it back', () => { - const status = addRow({ text: 'les commandes avec /help', type: 'watching', createdBy: 'u1' }); - assert.equal(status.text, 'les commandes avec /help'); - assert.equal(status.type, 'watching'); - assert.equal(status.enabled, 1); - assert.equal(status.created_by, 'u1'); - assert.equal(getBotStatus(status.id).text, status.text); - assert.equal(countBotStatuses(), 1); - }); - - it('keeps the insertion order and separates the paused ones', () => { - const first = addRow({ text: 'un' }); - addRow({ text: 'deux' }); - const third = addRow({ text: 'trois' }); - setBotStatusEnabled(third.id, false); - - assert.deepEqual( - listBotStatuses().map((status) => status.text), - ['un', 'deux', 'trois'], - ); - assert.deepEqual( - listEnabledBotStatuses().map((status) => status.text), - ['un', 'deux'], - ); - assert.equal(first.id < third.id, true); - }); - - it('refuses the same text twice and forgets a removed status', () => { - const status = addRow({ text: 'déjà là' }); - assert.throws(() => addRow({ text: 'déjà là' }), /UNIQUE constraint/i); - - assert.equal(removeBotStatus(status.id), 1); - assert.equal(getBotStatus(status.id), null); - assert.equal(removeBotStatus(status.id), 0); - }); -}); - -describe('bot status helpers', () => { - it('normalises the text and refuses what Discord would reject', () => { - assert.equal(sanitizeStatusText(' les tickets '), 'les tickets'); - assert.equal(sanitizeStatusText('a\nb'), 'a b'); - assert.equal(sanitizeStatusText('x'.repeat(STATUS_TEXT_MAX)).length, STATUS_TEXT_MAX); - assert.throws(() => sanitizeStatusText(' '), UserFacingError); - assert.throws(() => sanitizeStatusText('x'.repeat(STATUS_TEXT_MAX + 1)), UserFacingError); - }); - - it('accepts the known types and explains the others', () => { - assert.equal(normalizeStatusType(), 'watching'); - assert.equal(normalizeStatusType('PLAYING'), 'playing'); - assert.throws(() => normalizeStatusType('danse'), UserFacingError); - }); - - it('requires a link for a stream and validates the ones it gets', () => { - assert.throws(() => validateStatusUrl(null, 'streaming'), UserFacingError); - assert.throws(() => validateStatusUrl('twitch.tv/fws', 'streaming'), UserFacingError); - assert.equal(validateStatusUrl('https://twitch.tv/fws', 'streaming'), 'https://twitch.tv/fws'); - assert.equal(validateStatusUrl(null, 'watching'), null); - assert.equal(validateStatusUrl('https://exemple.fr', 'playing'), 'https://exemple.fr'); - }); - - it('formats a delay the way the embeds show it', () => { - assert.equal(formatSeconds(30), '30 s'); - assert.equal(formatSeconds(60), '1 min'); - assert.equal(formatSeconds(3600), '1 h'); - assert.equal(formatSeconds(9000), '2 h 30 min'); - }); -}); - -describe('bot status rotation', () => { - before(() => initDatabase(':memory:')); - after(() => closeDatabase()); - beforeEach(() => { - getDatabase().exec('DELETE FROM bot_statuses'); - getDatabase().exec(`DELETE FROM guild_settings WHERE key = '${ROTATION_KEY}'`); - }); - - const client = () => { - const presences = []; - return { presences, user: { setPresence: (payload) => presences.push(payload) } }; - }; - - it('walks the enabled statuses one after the other, then starts over', () => { - const first = addBotStatus({ text: 'un' }); - const second = addBotStatus({ text: 'deux' }); - const third = addBotStatus({ text: 'trois', type: 'listening' }); - setBotStatusEnabled(third.id, false); - - const statuses = listEnabledBotStatuses(); - assert.equal(selectNextStatus(statuses).id, first.id); - assert.equal(selectNextStatus(statuses, first.id).id, second.id); - assert.equal(selectNextStatus(statuses, second.id).id, first.id); - assert.equal(selectNextStatus([]), null); - }); - - it('shows the statuses in Discord with the right activity type', () => { - addBotStatus({ text: 'les tickets', type: 'listening' }); - addBotStatus({ text: 'en direct', type: 'streaming', url: 'https://twitch.tv/fws' }); - const fake = client(); - - const first = rotateBotStatus(fake); - const second = rotateBotStatus(fake, first.id); - - assert.deepEqual(fake.presences[0].activities[0], { name: 'les tickets', type: 2 }); - assert.equal(fake.presences[1].activities[0].url, 'https://twitch.tv/fws'); - assert.equal(second.id !== first.id, true); - }); - - it('falls back to the default line instead of showing nothing', () => { - const fake = client(); - assert.equal(rotateBotStatus(fake), FALLBACK_STATUS); - assert.equal(fake.presences[0].activities[0].name, FALLBACK_STATUS.text); - }); - - it('shows a lone status right away', () => { - const status = addBotStatus({ text: 'seul statut' }); - const fake = client(); - assert.equal(applyStatusIfAlone(fake).id, status.id); - - addBotStatus({ text: 'un autre' }); - assert.equal(applyStatusIfAlone(fake), null, 'with several statuses the rotation decides'); - }); - - it('refuses the same text twice and stops at the maximum', () => { - addBotStatus({ text: 'unique' }); - assert.throws(() => addBotStatus({ text: 'unique' }), UserFacingError); - - for (let index = countBotStatuses(); index < STATUS_MAX; index += 1) { - addBotStatus({ text: `statut ${index}` }); - } - assert.equal(countBotStatuses(), STATUS_MAX); - assert.throws(() => addBotStatus({ text: 'un de trop' }), UserFacingError); - }); - - it('pauses and resumes a status without losing it', () => { - const status = addBotStatus({ text: 'en pause' }); - const paused = toggleBotStatus(status.id, false); - assert.equal(paused.enabled, 0); - assert.equal(listEnabledBotStatuses().length, 0); - assert.throws(() => toggleBotStatus(status.id, false), UserFacingError); - - toggleBotStatus(status.id, true); - assert.equal(listEnabledBotStatuses()[0].id, status.id); - assert.throws(() => toggleBotStatus(999, true), UserFacingError); - }); - - it('empties the list and forgets every status', () => { - addBotStatus({ text: 'un' }); - addBotStatus({ text: 'deux' }); - assert.equal(clearBotStatusList(), 2); - assert.equal(countBotStatuses(), 0); - assert.equal(clearBotStatusList(), 0); - }); - - it('keeps the rotation delay between the allowed bounds, database first', () => { - assert.equal(clampRotation(30), 30); - assert.equal(clampRotation(ROTATION_MIN_SECONDS - 1), 60, 'an unusable value falls back to the default'); - assert.equal(clampRotation(ROTATION_MAX_SECONDS + 1), 60); - assert.throws(() => clampRotation(1, { strict: true }), UserFacingError); - - saveRotationSeconds(45, GUILD, 'u1'); - assert.equal(getRotationSeconds(GUILD), 45); - - setSetting(GUILD, ROTATION_KEY, 'pas un nombre', 'u1'); - assert.equal(getRotationSeconds(GUILD), 60, 'a corrupted setting never breaks the rotation'); - assert.equal(getRotationSeconds('autre-serveur'), 60); - }); - - it('lists the statuses with their state and the current rhythm', () => { - const empty = statusListEmbed({ guildId: GUILD, statuses: [] }); - assert.match(empty.data.description, /Aucun statut personnalisé/); - - const status = addBotStatus({ text: 'les commandes avec /help' }); - const embed = statusListEmbed({ guildId: GUILD, statuses: listBotStatuses() }); - assert.match(embed.data.description, /\*\*1\*\* statut\(s\), dont \*\*1\*\* en rotation/); - assert.equal(embed.data.fields[0].name, `#${status.id} · ✅ en rotation`); - assert.match(embed.data.fields[0].value, /les commandes avec \/help/); - }); -}); +import assert from 'node:assert/strict'; +import { after, before, beforeEach, describe, it } from 'node:test'; +import { UserFacingError } from '../src/core/errors.js'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { + addBotStatus as addRow, + countBotStatuses, + getBotStatus, + listBotStatuses, + listEnabledBotStatuses, + removeBotStatus, + setBotStatusEnabled, +} from '../src/database/repositories/bot-status-repository.js'; +import { setSetting } from '../src/database/repositories/settings-repository.js'; +import { + addBotStatus, + applyStatusIfAlone, + clampRotation, + clearBotStatusList, + FALLBACK_STATUS, + formatSeconds, + getRotationSeconds, + normalizeStatusType, + ROTATION_KEY, + ROTATION_MAX_SECONDS, + ROTATION_MIN_SECONDS, + rotateBotStatus, + sanitizeStatusText, + saveRotationSeconds, + selectNextStatus, + STATUS_MAX, + STATUS_TEXT_MAX, + statusListEmbed, + toggleBotStatus, + validateStatusUrl, +} from '../src/services/status/bot-status-service.js'; + +const GUILD = 'g'; + +describe('bot status repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM bot_statuses')); + + it('stores a status and reads it back', () => { + const status = addRow({ text: 'les commandes avec /help', type: 'watching', createdBy: 'u1' }); + assert.equal(status.text, 'les commandes avec /help'); + assert.equal(status.type, 'watching'); + assert.equal(status.enabled, 1); + assert.equal(status.created_by, 'u1'); + assert.equal(getBotStatus(status.id).text, status.text); + assert.equal(countBotStatuses(), 1); + }); + + it('keeps the insertion order and separates the paused ones', () => { + const first = addRow({ text: 'un' }); + addRow({ text: 'deux' }); + const third = addRow({ text: 'trois' }); + setBotStatusEnabled(third.id, false); + + assert.deepEqual( + listBotStatuses().map((status) => status.text), + ['un', 'deux', 'trois'], + ); + assert.deepEqual( + listEnabledBotStatuses().map((status) => status.text), + ['un', 'deux'], + ); + assert.equal(first.id < third.id, true); + }); + + it('refuses the same text twice and forgets a removed status', () => { + const status = addRow({ text: 'déjà là' }); + assert.throws(() => addRow({ text: 'déjà là' }), /UNIQUE constraint/i); + + assert.equal(removeBotStatus(status.id), 1); + assert.equal(getBotStatus(status.id), null); + assert.equal(removeBotStatus(status.id), 0); + }); +}); + +describe('bot status helpers', () => { + it('normalises the text and refuses what Discord would reject', () => { + assert.equal(sanitizeStatusText(' les tickets '), 'les tickets'); + assert.equal(sanitizeStatusText('a\nb'), 'a b'); + assert.equal(sanitizeStatusText('x'.repeat(STATUS_TEXT_MAX)).length, STATUS_TEXT_MAX); + assert.throws(() => sanitizeStatusText(' '), UserFacingError); + assert.throws(() => sanitizeStatusText('x'.repeat(STATUS_TEXT_MAX + 1)), UserFacingError); + }); + + it('accepts the known types and explains the others', () => { + assert.equal(normalizeStatusType(), 'watching'); + assert.equal(normalizeStatusType('PLAYING'), 'playing'); + assert.throws(() => normalizeStatusType('danse'), UserFacingError); + }); + + it('requires a link for a stream and validates the ones it gets', () => { + assert.throws(() => validateStatusUrl(null, 'streaming'), UserFacingError); + assert.throws(() => validateStatusUrl('twitch.tv/fws', 'streaming'), UserFacingError); + assert.equal(validateStatusUrl('https://twitch.tv/fws', 'streaming'), 'https://twitch.tv/fws'); + assert.equal(validateStatusUrl(null, 'watching'), null); + assert.equal(validateStatusUrl('https://exemple.fr', 'playing'), 'https://exemple.fr'); + }); + + it('formats a delay the way the embeds show it', () => { + assert.equal(formatSeconds(30), '30 s'); + assert.equal(formatSeconds(60), '1 min'); + assert.equal(formatSeconds(3600), '1 h'); + assert.equal(formatSeconds(9000), '2 h 30 min'); + }); +}); + +describe('bot status rotation', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => { + getDatabase().exec('DELETE FROM bot_statuses'); + getDatabase().exec(`DELETE FROM guild_settings WHERE key = '${ROTATION_KEY}'`); + }); + + const client = () => { + const presences = []; + return { presences, user: { setPresence: (payload) => presences.push(payload) } }; + }; + + it('walks the enabled statuses one after the other, then starts over', () => { + const first = addBotStatus({ text: 'un' }); + const second = addBotStatus({ text: 'deux' }); + const third = addBotStatus({ text: 'trois', type: 'listening' }); + setBotStatusEnabled(third.id, false); + + const statuses = listEnabledBotStatuses(); + assert.equal(selectNextStatus(statuses).id, first.id); + assert.equal(selectNextStatus(statuses, first.id).id, second.id); + assert.equal(selectNextStatus(statuses, second.id).id, first.id); + assert.equal(selectNextStatus([]), null); + }); + + it('shows the statuses in Discord with the right activity type', () => { + addBotStatus({ text: 'les tickets', type: 'listening' }); + addBotStatus({ text: 'en direct', type: 'streaming', url: 'https://twitch.tv/fws' }); + const fake = client(); + + const first = rotateBotStatus(fake); + const second = rotateBotStatus(fake, first.id); + + assert.deepEqual(fake.presences[0].activities[0], { name: 'les tickets', type: 2 }); + assert.equal(fake.presences[1].activities[0].url, 'https://twitch.tv/fws'); + assert.equal(second.id !== first.id, true); + }); + + it('falls back to the default line instead of showing nothing', () => { + const fake = client(); + assert.equal(rotateBotStatus(fake), FALLBACK_STATUS); + assert.equal(fake.presences[0].activities[0].name, FALLBACK_STATUS.text); + }); + + it('shows a lone status right away', () => { + const status = addBotStatus({ text: 'seul statut' }); + const fake = client(); + assert.equal(applyStatusIfAlone(fake).id, status.id); + + addBotStatus({ text: 'un autre' }); + assert.equal(applyStatusIfAlone(fake), null, 'with several statuses the rotation decides'); + }); + + it('refuses the same text twice and stops at the maximum', () => { + addBotStatus({ text: 'unique' }); + assert.throws(() => addBotStatus({ text: 'unique' }), UserFacingError); + + for (let index = countBotStatuses(); index < STATUS_MAX; index += 1) { + addBotStatus({ text: `statut ${index}` }); + } + assert.equal(countBotStatuses(), STATUS_MAX); + assert.throws(() => addBotStatus({ text: 'un de trop' }), UserFacingError); + }); + + it('pauses and resumes a status without losing it', () => { + const status = addBotStatus({ text: 'en pause' }); + const paused = toggleBotStatus(status.id, false); + assert.equal(paused.enabled, 0); + assert.equal(listEnabledBotStatuses().length, 0); + assert.throws(() => toggleBotStatus(status.id, false), UserFacingError); + + toggleBotStatus(status.id, true); + assert.equal(listEnabledBotStatuses()[0].id, status.id); + assert.throws(() => toggleBotStatus(999, true), UserFacingError); + }); + + it('empties the list and forgets every status', () => { + addBotStatus({ text: 'un' }); + addBotStatus({ text: 'deux' }); + assert.equal(clearBotStatusList(), 2); + assert.equal(countBotStatuses(), 0); + assert.equal(clearBotStatusList(), 0); + }); + + it('keeps the rotation delay between the allowed bounds, database first', () => { + assert.equal(clampRotation(30), 30); + assert.equal(clampRotation(ROTATION_MIN_SECONDS - 1), 60, 'an unusable value falls back to the default'); + assert.equal(clampRotation(ROTATION_MAX_SECONDS + 1), 60); + assert.throws(() => clampRotation(1, { strict: true }), UserFacingError); + + saveRotationSeconds(45, GUILD, 'u1'); + assert.equal(getRotationSeconds(GUILD), 45); + + setSetting(GUILD, ROTATION_KEY, 'pas un nombre', 'u1'); + assert.equal(getRotationSeconds(GUILD), 60, 'a corrupted setting never breaks the rotation'); + assert.equal(getRotationSeconds('autre-serveur'), 60); + }); + + it('lists the statuses with their state and the current rhythm', () => { + const empty = statusListEmbed({ guildId: GUILD, statuses: [] }); + assert.match(empty.data.description, /Aucun statut personnalisé/); + + const status = addBotStatus({ text: 'les commandes avec /help' }); + const embed = statusListEmbed({ guildId: GUILD, statuses: listBotStatuses() }); + assert.match(embed.data.description, /\*\*1\*\* statut\(s\), dont \*\*1\*\* en rotation/); + assert.equal(embed.data.fields[0].name, `#${status.id} · ✅ en rotation`); + assert.match(embed.data.fields[0].value, /les commandes avec \/help/); + }); +}); diff --git a/tests/database.test.js b/tests/database.test.js index 6f796ad..da39f42 100644 --- a/tests/database.test.js +++ b/tests/database.test.js @@ -1,32 +1,32 @@ -import assert from 'node:assert/strict'; -import { after, before, describe, it } from 'node:test'; -import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; -import { getSetting, setSetting } from '../src/database/repositories/settings-repository.js'; - -describe('database', () => { - before(() => initDatabase(':memory:')); - after(() => closeDatabase()); - - it('applies the initial migration', () => { - const tables = getDatabase() - .prepare("SELECT name FROM sqlite_master WHERE type = 'table'") - .all() - .map((row) => row.name); - assert.ok(tables.includes('tickets')); - assert.ok(tables.includes('guild_settings')); - }); - - it('isolates settings per guild', () => { - setSetting('guild-a', 'welcome', { enabled: true }); - assert.deepEqual(getSetting('guild-a', 'welcome'), { enabled: true }); - assert.equal(getSetting('guild-b', 'welcome'), null); - }); - - it('prevents two open tickets for the same author and category', () => { - const insert = getDatabase().prepare( - "INSERT INTO tickets (guild_id, category_id, author_id) VALUES ('g', 'bug', 'u')", - ); - insert.run(); - assert.throws(() => insert.run(), /UNIQUE/); - }); -}); +import assert from 'node:assert/strict'; +import { after, before, describe, it } from 'node:test'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { getSetting, setSetting } from '../src/database/repositories/settings-repository.js'; + +describe('database', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + + it('applies the initial migration', () => { + const tables = getDatabase() + .prepare("SELECT name FROM sqlite_master WHERE type = 'table'") + .all() + .map((row) => row.name); + assert.ok(tables.includes('tickets')); + assert.ok(tables.includes('guild_settings')); + }); + + it('isolates settings per guild', () => { + setSetting('guild-a', 'welcome', { enabled: true }); + assert.deepEqual(getSetting('guild-a', 'welcome'), { enabled: true }); + assert.equal(getSetting('guild-b', 'welcome'), null); + }); + + it('prevents two open tickets for the same author and category', () => { + const insert = getDatabase().prepare( + "INSERT INTO tickets (guild_id, category_id, author_id) VALUES ('g', 'bug', 'u')", + ); + insert.run(); + assert.throws(() => insert.run(), /UNIQUE/); + }); +}); diff --git a/tests/docs.test.js b/tests/docs.test.js index 478ed80..616e786 100644 --- a/tests/docs.test.js +++ b/tests/docs.test.js @@ -1,50 +1,50 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import { describe, it } from 'node:test'; - -const read = (file) => readFileSync(new URL(`../${file}`, import.meta.url), 'utf8'); - -const headingCount = (text, level) => (text.match(new RegExp(`^${'#'.repeat(level)} `, 'gm')) ?? []).length; -const commandNames = (text) => new Set([...text.matchAll(/`\/([a-z]+)/g)].map((match) => match[1])); -const envTokens = (text) => new Set(text.match(/\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b/g) ?? []); - -/** The organisation requires both READMEs, kept in sync (`.profile/README.md`). */ -describe('bilingual documentation', () => { - it('keeps README.md and README.en.md structurally in sync', () => { - const fr = read('README.md'); - const en = read('README.en.md'); - - assert.equal(headingCount(en, 2), headingCount(fr, 2), 'a section is missing on one side'); - assert.equal(headingCount(en, 3), headingCount(fr, 3), 'a subsection is missing on one side'); - }); - - it('documents the same commands and environment variables in both languages', () => { - const fr = read('README.md'); - const en = read('README.en.md'); - - assert.deepEqual([...commandNames(en)].sort(), [...commandNames(fr)].sort(), 'command list differs'); - assert.deepEqual([...envTokens(en)].sort(), [...envTokens(fr)].sort(), 'environment list differs'); - }); - - it('links the two versions to each other', () => { - assert.match(read('README.md'), /README\.en\.md/, 'the French README does not link the English one'); - assert.match(read('README.en.md'), /README\.md/, 'the English README does not link the French one'); - }); - - it('ships the organisation files', () => { - assert.match(read('CHANGELOG.md'), /^# Changelog/, 'the generated changelog is missing'); - assert.match(read('AGENTS.md'), /Instructions pour les agents/, 'the agent instructions are missing'); - assert.match( - read('.gitea/PULL_REQUEST_TEMPLATE.md'), - /Conventional Commits/, - 'the pull request template is missing', - ); - assert.match( - read('.gitea/ISSUE_TEMPLATE/bug.md'), - /Étapes de reproduction/, - 'the bug report template is missing', - ); - assert.match(read('.gitignore'), /^\.env$/m, 'the environment files are not ignored'); - assert.match(read('.gitignore'), /^\.freebuff\/$/m, 'the assistant data is not ignored'); - }); -}); +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { describe, it } from 'node:test'; + +const read = (file) => readFileSync(new URL(`../${file}`, import.meta.url), 'utf8'); + +const headingCount = (text, level) => (text.match(new RegExp(`^${'#'.repeat(level)} `, 'gm')) ?? []).length; +const commandNames = (text) => new Set([...text.matchAll(/`\/([a-z]+)/g)].map((match) => match[1])); +const envTokens = (text) => new Set(text.match(/\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b/g) ?? []); + +/** The organisation requires both READMEs, kept in sync (`.profile/README.md`). */ +describe('bilingual documentation', () => { + it('keeps README.md and README.en.md structurally in sync', () => { + const fr = read('README.md'); + const en = read('README.en.md'); + + assert.equal(headingCount(en, 2), headingCount(fr, 2), 'a section is missing on one side'); + assert.equal(headingCount(en, 3), headingCount(fr, 3), 'a subsection is missing on one side'); + }); + + it('documents the same commands and environment variables in both languages', () => { + const fr = read('README.md'); + const en = read('README.en.md'); + + assert.deepEqual([...commandNames(en)].sort(), [...commandNames(fr)].sort(), 'command list differs'); + assert.deepEqual([...envTokens(en)].sort(), [...envTokens(fr)].sort(), 'environment list differs'); + }); + + it('links the two versions to each other', () => { + assert.match(read('README.md'), /README\.en\.md/, 'the French README does not link the English one'); + assert.match(read('README.en.md'), /README\.md/, 'the English README does not link the French one'); + }); + + it('ships the organisation files', () => { + assert.match(read('CHANGELOG.md'), /^# Changelog/, 'the generated changelog is missing'); + assert.match(read('AGENTS.md'), /Instructions pour les agents/, 'the agent instructions are missing'); + assert.match( + read('.gitea/PULL_REQUEST_TEMPLATE.md'), + /Conventional Commits/, + 'the pull request template is missing', + ); + assert.match( + read('.gitea/ISSUE_TEMPLATE/bug.md'), + /Étapes de reproduction/, + 'the bug report template is missing', + ); + assert.match(read('.gitignore'), /^\.env$/m, 'the environment files are not ignored'); + assert.match(read('.gitignore'), /^\.freebuff\/$/m, 'the assistant data is not ignored'); + }); +}); diff --git a/tests/modules.test.js b/tests/modules.test.js index 092f2ce..3070455 100644 --- a/tests/modules.test.js +++ b/tests/modules.test.js @@ -1,108 +1,108 @@ -import assert from 'node:assert/strict'; -import { createHmac } from 'node:crypto'; -import { readdir } from 'node:fs/promises'; -import { describe, it } from 'node:test'; -import { ACCESS_LEVELS } from '../src/config/constants.js'; -import { loadCommands } from '../src/core/command-loader.js'; - -const eventsDir = new URL('../src/events/', import.meta.url); - -describe('command modules', () => { - it('exposes data, a valid access level and an execute function', async () => { - const commands = await loadCommands(); - assert.ok(commands.length >= 16, `only ${commands.length} commands loaded`); - - for (const command of commands) { - const json = command.data.toJSON(); - assert.ok(json.name, 'a command has no name'); - assert.ok(json.description, `/${json.name} has no description`); - assert.equal(typeof command.execute, 'function', `/${json.name} has no execute()`); - assert.ok( - Object.values(ACCESS_LEVELS).includes(command.access), - `/${json.name} has an unknown access level`, - ); - } - }); - - it('uses unique command names', async () => { - const names = (await loadCommands()).map((command) => command.data.name); - assert.equal(new Set(names).size, names.length); - }); - - it('only overrides the access of declared subcommands', async () => { - /** Top-level subcommands and those nested in a subcommand group (M14). */ - const subcommandNames = (options = []) => - options.flatMap((option) => - option.type === 1 ? [option.name] : option.type === 2 ? subcommandNames(option.options) : [], - ); - - for (const command of await loadCommands()) { - if (!command.subcommandAccess) continue; - const subcommands = subcommandNames(command.data.toJSON().options); - for (const name of Object.keys(command.subcommandAccess)) { - assert.ok(subcommands.includes(name), `/${command.data.name} ${name} is not a subcommand`); - } - } - }); -}); - -describe('message tone', () => { - it('builds every embed with the shared titles, marker and hint', async () => { - const { TONE, bullets, errorEmbed, successEmbed, warningEmbed, withHint } = - await import('../src/ui/embeds.js'); - - assert.equal(successEmbed('x').data.title, TONE.success); - assert.equal(errorEmbed('x').data.title, TONE.error); - assert.equal(warningEmbed('x').data.title, TONE.warning); - assert.equal(bullets(['a', 'b', '']), '• a\n• b'); - assert.equal(withHint('fait', 'ensuite'), 'fait\n\nensuite'); - assert.equal(withHint('fait', null), 'fait'); - }); - - it('keeps command descriptions free of gendered wording', async () => { - /** Words that would address or describe a person with a gender. */ - const gendered = - /\b(utilisateur|utilisatrice|cher|chère|ravi|ravie|content|contente|bienvenu|bienvenue à (lui|elle))/i; - - for (const command of await loadCommands()) { - const json = command.data.toJSON(); - const texts = [json.description, ...(json.options ?? []).map((option) => option.description ?? '')]; - for (const text of texts) { - assert.ok(!gendered.test(text), `/${json.name} uses gendered wording: ${text}`); - } - } - }); -}); - -describe('webhook entry points', () => { - it('exposes the server and the dispatch functions', async () => { - const server = await import('../src/webhooks/server.js'); - const webhook = await import('../src/webhooks/gitea-webhook.js'); - assert.equal(typeof server.startWebhookServer, 'function'); - assert.equal(typeof webhook.handleGiteaWebhook, 'function'); - }); - - it('accepts only a valid HMAC signature and refuses an empty secret', async () => { - const { isValidSignature } = await import('../src/webhooks/gitea-webhook.js'); - const body = Buffer.from('{"action":"opened"}'); - const signature = createHmac('sha256', 'secret').update(body).digest('hex'); - - assert.equal(isValidSignature(body, signature, 'secret'), true); - assert.equal(isValidSignature(body, 'deadbeef', 'secret'), false); - assert.equal(isValidSignature(body, signature, ''), false); - assert.equal(isValidSignature(body, undefined, 'secret'), false); - }); -}); - -describe('event modules', () => { - it('exports a name and a handler', async () => { - const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js')); - assert.ok(files.length >= 6, `only ${files.length} event files found`); - - for (const file of files) { - const event = await import(new URL(file, eventsDir).href); - assert.equal(typeof event.name, 'string', `${file} has no name`); - assert.equal(typeof event.execute, 'function', `${file} has no execute()`); - } - }); -}); +import assert from 'node:assert/strict'; +import { createHmac } from 'node:crypto'; +import { readdir } from 'node:fs/promises'; +import { describe, it } from 'node:test'; +import { ACCESS_LEVELS } from '../src/config/constants.js'; +import { loadCommands } from '../src/core/command-loader.js'; + +const eventsDir = new URL('../src/events/', import.meta.url); + +describe('command modules', () => { + it('exposes data, a valid access level and an execute function', async () => { + const commands = await loadCommands(); + assert.ok(commands.length >= 16, `only ${commands.length} commands loaded`); + + for (const command of commands) { + const json = command.data.toJSON(); + assert.ok(json.name, 'a command has no name'); + assert.ok(json.description, `/${json.name} has no description`); + assert.equal(typeof command.execute, 'function', `/${json.name} has no execute()`); + assert.ok( + Object.values(ACCESS_LEVELS).includes(command.access), + `/${json.name} has an unknown access level`, + ); + } + }); + + it('uses unique command names', async () => { + const names = (await loadCommands()).map((command) => command.data.name); + assert.equal(new Set(names).size, names.length); + }); + + it('only overrides the access of declared subcommands', async () => { + /** Top-level subcommands and those nested in a subcommand group (M14). */ + const subcommandNames = (options = []) => + options.flatMap((option) => + option.type === 1 ? [option.name] : option.type === 2 ? subcommandNames(option.options) : [], + ); + + for (const command of await loadCommands()) { + if (!command.subcommandAccess) continue; + const subcommands = subcommandNames(command.data.toJSON().options); + for (const name of Object.keys(command.subcommandAccess)) { + assert.ok(subcommands.includes(name), `/${command.data.name} ${name} is not a subcommand`); + } + } + }); +}); + +describe('message tone', () => { + it('builds every embed with the shared titles, marker and hint', async () => { + const { TONE, bullets, errorEmbed, successEmbed, warningEmbed, withHint } = + await import('../src/ui/embeds.js'); + + assert.equal(successEmbed('x').data.title, TONE.success); + assert.equal(errorEmbed('x').data.title, TONE.error); + assert.equal(warningEmbed('x').data.title, TONE.warning); + assert.equal(bullets(['a', 'b', '']), '• a\n• b'); + assert.equal(withHint('fait', 'ensuite'), 'fait\n\nensuite'); + assert.equal(withHint('fait', null), 'fait'); + }); + + it('keeps command descriptions free of gendered wording', async () => { + /** Words that would address or describe a person with a gender. */ + const gendered = + /\b(utilisateur|utilisatrice|cher|chère|ravi|ravie|content|contente|bienvenu|bienvenue à (lui|elle))/i; + + for (const command of await loadCommands()) { + const json = command.data.toJSON(); + const texts = [json.description, ...(json.options ?? []).map((option) => option.description ?? '')]; + for (const text of texts) { + assert.ok(!gendered.test(text), `/${json.name} uses gendered wording: ${text}`); + } + } + }); +}); + +describe('webhook entry points', () => { + it('exposes the server and the dispatch functions', async () => { + const server = await import('../src/webhooks/server.js'); + const webhook = await import('../src/webhooks/gitea-webhook.js'); + assert.equal(typeof server.startWebhookServer, 'function'); + assert.equal(typeof webhook.handleGiteaWebhook, 'function'); + }); + + it('accepts only a valid HMAC signature and refuses an empty secret', async () => { + const { isValidSignature } = await import('../src/webhooks/gitea-webhook.js'); + const body = Buffer.from('{"action":"opened"}'); + const signature = createHmac('sha256', 'secret').update(body).digest('hex'); + + assert.equal(isValidSignature(body, signature, 'secret'), true); + assert.equal(isValidSignature(body, 'deadbeef', 'secret'), false); + assert.equal(isValidSignature(body, signature, ''), false); + assert.equal(isValidSignature(body, undefined, 'secret'), false); + }); +}); + +describe('event modules', () => { + it('exports a name and a handler', async () => { + const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js')); + assert.ok(files.length >= 6, `only ${files.length} event files found`); + + for (const file of files) { + const event = await import(new URL(file, eventsDir).href); + assert.equal(typeof event.name, 'string', `${file} has no name`); + assert.equal(typeof event.execute, 'function', `${file} has no execute()`); + } + }); +}); diff --git a/tests/notifications.test.js b/tests/notifications.test.js index ed7c292..15d4fcf 100644 --- a/tests/notifications.test.js +++ b/tests/notifications.test.js @@ -1,88 +1,88 @@ -import assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; -import { buildGiteaNotification } from '../src/services/notifications/gitea-notifications.js'; -import { releaseEmbed, truncate } from '../src/services/gitea/gitea-embeds.js'; - -const issue = { - number: 12, - title: 'Le lecteur ne démarre pas', - body: 'Depuis la mise à jour.', - state: 'open', - comments: 3, - user: { login: 'alice' }, - html_url: 'https://gitea.example/FWS/FWS-Arch/issues/12', - labels: [{ name: 'bug' }], -}; - -describe('buildGiteaNotification', () => { - it('maps an issue event to the issues channel', () => { - const notification = buildGiteaNotification('issues', { issue }); - assert.equal(notification.type, 'issues'); - assert.equal(notification.embed.data.title, '#12 Le lecteur ne démarre pas'); - assert.equal(notification.embed.data.url, issue.html_url); - }); - - it('maps a pull request to its own type', () => { - const notification = buildGiteaNotification('pull_request', { - pull_request: { - number: 4, - title: 'Corrige le démarrage', - state: 'open', - user: { login: 'bob' }, - head: { ref: 'fix/boot' }, - base: { ref: 'main' }, - }, - }); - assert.equal(notification.type, 'pull_request'); - assert.match(notification.embed.data.fields[2].value, /fix\/boot → main/); - }); - - it('reports a release with its tag', () => { - const notification = buildGiteaNotification('release', { - release: { tag_name: 'v1.2.0', name: 'Version 1.2.0', body: 'Nouveautés' }, - }); - assert.equal(notification.type, 'release'); - assert.equal(notification.embed.data.title, 'Version 1.2.0'); - }); - - it('ignores a push without commits', () => { - assert.equal(buildGiteaNotification('push', { commits: [], ref: 'refs/heads/main' }), null); - }); - - it('summarises the commits of a push', () => { - const notification = buildGiteaNotification('push', { - ref: 'refs/heads/main', - sender: { login: 'carol' }, - commits: [{ id: 'abcdef1234567', message: 'fix: boot\n\nDétails' }], - }); - assert.equal(notification.type, 'push'); - assert.equal(notification.embed.data.title, 'Push sur main'); - assert.match(notification.embed.data.description, /`abcdef1` fix: boot/); - }); - - it('ignores events without a notification type', () => { - assert.equal(buildGiteaNotification('repository', { repository: {} }), null); - }); -}); - -describe('releaseEmbed', () => { - it('keeps the notes by default and can drop them', () => { - const release = { - tag_name: 'v2.0.0', - name: 'v2.0.0', - body: 'Changements', - published_at: '2026-01-01T10:00:00Z', - }; - assert.equal(releaseEmbed(release).data.description, 'Changements'); - assert.equal(releaseEmbed(release, { withNotes: false }).data.description, undefined); - }); -}); - -describe('truncate', () => { - it('keeps short text and cuts long text', () => { - assert.equal(truncate('court'), 'court'); - assert.equal(truncate('', 10), ''); - assert.equal(truncate('ab'.repeat(20), 10).length, 10); - assert.match(truncate('ab'.repeat(20), 10), /…$/); - }); -}); +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { buildGiteaNotification } from '../src/services/notifications/gitea-notifications.js'; +import { releaseEmbed, truncate } from '../src/services/gitea/gitea-embeds.js'; + +const issue = { + number: 12, + title: 'Le lecteur ne démarre pas', + body: 'Depuis la mise à jour.', + state: 'open', + comments: 3, + user: { login: 'alice' }, + html_url: 'https://gitea.example/FWS/FWS-Arch/issues/12', + labels: [{ name: 'bug' }], +}; + +describe('buildGiteaNotification', () => { + it('maps an issue event to the issues channel', () => { + const notification = buildGiteaNotification('issues', { issue }); + assert.equal(notification.type, 'issues'); + assert.equal(notification.embed.data.title, '#12 Le lecteur ne démarre pas'); + assert.equal(notification.embed.data.url, issue.html_url); + }); + + it('maps a pull request to its own type', () => { + const notification = buildGiteaNotification('pull_request', { + pull_request: { + number: 4, + title: 'Corrige le démarrage', + state: 'open', + user: { login: 'bob' }, + head: { ref: 'fix/boot' }, + base: { ref: 'main' }, + }, + }); + assert.equal(notification.type, 'pull_request'); + assert.match(notification.embed.data.fields[2].value, /fix\/boot → main/); + }); + + it('reports a release with its tag', () => { + const notification = buildGiteaNotification('release', { + release: { tag_name: 'v1.2.0', name: 'Version 1.2.0', body: 'Nouveautés' }, + }); + assert.equal(notification.type, 'release'); + assert.equal(notification.embed.data.title, 'Version 1.2.0'); + }); + + it('ignores a push without commits', () => { + assert.equal(buildGiteaNotification('push', { commits: [], ref: 'refs/heads/main' }), null); + }); + + it('summarises the commits of a push', () => { + const notification = buildGiteaNotification('push', { + ref: 'refs/heads/main', + sender: { login: 'carol' }, + commits: [{ id: 'abcdef1234567', message: 'fix: boot\n\nDétails' }], + }); + assert.equal(notification.type, 'push'); + assert.equal(notification.embed.data.title, 'Push sur main'); + assert.match(notification.embed.data.description, /`abcdef1` fix: boot/); + }); + + it('ignores events without a notification type', () => { + assert.equal(buildGiteaNotification('repository', { repository: {} }), null); + }); +}); + +describe('releaseEmbed', () => { + it('keeps the notes by default and can drop them', () => { + const release = { + tag_name: 'v2.0.0', + name: 'v2.0.0', + body: 'Changements', + published_at: '2026-01-01T10:00:00Z', + }; + assert.equal(releaseEmbed(release).data.description, 'Changements'); + assert.equal(releaseEmbed(release, { withNotes: false }).data.description, undefined); + }); +}); + +describe('truncate', () => { + it('keeps short text and cuts long text', () => { + assert.equal(truncate('court'), 'court'); + assert.equal(truncate('', 10), ''); + assert.equal(truncate('ab'.repeat(20), 10).length, 10); + assert.match(truncate('ab'.repeat(20), 10), /…$/); + }); +}); diff --git a/tests/pending-actions.test.js b/tests/pending-actions.test.js index c0d4ea4..2675b88 100644 --- a/tests/pending-actions.test.js +++ b/tests/pending-actions.test.js @@ -1,33 +1,33 @@ -import assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; -import { consume, pendingCount, purgeExpired, remember } from '../src/services/gitea/pending-actions.js'; - -describe('pending actions', () => { - it('returns a stored value exactly once', () => { - remember('pr:1', { head: 'feature', base: 'main' }); - assert.deepEqual(consume('pr:1'), { head: 'feature', base: 'main' }); - assert.equal(consume('pr:1'), null); - }); - - it('returns null for an unknown key', () => { - assert.equal(consume('pr:unknown'), null); - }); - - it('drops an expired entry', () => { - const start = 1_000; - remember('pr:2', 'value', { ttlMs: 500, now: start }); - assert.equal(consume('pr:2', { now: start + 501 }), null); - }); - - it('keeps a value still within its window', () => { - remember('pr:3', 'value', { ttlMs: 500, now: 0 }); - assert.equal(consume('pr:3', { now: 499 }), 'value'); - }); - - it('purges expired entries without touching fresh ones', () => { - remember('pr:4', 'old', { ttlMs: 10, now: 0 }); - remember('pr:5', 'fresh', { ttlMs: 10_000, now: 0 }); - assert.equal(purgeExpired(100), 1); - assert.equal(pendingCount(), 1); - }); -}); +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { consume, pendingCount, purgeExpired, remember } from '../src/services/gitea/pending-actions.js'; + +describe('pending actions', () => { + it('returns a stored value exactly once', () => { + remember('pr:1', { head: 'feature', base: 'main' }); + assert.deepEqual(consume('pr:1'), { head: 'feature', base: 'main' }); + assert.equal(consume('pr:1'), null); + }); + + it('returns null for an unknown key', () => { + assert.equal(consume('pr:unknown'), null); + }); + + it('drops an expired entry', () => { + const start = 1_000; + remember('pr:2', 'value', { ttlMs: 500, now: start }); + assert.equal(consume('pr:2', { now: start + 501 }), null); + }); + + it('keeps a value still within its window', () => { + remember('pr:3', 'value', { ttlMs: 500, now: 0 }); + assert.equal(consume('pr:3', { now: 499 }), 'value'); + }); + + it('purges expired entries without touching fresh ones', () => { + remember('pr:4', 'old', { ttlMs: 10, now: 0 }); + remember('pr:5', 'fresh', { ttlMs: 10_000, now: 0 }); + assert.equal(purgeExpired(100), 1); + assert.equal(pendingCount(), 1); + }); +}); diff --git a/tests/permissions.test.js b/tests/permissions.test.js index c820ecf..3744e75 100644 --- a/tests/permissions.test.js +++ b/tests/permissions.test.js @@ -1,40 +1,40 @@ -import assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; -import { ACCESS_LEVELS } from '../src/config/constants.js'; -import { getAccessLevel, hasAccess } from '../src/core/permissions.js'; - -const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff', member: 'r-member' }; - -const fakeMember = (roleIds, { id = 'u1', ownerId = 'someone-else' } = {}) => ({ - id, - guild: { ownerId }, - roles: { cache: new Set(roleIds) }, -}); - -describe('getAccessLevel', () => { - it('returns USER for a member without FWS roles', () => { - assert.equal(getAccessLevel(fakeMember(['r-member']), roles), ACCESS_LEVELS.USER); - }); - - it('returns the highest level when a member has several roles', () => { - assert.equal(getAccessLevel(fakeMember(['r-staff', 'r-dev']), roles), ACCESS_LEVELS.DEV); - }); - - it('returns OWNER for the guild owner', () => { - assert.equal(getAccessLevel(fakeMember([], { id: 'u1', ownerId: 'u1' }), roles), ACCESS_LEVELS.OWNER); - }); - - it('ignores unconfigured role ids', () => { - assert.equal(getAccessLevel(fakeMember(['']), { owner: '', dev: '', staff: '' }), ACCESS_LEVELS.USER); - }); -}); - -describe('hasAccess', () => { - it('denies a staff command to a regular user', () => { - assert.equal(hasAccess(fakeMember([]), ACCESS_LEVELS.STAFF, roles), false); - }); - - it('allows a staff command to an owner', () => { - assert.equal(hasAccess(fakeMember(['r-owner']), ACCESS_LEVELS.STAFF, roles), true); - }); -}); +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { ACCESS_LEVELS } from '../src/config/constants.js'; +import { getAccessLevel, hasAccess } from '../src/core/permissions.js'; + +const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff', member: 'r-member' }; + +const fakeMember = (roleIds, { id = 'u1', ownerId = 'someone-else' } = {}) => ({ + id, + guild: { ownerId }, + roles: { cache: new Set(roleIds) }, +}); + +describe('getAccessLevel', () => { + it('returns USER for a member without FWS roles', () => { + assert.equal(getAccessLevel(fakeMember(['r-member']), roles), ACCESS_LEVELS.USER); + }); + + it('returns the highest level when a member has several roles', () => { + assert.equal(getAccessLevel(fakeMember(['r-staff', 'r-dev']), roles), ACCESS_LEVELS.DEV); + }); + + it('returns OWNER for the guild owner', () => { + assert.equal(getAccessLevel(fakeMember([], { id: 'u1', ownerId: 'u1' }), roles), ACCESS_LEVELS.OWNER); + }); + + it('ignores unconfigured role ids', () => { + assert.equal(getAccessLevel(fakeMember(['']), { owner: '', dev: '', staff: '' }), ACCESS_LEVELS.USER); + }); +}); + +describe('hasAccess', () => { + it('denies a staff command to a regular user', () => { + assert.equal(hasAccess(fakeMember([]), ACCESS_LEVELS.STAFF, roles), false); + }); + + it('allows a staff command to an owner', () => { + assert.equal(hasAccess(fakeMember(['r-owner']), ACCESS_LEVELS.STAFF, roles), true); + }); +}); diff --git a/tests/poll-service.test.js b/tests/poll-service.test.js index 3d1ea56..4907e3f 100644 --- a/tests/poll-service.test.js +++ b/tests/poll-service.test.js @@ -1,80 +1,80 @@ -import assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; -import { formatDuration } from '../src/services/moderation/moderation-service.js'; -import { buildPollEmbed, parseChoices, toSqliteDate } from '../src/services/polls/poll-service.js'; - -describe('parseChoices', () => { - it('splits, trims and keeps the order', () => { - assert.deepEqual(parseChoices('Oui ; Non; Peut-être '), ['Oui', 'Non', 'Peut-être']); - }); - - it('rejects a single choice', () => { - assert.throws(() => parseChoices('Oui'), /entre 2 et 10 propositions/); - }); - - it('rejects duplicated choices regardless of case', () => { - assert.throws(() => parseChoices('Oui;oui'), /Deux propositions identiques/); - }); - - it('rejects more choices than allowed', () => { - assert.throws(() => parseChoices(Array.from({ length: 11 }, (_v, i) => i).join(';')), /entre 2 et 10/); - }); -}); - -describe('toSqliteDate', () => { - it('formats a UTC datetime the way SQLite stores it', () => { - assert.equal(toSqliteDate(new Date('2026-03-04T05:06:07.890Z')), '2026-03-04 05:06:07'); - }); -}); - -describe('buildPollEmbed', () => { - const poll = { - id: 3, - creator_id: 'u1', - question: 'Quel thème ?', - choices: JSON.stringify(['Clair', 'Sombre']), - status: 'open', - ends_at: null, - }; - - it('reports the totals and the percentage of each choice', () => { - const embed = buildPollEmbed(poll, [ - { choice_index: 0, count: 3 }, - { choice_index: 1, count: 1 }, - ]); - assert.equal(embed.data.title, '📊 Sondage #3 — Quel thème ?'); - assert.match(embed.data.description, /Clair/); - assert.match(embed.data.description, /3 \(75 %\)/); - assert.equal(embed.data.fields[0].value, '4'); - }); - - it('handles a poll without any vote', () => { - const embed = buildPollEmbed(poll, []); - assert.match(embed.data.description, /0 \(0 %\)/); - assert.equal(embed.data.fields[0].value, '0'); - }); - - it('announces the winning choice once closed', () => { - const closed = { ...poll, status: 'closed' }; - const embed = buildPollEmbed(closed, [ - { choice_index: 0, count: 1 }, - { choice_index: 1, count: 5 }, - ]); - assert.equal(embed.data.fields.at(-1).value, '**Sombre** (5 vote(s))'); - }); - - it('says so when a closed poll has no vote', () => { - const embed = buildPollEmbed({ ...poll, status: 'closed' }, []); - assert.equal(embed.data.fields.at(-1).value, 'Aucun vote'); - }); -}); - -describe('formatDuration', () => { - it('formats minutes, hours and days', () => { - assert.equal(formatDuration(30 * 60_000), '30 min'); - assert.equal(formatDuration(60 * 60_000), '1 h'); - assert.equal(formatDuration(150 * 60_000), '2 h 30 min'); - assert.equal(formatDuration(24 * 60 * 60_000), '1 j'); - assert.equal(formatDuration(30 * 60 * 60_000), '1 j 6 h'); - }); -}); +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { formatDuration } from '../src/services/moderation/moderation-service.js'; +import { buildPollEmbed, parseChoices, toSqliteDate } from '../src/services/polls/poll-service.js'; + +describe('parseChoices', () => { + it('splits, trims and keeps the order', () => { + assert.deepEqual(parseChoices('Oui ; Non; Peut-être '), ['Oui', 'Non', 'Peut-être']); + }); + + it('rejects a single choice', () => { + assert.throws(() => parseChoices('Oui'), /entre 2 et 10 propositions/); + }); + + it('rejects duplicated choices regardless of case', () => { + assert.throws(() => parseChoices('Oui;oui'), /Deux propositions identiques/); + }); + + it('rejects more choices than allowed', () => { + assert.throws(() => parseChoices(Array.from({ length: 11 }, (_v, i) => i).join(';')), /entre 2 et 10/); + }); +}); + +describe('toSqliteDate', () => { + it('formats a UTC datetime the way SQLite stores it', () => { + assert.equal(toSqliteDate(new Date('2026-03-04T05:06:07.890Z')), '2026-03-04 05:06:07'); + }); +}); + +describe('buildPollEmbed', () => { + const poll = { + id: 3, + creator_id: 'u1', + question: 'Quel thème ?', + choices: JSON.stringify(['Clair', 'Sombre']), + status: 'open', + ends_at: null, + }; + + it('reports the totals and the percentage of each choice', () => { + const embed = buildPollEmbed(poll, [ + { choice_index: 0, count: 3 }, + { choice_index: 1, count: 1 }, + ]); + assert.equal(embed.data.title, '📊 Sondage #3 — Quel thème ?'); + assert.match(embed.data.description, /Clair/); + assert.match(embed.data.description, /3 \(75 %\)/); + assert.equal(embed.data.fields[0].value, '4'); + }); + + it('handles a poll without any vote', () => { + const embed = buildPollEmbed(poll, []); + assert.match(embed.data.description, /0 \(0 %\)/); + assert.equal(embed.data.fields[0].value, '0'); + }); + + it('announces the winning choice once closed', () => { + const closed = { ...poll, status: 'closed' }; + const embed = buildPollEmbed(closed, [ + { choice_index: 0, count: 1 }, + { choice_index: 1, count: 5 }, + ]); + assert.equal(embed.data.fields.at(-1).value, '**Sombre** (5 vote(s))'); + }); + + it('says so when a closed poll has no vote', () => { + const embed = buildPollEmbed({ ...poll, status: 'closed' }, []); + assert.equal(embed.data.fields.at(-1).value, 'Aucun vote'); + }); +}); + +describe('formatDuration', () => { + it('formats minutes, hours and days', () => { + assert.equal(formatDuration(30 * 60_000), '30 min'); + assert.equal(formatDuration(60 * 60_000), '1 h'); + assert.equal(formatDuration(150 * 60_000), '2 h 30 min'); + assert.equal(formatDuration(24 * 60 * 60_000), '1 j'); + assert.equal(formatDuration(30 * 60 * 60_000), '1 j 6 h'); + }); +}); diff --git a/tests/repositories.test.js b/tests/repositories.test.js index 1accca9..4088d18 100644 --- a/tests/repositories.test.js +++ b/tests/repositories.test.js @@ -1,189 +1,189 @@ -import assert from 'node:assert/strict'; -import { after, before, beforeEach, describe, it } from 'node:test'; -import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; -import { - countActions, - listActions, - recordAction, -} from '../src/database/repositories/moderation-repository.js'; -import { - getNotificationChannel, - removeNotificationChannel, - setNotificationChannel, -} from '../src/database/repositories/notification-repository.js'; -import { - castVote, - closePoll, - countVotes, - createPoll, - listDuePolls, -} from '../src/database/repositories/poll-repository.js'; -import { - claimTicket, - closeTicket, - countOpenTickets, - createTicket, - getOpenTicket, - getTicketByChannel, -} from '../src/database/repositories/ticket-repository.js'; - -const reset = () => - getDatabase().exec( - 'DELETE FROM tickets; DELETE FROM moderation_actions; DELETE FROM polls; DELETE FROM poll_votes; DELETE FROM notification_channels;', - ); - -describe('ticket repository', () => { - before(() => initDatabase(':memory:')); - after(() => closeDatabase()); - beforeEach(reset); - - const openTicket = () => createTicket({ guildId: 'g', channelId: 'c1', categoryId: 'bug', authorId: 'u1' }); - - it('creates a ticket and finds it by channel', () => { - const id = openTicket(); - const ticket = getTicketByChannel('c1'); - assert.equal(ticket.id, id); - assert.equal(ticket.status, 'open'); - assert.equal(ticket.claimed_by, null); - }); - - it('refuses a second open ticket for the same author and category', () => { - openTicket(); - assert.throws( - () => createTicket({ guildId: 'g', channelId: 'c2', categoryId: 'bug', authorId: 'u1' }), - /UNIQUE/, - ); - assert.equal(getOpenTicket({ guildId: 'g', authorId: 'u1', categoryId: 'bug' }).channel_id, 'c1'); - }); - - it('allows a new ticket once the previous one is closed', () => { - const id = openTicket(); - closeTicket(id, { closedBy: 'staff', reason: 'résolu' }); - const newId = createTicket({ guildId: 'g', channelId: 'c3', categoryId: 'bug', authorId: 'u1' }); - assert.notEqual(newId, id); - assert.equal(countOpenTickets('g'), 1); - }); - - it('records who claimed and closed a ticket', () => { - const id = openTicket(); - assert.equal(claimTicket(id, 'staff'), 1); - assert.equal(getTicketByChannel('c1').claimed_by, 'staff'); - - assert.equal(closeTicket(id, { closedBy: 'staff', reason: 'ok' }), 1); - const closed = getTicketByChannel('c1'); - assert.equal(closed.status, 'closed'); - assert.equal(closed.close_reason, 'ok'); - assert.ok(closed.closed_at); - }); - - it('cannot close a ticket twice', () => { - const id = openTicket(); - closeTicket(id, { closedBy: 'staff' }); - assert.equal(closeTicket(id, { closedBy: 'staff' }), 0); - }); -}); - -describe('moderation repository', () => { - before(() => initDatabase(':memory:')); - after(() => closeDatabase()); - beforeEach(reset); - - it('records and lists actions of a target', () => { - recordAction({ guildId: 'g', action: 'warn', moderatorId: 'm1', targetId: 'u1', reason: 'spam' }); - recordAction({ guildId: 'g', action: 'warn', moderatorId: 'm1', targetId: 'u1', reason: 'again' }); - recordAction({ guildId: 'g', action: 'kick', moderatorId: 'm2', targetId: 'u2' }); - - assert.equal(countActions({ guildId: 'g', targetId: 'u1', action: 'warn' }), 2); - const history = listActions({ guildId: 'g', targetId: 'u1' }); - assert.equal(history.length, 2); - assert.equal(history[0].reason, 'again'); - - assert.equal(listActions({ guildId: 'g', action: 'kick' }).length, 1); - }); - - it('keeps the duration of a mute', () => { - recordAction({ - guildId: 'g', - action: 'mute', - moderatorId: 'm1', - targetId: 'u1', - durationMs: 60_000, - }); - assert.equal(listActions({ guildId: 'g', targetId: 'u1' })[0].duration_ms, 60_000); - }); -}); - -describe('poll repository', () => { - before(() => initDatabase(':memory:')); - after(() => closeDatabase()); - beforeEach(reset); - - const poll = () => - createPoll({ - guildId: 'g', - channelId: 'c', - creatorId: 'u1', - question: 'Question ?', - choices: ['a', 'b'], - endsAt: null, - }); - - it('counts one vote per user and allows a change of mind', () => { - const id = poll(); - assert.equal(castVote(id, 'u1', 0), 'created'); - assert.equal(castVote(id, 'u1', 0), 'unchanged'); - assert.equal(castVote(id, 'u1', 1), 'changed'); - assert.equal(castVote(id, 'u2', 1), 'created'); - - const counts = countVotes(id); - assert.equal(counts.length, 1); - assert.deepEqual({ ...counts[0] }, { choice_index: 1, count: 2 }); - }); - - it('lists only the polls whose end date has passed', () => { - const due = createPoll({ - guildId: 'g', - channelId: 'c', - creatorId: 'u1', - question: 'Bientôt fini', - choices: ['a', 'b'], - endsAt: '2000-01-01 00:00:00', - }); - createPoll({ - guildId: 'g', - channelId: 'c', - creatorId: 'u1', - question: 'En cours', - choices: ['a', 'b'], - endsAt: '2999-01-01 00:00:00', - }); - - const ids = listDuePolls().map((row) => row.id); - assert.deepEqual(ids, [due]); - }); - - it('closes a poll only once', () => { - const id = poll(); - assert.equal(closePoll(id), 1); - assert.equal(closePoll(id), 0); - }); -}); - -describe('notification repository', () => { - before(() => initDatabase(':memory:')); - after(() => closeDatabase()); - beforeEach(reset); - - it('stores one channel per type and replaces it', () => { - setNotificationChannel({ guildId: 'g', type: 'issues', channelId: 'c1' }); - setNotificationChannel({ guildId: 'g', type: 'issues', channelId: 'c2' }); - assert.equal(getNotificationChannel('g', 'issues').channel_id, 'c2'); - assert.equal(getNotificationChannel('other', 'issues'), null); - }); - - it('removes an override and reports it', () => { - setNotificationChannel({ guildId: 'g', type: 'release', channelId: 'c1' }); - assert.equal(removeNotificationChannel('g', 'release'), 1); - assert.equal(removeNotificationChannel('g', 'release'), 0); - }); -}); +import assert from 'node:assert/strict'; +import { after, before, beforeEach, describe, it } from 'node:test'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { + countActions, + listActions, + recordAction, +} from '../src/database/repositories/moderation-repository.js'; +import { + getNotificationChannel, + removeNotificationChannel, + setNotificationChannel, +} from '../src/database/repositories/notification-repository.js'; +import { + castVote, + closePoll, + countVotes, + createPoll, + listDuePolls, +} from '../src/database/repositories/poll-repository.js'; +import { + claimTicket, + closeTicket, + countOpenTickets, + createTicket, + getOpenTicket, + getTicketByChannel, +} from '../src/database/repositories/ticket-repository.js'; + +const reset = () => + getDatabase().exec( + 'DELETE FROM tickets; DELETE FROM moderation_actions; DELETE FROM polls; DELETE FROM poll_votes; DELETE FROM notification_channels;', + ); + +describe('ticket repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(reset); + + const openTicket = () => createTicket({ guildId: 'g', channelId: 'c1', categoryId: 'bug', authorId: 'u1' }); + + it('creates a ticket and finds it by channel', () => { + const id = openTicket(); + const ticket = getTicketByChannel('c1'); + assert.equal(ticket.id, id); + assert.equal(ticket.status, 'open'); + assert.equal(ticket.claimed_by, null); + }); + + it('refuses a second open ticket for the same author and category', () => { + openTicket(); + assert.throws( + () => createTicket({ guildId: 'g', channelId: 'c2', categoryId: 'bug', authorId: 'u1' }), + /UNIQUE/, + ); + assert.equal(getOpenTicket({ guildId: 'g', authorId: 'u1', categoryId: 'bug' }).channel_id, 'c1'); + }); + + it('allows a new ticket once the previous one is closed', () => { + const id = openTicket(); + closeTicket(id, { closedBy: 'staff', reason: 'résolu' }); + const newId = createTicket({ guildId: 'g', channelId: 'c3', categoryId: 'bug', authorId: 'u1' }); + assert.notEqual(newId, id); + assert.equal(countOpenTickets('g'), 1); + }); + + it('records who claimed and closed a ticket', () => { + const id = openTicket(); + assert.equal(claimTicket(id, 'staff'), 1); + assert.equal(getTicketByChannel('c1').claimed_by, 'staff'); + + assert.equal(closeTicket(id, { closedBy: 'staff', reason: 'ok' }), 1); + const closed = getTicketByChannel('c1'); + assert.equal(closed.status, 'closed'); + assert.equal(closed.close_reason, 'ok'); + assert.ok(closed.closed_at); + }); + + it('cannot close a ticket twice', () => { + const id = openTicket(); + closeTicket(id, { closedBy: 'staff' }); + assert.equal(closeTicket(id, { closedBy: 'staff' }), 0); + }); +}); + +describe('moderation repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(reset); + + it('records and lists actions of a target', () => { + recordAction({ guildId: 'g', action: 'warn', moderatorId: 'm1', targetId: 'u1', reason: 'spam' }); + recordAction({ guildId: 'g', action: 'warn', moderatorId: 'm1', targetId: 'u1', reason: 'again' }); + recordAction({ guildId: 'g', action: 'kick', moderatorId: 'm2', targetId: 'u2' }); + + assert.equal(countActions({ guildId: 'g', targetId: 'u1', action: 'warn' }), 2); + const history = listActions({ guildId: 'g', targetId: 'u1' }); + assert.equal(history.length, 2); + assert.equal(history[0].reason, 'again'); + + assert.equal(listActions({ guildId: 'g', action: 'kick' }).length, 1); + }); + + it('keeps the duration of a mute', () => { + recordAction({ + guildId: 'g', + action: 'mute', + moderatorId: 'm1', + targetId: 'u1', + durationMs: 60_000, + }); + assert.equal(listActions({ guildId: 'g', targetId: 'u1' })[0].duration_ms, 60_000); + }); +}); + +describe('poll repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(reset); + + const poll = () => + createPoll({ + guildId: 'g', + channelId: 'c', + creatorId: 'u1', + question: 'Question ?', + choices: ['a', 'b'], + endsAt: null, + }); + + it('counts one vote per user and allows a change of mind', () => { + const id = poll(); + assert.equal(castVote(id, 'u1', 0), 'created'); + assert.equal(castVote(id, 'u1', 0), 'unchanged'); + assert.equal(castVote(id, 'u1', 1), 'changed'); + assert.equal(castVote(id, 'u2', 1), 'created'); + + const counts = countVotes(id); + assert.equal(counts.length, 1); + assert.deepEqual({ ...counts[0] }, { choice_index: 1, count: 2 }); + }); + + it('lists only the polls whose end date has passed', () => { + const due = createPoll({ + guildId: 'g', + channelId: 'c', + creatorId: 'u1', + question: 'Bientôt fini', + choices: ['a', 'b'], + endsAt: '2000-01-01 00:00:00', + }); + createPoll({ + guildId: 'g', + channelId: 'c', + creatorId: 'u1', + question: 'En cours', + choices: ['a', 'b'], + endsAt: '2999-01-01 00:00:00', + }); + + const ids = listDuePolls().map((row) => row.id); + assert.deepEqual(ids, [due]); + }); + + it('closes a poll only once', () => { + const id = poll(); + assert.equal(closePoll(id), 1); + assert.equal(closePoll(id), 0); + }); +}); + +describe('notification repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(reset); + + it('stores one channel per type and replaces it', () => { + setNotificationChannel({ guildId: 'g', type: 'issues', channelId: 'c1' }); + setNotificationChannel({ guildId: 'g', type: 'issues', channelId: 'c2' }); + assert.equal(getNotificationChannel('g', 'issues').channel_id, 'c2'); + assert.equal(getNotificationChannel('other', 'issues'), null); + }); + + it('removes an override and reports it', () => { + setNotificationChannel({ guildId: 'g', type: 'release', channelId: 'c1' }); + assert.equal(removeNotificationChannel('g', 'release'), 1); + assert.equal(removeNotificationChannel('g', 'release'), 0); + }); +}); diff --git a/tests/voice.test.js b/tests/voice.test.js index 8b0b37f..1a7eee0 100644 --- a/tests/voice.test.js +++ b/tests/voice.test.js @@ -1,530 +1,530 @@ -import assert from 'node:assert/strict'; -import { after, before, beforeEach, describe, it } from 'node:test'; -import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; -import { - addVoiceChannel, - countVoiceChannels, - countVoiceChannelsByTrigger, - getVoiceChannel, - listOwnedVoiceChannels, - listVoiceChannels, - removeVoiceChannel, - setVoiceLimit, - setVoiceLocked, - setVoiceName, - setVoiceOwner, -} from '../src/database/repositories/voice-repository.js'; -import { ChannelType, Collection } from 'discord.js'; -import { PermissionDeniedError, UserFacingError } from '../src/core/errors.js'; -import { setSetting } from '../src/database/repositories/settings-repository.js'; -import { - assertVoiceOwner, - bottomPosition, - buildChannelName, - clampLimit, - cleanupVoiceChannel, - createFromTrigger, - deleteVoiceChannel, - findTrigger, - getVoiceTrigger, - getVoiceTriggers, - isStaff, - listTriggerSummaries, - removeVoiceTriggerConfig, - sanitizeChannelName, - saveVoiceTrigger, - setTriggerEnabled, - startVoiceJanitor, - sweepVoiceChannels, -} from '../src/services/voice/voice-service.js'; - -const member = (roleIds = [], { id = 'u1', guildOwnerId = 'someone-else' } = {}) => ({ - id, - guild: { ownerId: guildOwnerId }, - roles: { cache: new Set(roleIds) }, -}); - -describe('voice repository', () => { - before(() => initDatabase(':memory:')); - after(() => closeDatabase()); - beforeEach(() => getDatabase().exec('DELETE FROM voice_channels')); - - const add = (channelId, ownerId = 'u1') => - addVoiceChannel({ - channelId, - guildId: 'g', - ownerId, - triggerId: 'trigger', - name: 'Salon de u1', - userLimit: 0, - }); - - it('stores a temporary channel and reads it back', () => { - add('c1'); - const row = getVoiceChannel('c1'); - assert.equal(row.owner_id, 'u1'); - assert.equal(row.trigger_id, 'trigger'); - assert.equal(row.locked, 0); - assert.equal(row.user_limit, 0); - assert.ok(row.created_at); - }); - - it('keeps several channels per guild and per owner, without any limit', () => { - add('c1'); - add('c2'); - add('c3', 'u2'); - assert.equal(countVoiceChannels('g'), 3); - assert.equal(listVoiceChannels('g').length, 3); - assert.deepEqual( - listOwnedVoiceChannels('g', 'u1').map((row) => row.channel_id), - ['c1', 'c2'], - ); - }); - - it('updates the owner, the name, the lock and the limit', () => { - add('c1'); - setVoiceOwner('c1', 'u2'); - setVoiceName('c1', 'Nouveau nom'); - setVoiceLocked('c1', true); - setVoiceLimit('c1', 5); - - const row = getVoiceChannel('c1'); - assert.equal(row.owner_id, 'u2'); - assert.equal(row.name, 'Nouveau nom'); - assert.equal(row.locked, 1); - assert.equal(row.user_limit, 5); - }); - - it('forgets a channel once deleted', () => { - add('c1'); - assert.equal(removeVoiceChannel('c1'), 1); - assert.equal(getVoiceChannel('c1'), null); - assert.equal(removeVoiceChannel('c1'), 0); - }); - - it('counts the channels created from one trigger only', () => { - addVoiceChannel({ channelId: 'c1', guildId: 'g', ownerId: 'u1', triggerId: 'dev', name: 'd' }); - addVoiceChannel({ channelId: 'c2', guildId: 'g', ownerId: 'u2', triggerId: 'dev', name: 'd' }); - addVoiceChannel({ channelId: 'c3', guildId: 'g', ownerId: 'u3', triggerId: 'sio', name: 's' }); - - assert.equal(countVoiceChannelsByTrigger('dev'), 2); - assert.equal(countVoiceChannelsByTrigger('sio'), 1); - assert.equal(countVoiceChannelsByTrigger('unknown'), 0); - }); -}); - -describe('voice triggers', () => { - before(() => initDatabase(':memory:')); - after(() => closeDatabase()); - beforeEach(() => { - getDatabase().exec('DELETE FROM voice_triggers'); - getDatabase().exec("DELETE FROM guild_settings WHERE key LIKE 'voice.%'"); - }); - - const declared = (guildId = 'g') => - getVoiceTriggers(guildId).filter((trigger) => trigger.source === 'database'); - - it('declares several triggers, each with its own category', () => { - saveVoiceTrigger('g', { - triggerId: 'dev', - label: 'Dev', - categoryId: 'cat-dev', - template: '🛠️ Salon de {user}', - userLimit: 4, - }); - saveVoiceTrigger('g', { triggerId: 'sio', label: 'SIO', categoryId: 'cat-sio' }); - - assert.deepEqual( - declared().map((trigger) => trigger.triggerId), - ['dev', 'sio'], - ); - const dev = findTrigger('g', 'dev'); - assert.equal(dev.categoryId, 'cat-dev'); - assert.equal(dev.template, '🛠️ Salon de {user}'); - assert.equal(dev.userLimit, 4); - assert.equal(findTrigger('g', 'sio').categoryId, 'cat-sio'); - assert.equal(getVoiceTrigger('g', 'inconnu'), null); - }); - - it('keeps the stored values of the fields that are not passed again', () => { - saveVoiceTrigger('g', { triggerId: 'dev', label: 'Dev', categoryId: 'cat-dev', userLimit: 4 }); - saveVoiceTrigger('g', { triggerId: 'dev', categoryId: 'cat-2' }); - - const dev = findTrigger('g', 'dev'); - assert.equal(dev.label, 'Dev'); - assert.equal(dev.categoryId, 'cat-2'); - assert.equal(dev.template, '🔊 Salon de {user}'); - assert.equal(dev.userLimit, 4); - }); - - it('falls back to the settings written by the single-trigger version', () => { - setSetting('g', 'voice.trigger', 'legacy'); - setSetting('g', 'voice.category', 'cat-legacy'); - - const legacy = getVoiceTriggers('g').find((trigger) => trigger.triggerId === 'legacy'); - assert.equal(legacy.source, 'settings'); - assert.equal(legacy.categoryId, 'cat-legacy'); - assert.equal(legacy.enabled, true); - - saveVoiceTrigger('g', { triggerId: 'legacy', categoryId: 'cat-new' }); - const matches = getVoiceTriggers('g').filter((trigger) => trigger.triggerId === 'legacy'); - assert.equal(matches.length, 1, 'a declared trigger replaces the inherited one'); - assert.equal(matches[0].categoryId, 'cat-new'); - assert.equal(matches[0].source, 'database'); - }); - - it('can disable a trigger inherited from the settings', () => { - setSetting('g', 'voice.trigger', 'legacy'); - setTriggerEnabled('g', 'legacy', false); - - const disabled = findTrigger('g', 'legacy'); - assert.equal(disabled.enabled, false); - assert.equal(disabled.source, 'database', 'the inherited trigger is written before being disabled'); - assert.equal(getVoiceTrigger('g', 'legacy'), null); - }); - - it('switches a trigger off and back on without losing its settings', () => { - saveVoiceTrigger('g', { triggerId: 'dev', label: 'Dev', categoryId: 'cat-dev' }); - setTriggerEnabled('g', 'dev', false); - - assert.equal(findTrigger('g', 'dev').enabled, false); - assert.equal(getVoiceTrigger('g', 'dev'), null, 'a disabled trigger creates no channel'); - assert.throws(() => setTriggerEnabled('g', 'dev', false), UserFacingError); - - setTriggerEnabled('g', 'dev', true); - assert.equal(getVoiceTrigger('g', 'dev').categoryId, 'cat-dev'); - assert.throws(() => setTriggerEnabled('g', 'sio', true), UserFacingError); - }); - - it('removes a declared trigger but never an inherited one', () => { - saveVoiceTrigger('g', { triggerId: 'dev', categoryId: 'cat-dev' }); - removeVoiceTriggerConfig('g', 'dev'); - assert.equal(findTrigger('g', 'dev'), null); - assert.throws(() => removeVoiceTriggerConfig('g', 'dev'), UserFacingError); - }); - - it('reports every trigger with the channels it currently hosts', () => { - saveVoiceTrigger('g', { triggerId: 'dev', label: 'Dev', categoryId: 'cat-dev' }); - addVoiceChannel({ channelId: 'c1', guildId: 'g', ownerId: 'u1', triggerId: 'dev', name: 'd' }); - - const summary = listTriggerSummaries('g').find((trigger) => trigger.triggerId === 'dev'); - assert.equal(summary.label, 'Dev'); - assert.equal(summary.activeChannels, 1); - }); -}); - -describe('voice channel creation from a trigger', () => { - before(() => initDatabase(':memory:')); - after(() => closeDatabase()); - beforeEach(() => { - getDatabase().exec('DELETE FROM voice_triggers'); - getDatabase().exec('DELETE FROM voice_channels'); - }); - - const makeChannel = (id, { parentId = null, position = 0, type = ChannelType.GuildVoice } = {}) => ({ - id, - name: `salon-${id}`, - type, - parentId, - position, - userLimit: 0, - members: new Collection(), - guild: null, - isSendable: () => true, - isVoiceBased: () => type === ChannelType.GuildVoice, - send: async () => ({ id: `message-${id}` }), - delete: async () => true, - setPosition: async function setPosition(target) { - this.position = target; - return this; - }, - permissionOverwrites: { edit: async () => {} }, - }); - - const makeGuild = (channels) => { - const cache = new Collection(channels.map((channel) => [channel.id, channel])); - const created = []; - const guild = { - id: 'g', - roles: { everyone: { id: 'everyone' } }, - channels: { - cache, - fetch: async (id) => cache.get(id) ?? null, - create: async (options) => { - created.push(options); - const channel = makeChannel(`nouveau-${created.length}`, { - parentId: options.parent ?? null, - position: cache.size, - }); - channel.name = options.name; - channel.userLimit = options.userLimit; - channel.guild = guild; - cache.set(channel.id, channel); - return channel; - }, - }, - }; - for (const channel of cache.values()) channel.guild = guild; - return { guild, created, cache }; - }; - - const makeMember = (guild, { id = 'u1', displayName = 'Léa' } = {}) => { - const member = { - id, - displayName, - guild, - moved: [], - user: { tag: `${displayName}#0001`, username: 'lea' }, - client: { user: { id: 'bot' } }, - }; - member.voice = { - setChannel: async (channel) => { - member.moved.push(channel.id); - }, - }; - return member; - }; - - const guildWithTwoTriggers = () => { - const { guild, created, cache } = makeGuild([ - makeChannel('cat-dev', { type: ChannelType.GuildCategory }), - makeChannel('cat-sio', { type: ChannelType.GuildCategory }), - makeChannel('trig-dev', { parentId: 'cat-dev', position: 0 }), - makeChannel('trig-sio', { parentId: 'cat-sio', position: 0 }), - ]); - saveVoiceTrigger('g', { - triggerId: 'trig-dev', - label: 'Dev', - categoryId: 'cat-dev', - template: '🛠️ {user}', - userLimit: 3, - }); - saveVoiceTrigger('g', { triggerId: 'trig-sio', label: 'SIO', categoryId: 'cat-sio' }); - return { guild, created, cache }; - }; - - it('creates the channel at the bottom of the category of the trigger that was joined', async () => { - const { guild, created, cache } = guildWithTwoTriggers(); - const member = makeMember(guild); - - await createFromTrigger(member, getVoiceTrigger('g', 'trig-dev')); - - assert.equal(created.length, 1); - assert.equal(created[0].parent, 'cat-dev'); - assert.equal(created[0].name, '🛠️ Léa'); - assert.equal(created[0].userLimit, 3); - assert.equal(member.moved.at(-1), 'nouveau-1', 'the member is moved into their channel'); - - const channel = cache.get('nouveau-1'); - const siblings = [...cache.values()].filter((candidate) => candidate.parentId === 'cat-dev'); - assert.equal(siblings.length, 2, 'the trigger and the temporary channel share the category'); - assert.equal(channel.position, siblings.length - 1, 'the channel sits below the trigger'); - - const row = getVoiceChannel('nouveau-1'); - assert.equal(row.trigger_id, 'trig-dev'); - assert.equal(row.owner_id, 'u1'); - assert.equal(row.user_limit, 3); - }); - - it('keeps one channel per trigger and moves the member back into the existing one', async () => { - const { guild, created } = guildWithTwoTriggers(); - const member = makeMember(guild); - - await createFromTrigger(member, getVoiceTrigger('g', 'trig-dev')); - await createFromTrigger(member, getVoiceTrigger('g', 'trig-sio')); - - assert.equal(created.length, 2, 'another trigger gets its own channel'); - assert.equal(created[1].parent, 'cat-sio'); - assert.equal(created[1].name, '🔊 Salon de Léa'); - - await createFromTrigger(member, getVoiceTrigger('g', 'trig-dev')); - assert.equal(created.length, 2, 'no third channel for a trigger already served'); - assert.equal(member.moved.at(-1), 'nouveau-1'); - assert.equal(countVoiceChannels('g'), 2); - }); - - it('creates nothing when the channel is not an enabled trigger', async () => { - const { guild, created } = guildWithTwoTriggers(); - setTriggerEnabled('g', 'trig-dev', false); - - assert.equal(await createFromTrigger(makeMember(guild), getVoiceTrigger('g', 'trig-dev')), null); - assert.equal(await createFromTrigger(makeMember(guild, { id: 'u2' }), null), null); - assert.equal(created.length, 0); - }); -}); - -describe('empty generated channels', () => { - before(() => initDatabase(':memory:')); - after(() => closeDatabase()); - beforeEach(() => { - getDatabase().exec('DELETE FROM voice_channels'); - }); - - const track = (channelId, ownerId = 'u1', triggerId = 'dev') => - addVoiceChannel({ channelId, guildId: 'g', ownerId, triggerId, name: `salon-${channelId}` }); - - const voiceChannel = (id, { members = [] } = {}) => ({ - id, - parentId: 'cat', - members: new Collection(members.map((memberId) => [memberId, { id: memberId }])), - deleted: false, - failure: null, - async delete() { - if (this.failure) throw this.failure; - this.deleted = true; - }, - }); - - /** Guild mock whose `fetch` only knows the cached channels, like a channel deleted by hand. */ - const makeGuild = (channels) => { - const cache = new Collection(channels.map((channel) => [channel.id, channel])); - const guild = { id: 'g', channels: { cache, fetch: async (id) => cache.get(id) ?? null } }; - for (const channel of cache.values()) channel.guild = guild; - return guild; - }; - - const clientOf = (...guilds) => ({ guilds: { cache: new Collection(guilds.map((g) => [g.id, g])) } }); - - it('deletes a generated channel as soon as nobody is left in it', async () => { - track('c1'); - const channel = voiceChannel('c1'); - - await cleanupVoiceChannel(makeGuild([channel]), 'c1', { graceMs: 0 }); - - assert.equal(channel.deleted, true); - assert.equal(getVoiceChannel('c1'), null, 'the row is forgotten too'); - }); - - it('keeps a channel that still has members', async () => { - track('c1'); - const channel = voiceChannel('c1', { members: ['u2'] }); - - await cleanupVoiceChannel(makeGuild([channel]), 'c1', { graceMs: 0 }); - - assert.equal(channel.deleted, false); - assert.ok(getVoiceChannel('c1')); - }); - - it('leaves a grace period during which the owner can come back', async () => { - track('c1'); - const channel = voiceChannel('c1'); - - const pending = cleanupVoiceChannel(makeGuild([channel]), 'c1', { graceMs: 30 }); - channel.members.set('u1', { id: 'u1' }); - await pending; - await new Promise((resolve) => setTimeout(resolve, 60)); - - assert.equal(channel.deleted, false, 'the customised channel survives a quick move'); - assert.ok(getVoiceChannel('c1')); - }); - - it('deletes the empty channels and forgets the vanished ones in one sweep', async () => { - track('vide'); - track('occupe', 'u2'); - track('disparu', 'u3', 'sio'); - - const empty = voiceChannel('vide'); - const busy = voiceChannel('occupe', { members: ['u2'] }); - await sweepVoiceChannels(clientOf(makeGuild([empty, busy]))); - - assert.equal(empty.deleted, true); - assert.equal(busy.deleted, false); - assert.equal(getVoiceChannel('vide'), null); - assert.equal(getVoiceChannel('disparu'), null, 'a channel deleted by hand is forgotten'); - assert.ok(getVoiceChannel('occupe')); - }); - - it('runs that sweep on an interval', async () => { - track('c1'); - const channel = voiceChannel('c1'); - - const timer = startVoiceJanitor(clientOf(makeGuild([channel])), 20); - await new Promise((resolve) => setTimeout(resolve, 60)); - clearInterval(timer); - - assert.equal(channel.deleted, true); - assert.equal(getVoiceChannel('c1'), null); - }); - - it('keeps the row when the deletion fails, so the sweep can retry', async () => { - track('c1'); - const channel = voiceChannel('c1'); - channel.failure = Object.assign(new Error('Missing Permissions'), { code: 50013, status: 403 }); - makeGuild([channel]); - - assert.equal(await deleteVoiceChannel(channel, 'test'), false); - assert.ok(getVoiceChannel('c1'), 'the channel is not leaked'); - - channel.failure = null; - assert.equal(await deleteVoiceChannel(channel, 'test'), true); - assert.equal(getVoiceChannel('c1'), null); - }); - - it('forgets a channel that Discord has already deleted', async () => { - track('c1'); - const channel = voiceChannel('c1'); - channel.failure = Object.assign(new Error('Unknown Channel'), { code: 10003 }); - makeGuild([channel]); - - assert.equal(await deleteVoiceChannel(channel, 'test'), true); - assert.equal(getVoiceChannel('c1'), null); - }); -}); - -describe('voice helpers', () => { - it('normalises a channel name', () => { - assert.equal(sanitizeChannelName(' Salon de Léa '), 'Salon de Léa'); - assert.equal(sanitizeChannelName('a\nb'), 'a b'); - assert.equal(sanitizeChannelName('x'.repeat(150)).length, 100); - assert.throws(() => sanitizeChannelName(' '), UserFacingError); - }); - - it('builds the channel name from the template', () => { - const member = { displayName: 'Léa', user: { username: 'lea' } }; - assert.equal(buildChannelName('🔊 Salon de {user}', member), '🔊 Salon de Léa'); - assert.equal(buildChannelName('', member), '🔊 Salon de Léa'); - assert.equal(buildChannelName('{user} {user}', member), 'Léa Léa'); - assert.equal(buildChannelName(' ', member), '🔊 Salon vocal'); - }); - - it('accepts 0..99 as a user limit and rejects anything else', () => { - assert.equal(clampLimit(0), 0); - assert.equal(clampLimit(99), 99); - assert.equal(clampLimit('12'), 12); - assert.equal(clampLimit(150), 0); - assert.equal(clampLimit('abc'), 0); - assert.throws(() => clampLimit(150, { strict: true }), UserFacingError); - assert.throws(() => clampLimit(-1, { strict: true }), UserFacingError); - }); - - it('places a new channel on the last slot of its category', () => { - assert.equal(bottomPosition(0), 0); - assert.equal(bottomPosition(1), 0); - assert.equal(bottomPosition(2), 1); - assert.equal(bottomPosition(7), 6); - }); -}); - -describe('voice ownership', () => { - const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff' }; - const row = { owner_id: 'u1' }; - const context = (id, roleIds = [], overrides = {}) => ({ - user: { id }, - member: member(roleIds, { id, ...overrides }), - }); - - it('lets the owner manage their channel', () => { - assert.doesNotThrow(() => assertVoiceOwner(context('u1'), row)); - }); - - it('refuses a plain member', () => { - assert.throws(() => assertVoiceOwner(context('u2'), row), PermissionDeniedError); - }); - - it('recognises staff from the configured roles', () => { - assert.equal(isStaff(member(['r-staff']), roles), true); - assert.equal(isStaff(member(['r-dev']), roles), true); - assert.equal(isStaff(member(['r-member']), roles), false); - assert.equal(isStaff(member([], { id: 'u9', guildOwnerId: 'u9' }), roles), true); - }); -}); +import assert from 'node:assert/strict'; +import { after, before, beforeEach, describe, it } from 'node:test'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { + addVoiceChannel, + countVoiceChannels, + countVoiceChannelsByTrigger, + getVoiceChannel, + listOwnedVoiceChannels, + listVoiceChannels, + removeVoiceChannel, + setVoiceLimit, + setVoiceLocked, + setVoiceName, + setVoiceOwner, +} from '../src/database/repositories/voice-repository.js'; +import { ChannelType, Collection } from 'discord.js'; +import { PermissionDeniedError, UserFacingError } from '../src/core/errors.js'; +import { setSetting } from '../src/database/repositories/settings-repository.js'; +import { + assertVoiceOwner, + bottomPosition, + buildChannelName, + clampLimit, + cleanupVoiceChannel, + createFromTrigger, + deleteVoiceChannel, + findTrigger, + getVoiceTrigger, + getVoiceTriggers, + isStaff, + listTriggerSummaries, + removeVoiceTriggerConfig, + sanitizeChannelName, + saveVoiceTrigger, + setTriggerEnabled, + startVoiceJanitor, + sweepVoiceChannels, +} from '../src/services/voice/voice-service.js'; + +const member = (roleIds = [], { id = 'u1', guildOwnerId = 'someone-else' } = {}) => ({ + id, + guild: { ownerId: guildOwnerId }, + roles: { cache: new Set(roleIds) }, +}); + +describe('voice repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => getDatabase().exec('DELETE FROM voice_channels')); + + const add = (channelId, ownerId = 'u1') => + addVoiceChannel({ + channelId, + guildId: 'g', + ownerId, + triggerId: 'trigger', + name: 'Salon de u1', + userLimit: 0, + }); + + it('stores a temporary channel and reads it back', () => { + add('c1'); + const row = getVoiceChannel('c1'); + assert.equal(row.owner_id, 'u1'); + assert.equal(row.trigger_id, 'trigger'); + assert.equal(row.locked, 0); + assert.equal(row.user_limit, 0); + assert.ok(row.created_at); + }); + + it('keeps several channels per guild and per owner, without any limit', () => { + add('c1'); + add('c2'); + add('c3', 'u2'); + assert.equal(countVoiceChannels('g'), 3); + assert.equal(listVoiceChannels('g').length, 3); + assert.deepEqual( + listOwnedVoiceChannels('g', 'u1').map((row) => row.channel_id), + ['c1', 'c2'], + ); + }); + + it('updates the owner, the name, the lock and the limit', () => { + add('c1'); + setVoiceOwner('c1', 'u2'); + setVoiceName('c1', 'Nouveau nom'); + setVoiceLocked('c1', true); + setVoiceLimit('c1', 5); + + const row = getVoiceChannel('c1'); + assert.equal(row.owner_id, 'u2'); + assert.equal(row.name, 'Nouveau nom'); + assert.equal(row.locked, 1); + assert.equal(row.user_limit, 5); + }); + + it('forgets a channel once deleted', () => { + add('c1'); + assert.equal(removeVoiceChannel('c1'), 1); + assert.equal(getVoiceChannel('c1'), null); + assert.equal(removeVoiceChannel('c1'), 0); + }); + + it('counts the channels created from one trigger only', () => { + addVoiceChannel({ channelId: 'c1', guildId: 'g', ownerId: 'u1', triggerId: 'dev', name: 'd' }); + addVoiceChannel({ channelId: 'c2', guildId: 'g', ownerId: 'u2', triggerId: 'dev', name: 'd' }); + addVoiceChannel({ channelId: 'c3', guildId: 'g', ownerId: 'u3', triggerId: 'sio', name: 's' }); + + assert.equal(countVoiceChannelsByTrigger('dev'), 2); + assert.equal(countVoiceChannelsByTrigger('sio'), 1); + assert.equal(countVoiceChannelsByTrigger('unknown'), 0); + }); +}); + +describe('voice triggers', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => { + getDatabase().exec('DELETE FROM voice_triggers'); + getDatabase().exec("DELETE FROM guild_settings WHERE key LIKE 'voice.%'"); + }); + + const declared = (guildId = 'g') => + getVoiceTriggers(guildId).filter((trigger) => trigger.source === 'database'); + + it('declares several triggers, each with its own category', () => { + saveVoiceTrigger('g', { + triggerId: 'dev', + label: 'Dev', + categoryId: 'cat-dev', + template: '🛠️ Salon de {user}', + userLimit: 4, + }); + saveVoiceTrigger('g', { triggerId: 'sio', label: 'SIO', categoryId: 'cat-sio' }); + + assert.deepEqual( + declared().map((trigger) => trigger.triggerId), + ['dev', 'sio'], + ); + const dev = findTrigger('g', 'dev'); + assert.equal(dev.categoryId, 'cat-dev'); + assert.equal(dev.template, '🛠️ Salon de {user}'); + assert.equal(dev.userLimit, 4); + assert.equal(findTrigger('g', 'sio').categoryId, 'cat-sio'); + assert.equal(getVoiceTrigger('g', 'inconnu'), null); + }); + + it('keeps the stored values of the fields that are not passed again', () => { + saveVoiceTrigger('g', { triggerId: 'dev', label: 'Dev', categoryId: 'cat-dev', userLimit: 4 }); + saveVoiceTrigger('g', { triggerId: 'dev', categoryId: 'cat-2' }); + + const dev = findTrigger('g', 'dev'); + assert.equal(dev.label, 'Dev'); + assert.equal(dev.categoryId, 'cat-2'); + assert.equal(dev.template, '🔊 Salon de {user}'); + assert.equal(dev.userLimit, 4); + }); + + it('falls back to the settings written by the single-trigger version', () => { + setSetting('g', 'voice.trigger', 'legacy'); + setSetting('g', 'voice.category', 'cat-legacy'); + + const legacy = getVoiceTriggers('g').find((trigger) => trigger.triggerId === 'legacy'); + assert.equal(legacy.source, 'settings'); + assert.equal(legacy.categoryId, 'cat-legacy'); + assert.equal(legacy.enabled, true); + + saveVoiceTrigger('g', { triggerId: 'legacy', categoryId: 'cat-new' }); + const matches = getVoiceTriggers('g').filter((trigger) => trigger.triggerId === 'legacy'); + assert.equal(matches.length, 1, 'a declared trigger replaces the inherited one'); + assert.equal(matches[0].categoryId, 'cat-new'); + assert.equal(matches[0].source, 'database'); + }); + + it('can disable a trigger inherited from the settings', () => { + setSetting('g', 'voice.trigger', 'legacy'); + setTriggerEnabled('g', 'legacy', false); + + const disabled = findTrigger('g', 'legacy'); + assert.equal(disabled.enabled, false); + assert.equal(disabled.source, 'database', 'the inherited trigger is written before being disabled'); + assert.equal(getVoiceTrigger('g', 'legacy'), null); + }); + + it('switches a trigger off and back on without losing its settings', () => { + saveVoiceTrigger('g', { triggerId: 'dev', label: 'Dev', categoryId: 'cat-dev' }); + setTriggerEnabled('g', 'dev', false); + + assert.equal(findTrigger('g', 'dev').enabled, false); + assert.equal(getVoiceTrigger('g', 'dev'), null, 'a disabled trigger creates no channel'); + assert.throws(() => setTriggerEnabled('g', 'dev', false), UserFacingError); + + setTriggerEnabled('g', 'dev', true); + assert.equal(getVoiceTrigger('g', 'dev').categoryId, 'cat-dev'); + assert.throws(() => setTriggerEnabled('g', 'sio', true), UserFacingError); + }); + + it('removes a declared trigger but never an inherited one', () => { + saveVoiceTrigger('g', { triggerId: 'dev', categoryId: 'cat-dev' }); + removeVoiceTriggerConfig('g', 'dev'); + assert.equal(findTrigger('g', 'dev'), null); + assert.throws(() => removeVoiceTriggerConfig('g', 'dev'), UserFacingError); + }); + + it('reports every trigger with the channels it currently hosts', () => { + saveVoiceTrigger('g', { triggerId: 'dev', label: 'Dev', categoryId: 'cat-dev' }); + addVoiceChannel({ channelId: 'c1', guildId: 'g', ownerId: 'u1', triggerId: 'dev', name: 'd' }); + + const summary = listTriggerSummaries('g').find((trigger) => trigger.triggerId === 'dev'); + assert.equal(summary.label, 'Dev'); + assert.equal(summary.activeChannels, 1); + }); +}); + +describe('voice channel creation from a trigger', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => { + getDatabase().exec('DELETE FROM voice_triggers'); + getDatabase().exec('DELETE FROM voice_channels'); + }); + + const makeChannel = (id, { parentId = null, position = 0, type = ChannelType.GuildVoice } = {}) => ({ + id, + name: `salon-${id}`, + type, + parentId, + position, + userLimit: 0, + members: new Collection(), + guild: null, + isSendable: () => true, + isVoiceBased: () => type === ChannelType.GuildVoice, + send: async () => ({ id: `message-${id}` }), + delete: async () => true, + setPosition: async function setPosition(target) { + this.position = target; + return this; + }, + permissionOverwrites: { edit: async () => {} }, + }); + + const makeGuild = (channels) => { + const cache = new Collection(channels.map((channel) => [channel.id, channel])); + const created = []; + const guild = { + id: 'g', + roles: { everyone: { id: 'everyone' } }, + channels: { + cache, + fetch: async (id) => cache.get(id) ?? null, + create: async (options) => { + created.push(options); + const channel = makeChannel(`nouveau-${created.length}`, { + parentId: options.parent ?? null, + position: cache.size, + }); + channel.name = options.name; + channel.userLimit = options.userLimit; + channel.guild = guild; + cache.set(channel.id, channel); + return channel; + }, + }, + }; + for (const channel of cache.values()) channel.guild = guild; + return { guild, created, cache }; + }; + + const makeMember = (guild, { id = 'u1', displayName = 'Léa' } = {}) => { + const member = { + id, + displayName, + guild, + moved: [], + user: { tag: `${displayName}#0001`, username: 'lea' }, + client: { user: { id: 'bot' } }, + }; + member.voice = { + setChannel: async (channel) => { + member.moved.push(channel.id); + }, + }; + return member; + }; + + const guildWithTwoTriggers = () => { + const { guild, created, cache } = makeGuild([ + makeChannel('cat-dev', { type: ChannelType.GuildCategory }), + makeChannel('cat-sio', { type: ChannelType.GuildCategory }), + makeChannel('trig-dev', { parentId: 'cat-dev', position: 0 }), + makeChannel('trig-sio', { parentId: 'cat-sio', position: 0 }), + ]); + saveVoiceTrigger('g', { + triggerId: 'trig-dev', + label: 'Dev', + categoryId: 'cat-dev', + template: '🛠️ {user}', + userLimit: 3, + }); + saveVoiceTrigger('g', { triggerId: 'trig-sio', label: 'SIO', categoryId: 'cat-sio' }); + return { guild, created, cache }; + }; + + it('creates the channel at the bottom of the category of the trigger that was joined', async () => { + const { guild, created, cache } = guildWithTwoTriggers(); + const member = makeMember(guild); + + await createFromTrigger(member, getVoiceTrigger('g', 'trig-dev')); + + assert.equal(created.length, 1); + assert.equal(created[0].parent, 'cat-dev'); + assert.equal(created[0].name, '🛠️ Léa'); + assert.equal(created[0].userLimit, 3); + assert.equal(member.moved.at(-1), 'nouveau-1', 'the member is moved into their channel'); + + const channel = cache.get('nouveau-1'); + const siblings = [...cache.values()].filter((candidate) => candidate.parentId === 'cat-dev'); + assert.equal(siblings.length, 2, 'the trigger and the temporary channel share the category'); + assert.equal(channel.position, siblings.length - 1, 'the channel sits below the trigger'); + + const row = getVoiceChannel('nouveau-1'); + assert.equal(row.trigger_id, 'trig-dev'); + assert.equal(row.owner_id, 'u1'); + assert.equal(row.user_limit, 3); + }); + + it('keeps one channel per trigger and moves the member back into the existing one', async () => { + const { guild, created } = guildWithTwoTriggers(); + const member = makeMember(guild); + + await createFromTrigger(member, getVoiceTrigger('g', 'trig-dev')); + await createFromTrigger(member, getVoiceTrigger('g', 'trig-sio')); + + assert.equal(created.length, 2, 'another trigger gets its own channel'); + assert.equal(created[1].parent, 'cat-sio'); + assert.equal(created[1].name, '🔊 Salon de Léa'); + + await createFromTrigger(member, getVoiceTrigger('g', 'trig-dev')); + assert.equal(created.length, 2, 'no third channel for a trigger already served'); + assert.equal(member.moved.at(-1), 'nouveau-1'); + assert.equal(countVoiceChannels('g'), 2); + }); + + it('creates nothing when the channel is not an enabled trigger', async () => { + const { guild, created } = guildWithTwoTriggers(); + setTriggerEnabled('g', 'trig-dev', false); + + assert.equal(await createFromTrigger(makeMember(guild), getVoiceTrigger('g', 'trig-dev')), null); + assert.equal(await createFromTrigger(makeMember(guild, { id: 'u2' }), null), null); + assert.equal(created.length, 0); + }); +}); + +describe('empty generated channels', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(() => { + getDatabase().exec('DELETE FROM voice_channels'); + }); + + const track = (channelId, ownerId = 'u1', triggerId = 'dev') => + addVoiceChannel({ channelId, guildId: 'g', ownerId, triggerId, name: `salon-${channelId}` }); + + const voiceChannel = (id, { members = [] } = {}) => ({ + id, + parentId: 'cat', + members: new Collection(members.map((memberId) => [memberId, { id: memberId }])), + deleted: false, + failure: null, + async delete() { + if (this.failure) throw this.failure; + this.deleted = true; + }, + }); + + /** Guild mock whose `fetch` only knows the cached channels, like a channel deleted by hand. */ + const makeGuild = (channels) => { + const cache = new Collection(channels.map((channel) => [channel.id, channel])); + const guild = { id: 'g', channels: { cache, fetch: async (id) => cache.get(id) ?? null } }; + for (const channel of cache.values()) channel.guild = guild; + return guild; + }; + + const clientOf = (...guilds) => ({ guilds: { cache: new Collection(guilds.map((g) => [g.id, g])) } }); + + it('deletes a generated channel as soon as nobody is left in it', async () => { + track('c1'); + const channel = voiceChannel('c1'); + + await cleanupVoiceChannel(makeGuild([channel]), 'c1', { graceMs: 0 }); + + assert.equal(channel.deleted, true); + assert.equal(getVoiceChannel('c1'), null, 'the row is forgotten too'); + }); + + it('keeps a channel that still has members', async () => { + track('c1'); + const channel = voiceChannel('c1', { members: ['u2'] }); + + await cleanupVoiceChannel(makeGuild([channel]), 'c1', { graceMs: 0 }); + + assert.equal(channel.deleted, false); + assert.ok(getVoiceChannel('c1')); + }); + + it('leaves a grace period during which the owner can come back', async () => { + track('c1'); + const channel = voiceChannel('c1'); + + const pending = cleanupVoiceChannel(makeGuild([channel]), 'c1', { graceMs: 30 }); + channel.members.set('u1', { id: 'u1' }); + await pending; + await new Promise((resolve) => setTimeout(resolve, 60)); + + assert.equal(channel.deleted, false, 'the customised channel survives a quick move'); + assert.ok(getVoiceChannel('c1')); + }); + + it('deletes the empty channels and forgets the vanished ones in one sweep', async () => { + track('vide'); + track('occupe', 'u2'); + track('disparu', 'u3', 'sio'); + + const empty = voiceChannel('vide'); + const busy = voiceChannel('occupe', { members: ['u2'] }); + await sweepVoiceChannels(clientOf(makeGuild([empty, busy]))); + + assert.equal(empty.deleted, true); + assert.equal(busy.deleted, false); + assert.equal(getVoiceChannel('vide'), null); + assert.equal(getVoiceChannel('disparu'), null, 'a channel deleted by hand is forgotten'); + assert.ok(getVoiceChannel('occupe')); + }); + + it('runs that sweep on an interval', async () => { + track('c1'); + const channel = voiceChannel('c1'); + + const timer = startVoiceJanitor(clientOf(makeGuild([channel])), 20); + await new Promise((resolve) => setTimeout(resolve, 60)); + clearInterval(timer); + + assert.equal(channel.deleted, true); + assert.equal(getVoiceChannel('c1'), null); + }); + + it('keeps the row when the deletion fails, so the sweep can retry', async () => { + track('c1'); + const channel = voiceChannel('c1'); + channel.failure = Object.assign(new Error('Missing Permissions'), { code: 50013, status: 403 }); + makeGuild([channel]); + + assert.equal(await deleteVoiceChannel(channel, 'test'), false); + assert.ok(getVoiceChannel('c1'), 'the channel is not leaked'); + + channel.failure = null; + assert.equal(await deleteVoiceChannel(channel, 'test'), true); + assert.equal(getVoiceChannel('c1'), null); + }); + + it('forgets a channel that Discord has already deleted', async () => { + track('c1'); + const channel = voiceChannel('c1'); + channel.failure = Object.assign(new Error('Unknown Channel'), { code: 10003 }); + makeGuild([channel]); + + assert.equal(await deleteVoiceChannel(channel, 'test'), true); + assert.equal(getVoiceChannel('c1'), null); + }); +}); + +describe('voice helpers', () => { + it('normalises a channel name', () => { + assert.equal(sanitizeChannelName(' Salon de Léa '), 'Salon de Léa'); + assert.equal(sanitizeChannelName('a\nb'), 'a b'); + assert.equal(sanitizeChannelName('x'.repeat(150)).length, 100); + assert.throws(() => sanitizeChannelName(' '), UserFacingError); + }); + + it('builds the channel name from the template', () => { + const member = { displayName: 'Léa', user: { username: 'lea' } }; + assert.equal(buildChannelName('🔊 Salon de {user}', member), '🔊 Salon de Léa'); + assert.equal(buildChannelName('', member), '🔊 Salon de Léa'); + assert.equal(buildChannelName('{user} {user}', member), 'Léa Léa'); + assert.equal(buildChannelName(' ', member), '🔊 Salon vocal'); + }); + + it('accepts 0..99 as a user limit and rejects anything else', () => { + assert.equal(clampLimit(0), 0); + assert.equal(clampLimit(99), 99); + assert.equal(clampLimit('12'), 12); + assert.equal(clampLimit(150), 0); + assert.equal(clampLimit('abc'), 0); + assert.throws(() => clampLimit(150, { strict: true }), UserFacingError); + assert.throws(() => clampLimit(-1, { strict: true }), UserFacingError); + }); + + it('places a new channel on the last slot of its category', () => { + assert.equal(bottomPosition(0), 0); + assert.equal(bottomPosition(1), 0); + assert.equal(bottomPosition(2), 1); + assert.equal(bottomPosition(7), 6); + }); +}); + +describe('voice ownership', () => { + const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff' }; + const row = { owner_id: 'u1' }; + const context = (id, roleIds = [], overrides = {}) => ({ + user: { id }, + member: member(roleIds, { id, ...overrides }), + }); + + it('lets the owner manage their channel', () => { + assert.doesNotThrow(() => assertVoiceOwner(context('u1'), row)); + }); + + it('refuses a plain member', () => { + assert.throws(() => assertVoiceOwner(context('u2'), row), PermissionDeniedError); + }); + + it('recognises staff from the configured roles', () => { + assert.equal(isStaff(member(['r-staff']), roles), true); + assert.equal(isStaff(member(['r-dev']), roles), true); + assert.equal(isStaff(member(['r-member']), roles), false); + assert.equal(isStaff(member([], { id: 'u9', guildOwnerId: 'u9' }), roles), true); + }); +});