3
0
Fork 0
mirror of https://github.com/ZeppelinBot/Zeppelin.git synced 2025-07-06 18:47:20 +00:00

refactor: remove Timeout imports and constructor syntax sugar

This commit is contained in:
almeidx 2025-06-01 23:38:49 +01:00
parent 62da0a6e34
commit f607ad424b
No known key found for this signature in database
20 changed files with 32 additions and 42 deletions

View file

@ -2,15 +2,18 @@ import { CooldownManager } from "knub";
import { EventEmitter } from "node:events"; import { EventEmitter } from "node:events";
import { RegExpWorker, TimeoutError } from "regexp-worker"; import { RegExpWorker, TimeoutError } from "regexp-worker";
import { MINUTES, SECONDS } from "./utils.js"; import { MINUTES, SECONDS } from "./utils.js";
import Timeout = NodeJS.Timeout;
const isTimeoutError = (a): a is TimeoutError => { const isTimeoutError = (a): a is TimeoutError => {
return a.message != null && a.elapsedTimeMs != null; return a.message != null && a.elapsedTimeMs != null;
}; };
export class RegExpTimeoutError extends Error { export class RegExpTimeoutError extends Error {
constructor(message: string, public elapsedTimeMs: number) { public elapsedTimeMs: number;
constructor(message: string, elapsedTimeMs: number) {
super(message); super(message);
this.elapsedTimeMs = elapsedTimeMs;
} }
} }
@ -47,7 +50,7 @@ export interface RegExpRunner {
*/ */
export class RegExpRunner extends EventEmitter { export class RegExpRunner extends EventEmitter {
private _worker: RegExpWorker | null; private _worker: RegExpWorker | null;
private readonly _failedTimesInterval: Timeout; private readonly _failedTimesInterval: NodeJS.Timeout;
private cooldown: CooldownManager; private cooldown: CooldownManager;
private failedTimes: Map<string, number>; private failedTimes: Map<string, number>;

View file

@ -1,12 +1,10 @@
import Timeout = NodeJS.Timeout;
const CLEAN_INTERVAL = 1000; const CLEAN_INTERVAL = 1000;
export class SimpleCache<T = any> { export class SimpleCache<T = any> {
protected readonly retentionTime: number; protected readonly retentionTime: number;
protected readonly maxItems: number; protected readonly maxItems: number;
protected cleanTimeout: Timeout; protected cleanTimeout: NodeJS.Timeout;
protected unloaded: boolean; protected unloaded: boolean;
protected store: Map<string, { remove_at: number; value: T }>; protected store: Map<string, { remove_at: number; value: T }>;

View file

@ -5,12 +5,11 @@ import { lazyMemoize, MINUTES, SECONDS } from "../../utils.js";
import { Mute } from "../entities/Mute.js"; import { Mute } from "../entities/Mute.js";
import { emitGuildEvent, hasGuildEventListener } from "../GuildEvents.js"; import { emitGuildEvent, hasGuildEventListener } from "../GuildEvents.js";
import { Mutes, TIMEOUT_RENEWAL_THRESHOLD } from "../Mutes.js"; import { Mutes, TIMEOUT_RENEWAL_THRESHOLD } from "../Mutes.js";
import Timeout = NodeJS.Timeout;
const LOOP_INTERVAL = 15 * MINUTES; const LOOP_INTERVAL = 15 * MINUTES;
const MAX_TRIES_PER_SERVER = 3; const MAX_TRIES_PER_SERVER = 3;
const getMutesRepository = lazyMemoize(() => new Mutes()); const getMutesRepository = lazyMemoize(() => new Mutes());
const timeouts = new Map<string, Timeout>(); const timeouts = new Map<string, NodeJS.Timeout>();
function muteToKey(mute: Mute) { function muteToKey(mute: Mute) {
return `${mute.guild_id}/${mute.user_id}`; return `${mute.guild_id}/${mute.user_id}`;

View file

@ -5,12 +5,11 @@ import { lazyMemoize, MINUTES } from "../../utils.js";
import { Tempban } from "../entities/Tempban.js"; import { Tempban } from "../entities/Tempban.js";
import { emitGuildEvent, hasGuildEventListener } from "../GuildEvents.js"; import { emitGuildEvent, hasGuildEventListener } from "../GuildEvents.js";
import { Tempbans } from "../Tempbans.js"; import { Tempbans } from "../Tempbans.js";
import Timeout = NodeJS.Timeout;
const LOOP_INTERVAL = 15 * MINUTES; const LOOP_INTERVAL = 15 * MINUTES;
const MAX_TRIES_PER_SERVER = 3; const MAX_TRIES_PER_SERVER = 3;
const getBansRepository = lazyMemoize(() => new Tempbans()); const getBansRepository = lazyMemoize(() => new Tempbans());
const timeouts = new Map<string, Timeout>(); const timeouts = new Map<string, NodeJS.Timeout>();
function tempbanToKey(tempban: Tempban) { function tempbanToKey(tempban: Tempban) {
return `${tempban.guild_id}/${tempban.user_id}`; return `${tempban.guild_id}/${tempban.user_id}`;

View file

@ -5,12 +5,11 @@ import { lazyMemoize, MINUTES } from "../../utils.js";
import { VCAlert } from "../entities/VCAlert.js"; import { VCAlert } from "../entities/VCAlert.js";
import { emitGuildEvent, hasGuildEventListener } from "../GuildEvents.js"; import { emitGuildEvent, hasGuildEventListener } from "../GuildEvents.js";
import { VCAlerts } from "../VCAlerts.js"; import { VCAlerts } from "../VCAlerts.js";
import Timeout = NodeJS.Timeout;
const LOOP_INTERVAL = 15 * MINUTES; const LOOP_INTERVAL = 15 * MINUTES;
const MAX_TRIES_PER_SERVER = 3; const MAX_TRIES_PER_SERVER = 3;
const getVCAlertsRepository = lazyMemoize(() => new VCAlerts()); const getVCAlertsRepository = lazyMemoize(() => new VCAlerts());
const timeouts = new Map<number, Timeout>(); const timeouts = new Map<number, NodeJS.Timeout>();
function broadcastExpiredVCAlert(alert: VCAlert, tries = 0) { function broadcastExpiredVCAlert(alert: VCAlert, tries = 0) {
console.log(`[EXPIRING VCALERTS LOOP] Broadcasting expired vcalert: ${alert.guild_id}/${alert.user_id}`); console.log(`[EXPIRING VCALERTS LOOP] Broadcasting expired vcalert: ${alert.guild_id}/${alert.user_id}`);

View file

@ -5,12 +5,11 @@ import { lazyMemoize, MINUTES } from "../../utils.js";
import { Reminder } from "../entities/Reminder.js"; import { Reminder } from "../entities/Reminder.js";
import { emitGuildEvent, hasGuildEventListener } from "../GuildEvents.js"; import { emitGuildEvent, hasGuildEventListener } from "../GuildEvents.js";
import { Reminders } from "../Reminders.js"; import { Reminders } from "../Reminders.js";
import Timeout = NodeJS.Timeout;
const LOOP_INTERVAL = 15 * MINUTES; const LOOP_INTERVAL = 15 * MINUTES;
const MAX_TRIES_PER_SERVER = 3; const MAX_TRIES_PER_SERVER = 3;
const getRemindersRepository = lazyMemoize(() => new Reminders()); const getRemindersRepository = lazyMemoize(() => new Reminders());
const timeouts = new Map<number, Timeout>(); const timeouts = new Map<number, NodeJS.Timeout>();
function broadcastReminder(reminder: Reminder, tries = 0) { function broadcastReminder(reminder: Reminder, tries = 0) {
if (!hasGuildEventListener(reminder.guild_id, "reminder")) { if (!hasGuildEventListener(reminder.guild_id, "reminder")) {

View file

@ -5,12 +5,11 @@ import { lazyMemoize, MINUTES } from "../../utils.js";
import { ScheduledPost } from "../entities/ScheduledPost.js"; import { ScheduledPost } from "../entities/ScheduledPost.js";
import { emitGuildEvent, hasGuildEventListener } from "../GuildEvents.js"; import { emitGuildEvent, hasGuildEventListener } from "../GuildEvents.js";
import { ScheduledPosts } from "../ScheduledPosts.js"; import { ScheduledPosts } from "../ScheduledPosts.js";
import Timeout = NodeJS.Timeout;
const LOOP_INTERVAL = 15 * MINUTES; const LOOP_INTERVAL = 15 * MINUTES;
const MAX_TRIES_PER_SERVER = 3; const MAX_TRIES_PER_SERVER = 3;
const getScheduledPostsRepository = lazyMemoize(() => new ScheduledPosts()); const getScheduledPostsRepository = lazyMemoize(() => new ScheduledPosts());
const timeouts = new Map<number, Timeout>(); const timeouts = new Map<number, NodeJS.Timeout>();
function broadcastScheduledPost(post: ScheduledPost, tries = 0) { function broadcastScheduledPost(post: ScheduledPost, tries = 0) {
if (!hasGuildEventListener(post.guild_id, "scheduledPost")) { if (!hasGuildEventListener(post.guild_id, "scheduledPost")) {

View file

@ -4,7 +4,6 @@ import { GuildLogs } from "../../data/GuildLogs.js";
import { GuildSavedMessages } from "../../data/GuildSavedMessages.js"; import { GuildSavedMessages } from "../../data/GuildSavedMessages.js";
import { SavedMessage } from "../../data/entities/SavedMessage.js"; import { SavedMessage } from "../../data/entities/SavedMessage.js";
import { MINUTES, zDelayString } from "../../utils.js"; import { MINUTES, zDelayString } from "../../utils.js";
import Timeout = NodeJS.Timeout;
export const MAX_DELAY = 5 * MINUTES; export const MAX_DELAY = 5 * MINUTES;
@ -26,7 +25,7 @@ export interface AutoDeletePluginType extends BasePluginType {
deletionQueue: IDeletionQueueItem[]; deletionQueue: IDeletionQueueItem[];
nextDeletion: number | null; nextDeletion: number | null;
nextDeletionTimeout: Timeout | null; nextDeletionTimeout: NodeJS.Timeout | null;
maxDelayWarningSent: boolean; maxDelayWarningSent: boolean;

View file

@ -175,7 +175,7 @@ export const ChangePermsAction = automodAction({
const realKey = legacyPermMap[key] ?? key; const realKey = legacyPermMap[key] ?? key;
perms[realKey] = actionConfig.perms[key]; perms[realKey] = actionConfig.perms[key];
} }
const permsArray = <PermissionsString[]>Object.keys(perms).filter((key) => perms[key]); const permsArray = (Object.keys(perms) as PermissionsString[]).filter((key) => perms[key]);
await role.setPermissions(new PermissionsBitField(permsArray)).catch(noop); await role.setPermissions(new PermissionsBitField(permsArray)).catch(noop);
}, },
}); });

View file

@ -17,8 +17,6 @@ import { availableActions } from "./actions/availableActions.js";
import { RecentActionType } from "./constants.js"; import { RecentActionType } from "./constants.js";
import { availableTriggers } from "./triggers/availableTriggers.js"; import { availableTriggers } from "./triggers/availableTriggers.js";
import Timeout = NodeJS.Timeout;
export type ZTriggersMapHelper = { export type ZTriggersMapHelper = {
[TriggerName in keyof typeof availableTriggers]: (typeof availableTriggers)[TriggerName]["configSchema"]; [TriggerName in keyof typeof availableTriggers]: (typeof availableTriggers)[TriggerName]["configSchema"];
}; };
@ -86,7 +84,7 @@ export interface AutomodPluginType extends BasePluginType {
* Recent actions are used for spam triggers * Recent actions are used for spam triggers
*/ */
recentActions: RecentAction[]; recentActions: RecentAction[];
clearRecentActionsInterval: Timeout; clearRecentActionsInterval: NodeJS.Timeout;
/** /**
* After a spam trigger is tripped and the rule's action carried out, a unique identifier is placed here so further * After a spam trigger is tripped and the rule's action carried out, a unique identifier is placed here so further
@ -95,10 +93,10 @@ export interface AutomodPluginType extends BasePluginType {
* Key: rule_name-match_identifier * Key: rule_name-match_identifier
*/ */
recentSpam: RecentSpam[]; recentSpam: RecentSpam[];
clearRecentSpamInterval: Timeout; clearRecentSpamInterval: NodeJS.Timeout;
recentNicknameChanges: Map<string, { timestamp: number }>; recentNicknameChanges: Map<string, { timestamp: number }>;
clearRecentNicknameChangesInterval: Timeout; clearRecentNicknameChangesInterval: NodeJS.Timeout;
ignoredRoleChanges: Set<{ ignoredRoleChanges: Set<{
memberId: string; memberId: string;

View file

@ -10,7 +10,6 @@ import {
} from "../../data/entities/CounterTrigger.js"; } from "../../data/entities/CounterTrigger.js";
import { zBoundedCharacters, zBoundedRecord, zDelayString } from "../../utils.js"; import { zBoundedCharacters, zBoundedRecord, zDelayString } from "../../utils.js";
import { CommonPlugin } from "../Common/CommonPlugin.js"; import { CommonPlugin } from "../Common/CommonPlugin.js";
import Timeout = NodeJS.Timeout;
const MAX_COUNTERS = 5; const MAX_COUNTERS = 5;
const MAX_TRIGGERS_PER_COUNTER = 5; const MAX_TRIGGERS_PER_COUNTER = 5;
@ -89,7 +88,7 @@ export interface CountersPluginType extends BasePluginType {
state: { state: {
counters: GuildCounters; counters: GuildCounters;
counterIds: Record<string, number>; counterIds: Record<string, number>;
decayTimers: Timeout[]; decayTimers: NodeJS.Timeout[];
events: CounterEventEmitter; events: CounterEventEmitter;
counterTriggersByCounterId: Map<number, CounterTrigger[]>; counterTriggersByCounterId: Map<number, CounterTrigger[]>;
common: pluginUtils.PluginPublicInterface<typeof CommonPlugin>; common: pluginUtils.PluginPublicInterface<typeof CommonPlugin>;

View file

@ -1,7 +1,6 @@
import { BasePluginType } from "knub"; import { BasePluginType } from "knub";
import { z } from "zod/v4"; import { z } from "zod/v4";
import { Configs } from "../../data/Configs.js"; import { Configs } from "../../data/Configs.js";
import Timeout = NodeJS.Timeout;
export const zGuildConfigReloaderPluginConfig = z.strictObject({}); export const zGuildConfigReloaderPluginConfig = z.strictObject({});
@ -11,6 +10,6 @@ export interface GuildConfigReloaderPluginType extends BasePluginType {
guildConfigs: Configs; guildConfigs: Configs;
unloaded: boolean; unloaded: boolean;
highestConfigId: number; highestConfigId: number;
nextCheckTimeout: Timeout; nextCheckTimeout: NodeJS.Timeout;
}; };
} }

View file

@ -81,7 +81,7 @@ export async function muteUser(
await member.roles.set(newRoles as Snowflake[]); await member.roles.set(newRoles as Snowflake[]);
} }
} else { } else {
newRoles = currentUserRoles.filter((x) => !(<string[]>removeRoles).includes(x)); newRoles = currentUserRoles.filter((x) => !removeRoles.includes(x));
await member.roles.set(newRoles as Snowflake[]); await member.roles.set(newRoles as Snowflake[]);
} }
@ -91,7 +91,7 @@ export async function muteUser(
rolesToRestore = currentUserRoles; rolesToRestore = currentUserRoles;
} }
} else { } else {
rolesToRestore = currentUserRoles.filter((x) => (<string[]>restoreRoles).includes(x)); rolesToRestore = currentUserRoles.filter((x) => restoreRoles.includes(x));
} }
if (muteType === MuteTypes.Role) { if (muteType === MuteTypes.Role) {

View file

@ -1,10 +1,9 @@
import { Message } from "discord.js"; import { Message } from "discord.js";
import { TStarboardOpts } from "../types.js"; import { TStarboardOpts } from "../types.js";
import { createStarboardPseudoFooterForMessage } from "./createStarboardPseudoFooterForMessage.js"; import { createStarboardPseudoFooterForMessage } from "./createStarboardPseudoFooterForMessage.js";
import Timeout = NodeJS.Timeout;
const DEBOUNCE_DELAY = 1000; const DEBOUNCE_DELAY = 1000;
const debouncedUpdates: Record<string, Timeout> = {}; const debouncedUpdates: Record<string, NodeJS.Timeout> = {};
export async function updateStarboardMessageStarCount( export async function updateStarboardMessageStarCount(
starboard: TStarboardOpts, starboard: TStarboardOpts,

View file

@ -31,7 +31,6 @@ import { searchCmdSignature } from "./commands/SearchCmd.js";
import { getUserInfoEmbed } from "./functions/getUserInfoEmbed.js"; import { getUserInfoEmbed } from "./functions/getUserInfoEmbed.js";
import { refreshMembersIfNeeded } from "./refreshMembers.js"; import { refreshMembersIfNeeded } from "./refreshMembers.js";
import { UtilityPluginType } from "./types.js"; import { UtilityPluginType } from "./types.js";
import Timeout = NodeJS.Timeout;
const SEARCH_RESULTS_PER_PAGE = 15; const SEARCH_RESULTS_PER_PAGE = 15;
const SEARCH_ID_RESULTS_PER_PAGE = 50; const SEARCH_ID_RESULTS_PER_PAGE = 50;
@ -93,7 +92,7 @@ export async function displaySearch(
let searching = false; let searching = false;
let currentPage = args.page || 1; let currentPage = args.page || 1;
let stopCollectionFn: () => void; let stopCollectionFn: () => void;
let stopCollectionTimeout: Timeout; let stopCollectionTimeout: NodeJS.Timeout;
const perPage = args.ids ? SEARCH_ID_RESULTS_PER_PAGE : SEARCH_RESULTS_PER_PAGE; const perPage = args.ids ? SEARCH_ID_RESULTS_PER_PAGE : SEARCH_RESULTS_PER_PAGE;

View file

@ -3,8 +3,11 @@
*/ */
export class DecayingCounter { export class DecayingCounter {
protected value = 0; protected value = 0;
protected decayInterval: number;
constructor(decayInterval: number) {
this.decayInterval = decayInterval;
constructor(protected decayInterval: number) {
setInterval(() => { setInterval(() => {
this.value = Math.max(0, this.value - 1); this.value = Math.max(0, this.value - 1);
}, decayInterval); }, decayInterval);

View file

@ -1,6 +1,5 @@
import { StrictMessageContent } from "../utils.js"; import { StrictMessageContent } from "../utils.js";
import { calculateEmbedSize } from "./calculateEmbedSize.js"; import { calculateEmbedSize } from "./calculateEmbedSize.js";
import Timeout = NodeJS.Timeout;
type ConsumeFn = (part: StrictMessageContent) => void; type ConsumeFn = (part: StrictMessageContent) => void;
@ -35,7 +34,7 @@ export class MessageBuffer {
protected chunk: Chunk | null = null; protected chunk: Chunk | null = null;
protected chunkTimeout: Timeout | null = null; protected chunkTimeout: NodeJS.Timeout | null = null;
protected finalizedChunks: MessageBufferContent[] = []; protected finalizedChunks: MessageBufferContent[] = [];

View file

@ -2,7 +2,6 @@ import { Client, Message, MessageReaction, PartialMessageReaction, PartialUser,
import { ContextResponseOptions, fetchContextChannel, GenericCommandSource } from "../pluginUtils.js"; import { ContextResponseOptions, fetchContextChannel, GenericCommandSource } from "../pluginUtils.js";
import { MINUTES, noop } from "../utils.js"; import { MINUTES, noop } from "../utils.js";
import { Awaitable } from "./typeUtils.js"; import { Awaitable } from "./typeUtils.js";
import Timeout = NodeJS.Timeout;
export type LoadPageFn = (page: number) => Awaitable<ContextResponseOptions>; export type LoadPageFn = (page: number) => Awaitable<ContextResponseOptions>;
@ -81,7 +80,7 @@ export async function createPaginatedMessage(
// The timeout after which reactions are removed and the pagination stops working // The timeout after which reactions are removed and the pagination stops working
// is refreshed each time the page is changed // is refreshed each time the page is changed
let timeout: Timeout; let timeout: NodeJS.Timeout;
const refreshTimeout = () => { const refreshTimeout = () => {
clearTimeout(timeout); clearTimeout(timeout);
timeout = setTimeout(() => { timeout = setTimeout(() => {

View file

@ -1,10 +1,9 @@
import { MessagePayload, User } from "discord.js"; import { MessagePayload, User } from "discord.js";
import { logger } from "../logger.js"; import { logger } from "../logger.js";
import { HOURS, createChunkedMessage, isDiscordAPIError } from "../utils.js"; import { HOURS, createChunkedMessage, isDiscordAPIError } from "../utils.js";
import Timeout = NodeJS.Timeout;
let dmsDisabled = false; let dmsDisabled = false;
let dmsDisabledTimeout: Timeout; let dmsDisabledTimeout: NodeJS.Timeout;
function disableDMs(duration) { function disableDMs(duration) {
dmsDisabled = true; dmsDisabled = true;

View file

@ -6,7 +6,8 @@
"baseUrl": "./src", "baseUrl": "./src",
"rootDir": "./src", "rootDir": "./src",
"outDir": "./dist", "outDir": "./dist",
"composite": true "composite": true,
"erasableSyntaxOnly": true
}, },
"include": ["src/**/*.ts", "src/**/*.json"], "include": ["src/**/*.ts", "src/**/*.json"],
"references": [ "references": [