chore: fix leftover eslint exceptions

This commit is contained in:
iCrawl
2022-09-01 21:26:09 +02:00
parent edadb9fe5d
commit 3b7ba4062e
80 changed files with 141 additions and 337 deletions

View File

@@ -2,18 +2,18 @@ import { relative, resolve } from 'node:path';
import glob from 'fast-glob'; import glob from 'fast-glob';
import isCi from 'is-ci'; import isCi from 'is-ci';
import typescript from 'rollup-plugin-typescript2'; import typescript from 'rollup-plugin-typescript2';
import { defineBuildConfig, BuildEntry } from 'unbuild'; import { defineBuildConfig, type BuildEntry } from 'unbuild';
interface ConfigOptions { interface ConfigOptions {
entries: (BuildEntry | string)[];
minify: boolean;
emitCJS: boolean;
externals: string[];
cjsBridge: boolean; cjsBridge: boolean;
sourcemap: boolean; declaration: boolean;
emitCJS: boolean;
entries: (BuildEntry | string)[];
externals: string[];
minify: boolean;
preserveModules: boolean; preserveModules: boolean;
preserveModulesRoot: string; preserveModulesRoot: string;
declaration: boolean; sourcemap: boolean;
typeCheck: boolean; typeCheck: boolean;
} }
@@ -31,8 +31,7 @@ export function createUnbuildConfig({
}: Partial<ConfigOptions> = {}) { }: Partial<ConfigOptions> = {}) {
const files = glob const files = glob
.sync('**', { cwd: 'src' }) .sync('**', { cwd: 'src' })
.map((file) => [`${file.slice(0, -2)}cjs`, `${file.slice(0, -2)}mjs`]) .flatMap((file) => [`${file.slice(0, -2)}cjs`, `${file.slice(0, -2)}mjs`]);
.flat();
return defineBuildConfig({ return defineBuildConfig({
entries, entries,
@@ -55,7 +54,6 @@ export function createUnbuildConfig({
hooks: { hooks: {
'rollup:options': (_, options) => { 'rollup:options': (_, options) => {
// @ts-expect-error: This will always be an array // @ts-expect-error: This will always be an array
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
options.output![0] = { options.output![0] = {
// @ts-expect-error: This will always be an array // @ts-expect-error: This will always be an array
...options.output![0], ...options.output![0],
@@ -66,7 +64,6 @@ export function createUnbuildConfig({
if (emitCJS) { if (emitCJS) {
// @ts-expect-error: This will always be an array // @ts-expect-error: This will always be an array
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
options.output![1] = { options.output![1] = {
// @ts-expect-error: This will always be an array // @ts-expect-error: This will always be an array
...options.output![1], ...options.output![1],

View File

@@ -20,8 +20,8 @@ import {
} from '@microsoft/api-extractor-model'; } from '@microsoft/api-extractor-model';
import { generateTypeParamData } from './TypeParameterJSONEncoder.js'; import { generateTypeParamData } from './TypeParameterJSONEncoder.js';
import { type TokenDocumentation, resolveName, genReference, genToken, genParameter, generatePath } from './parse.js'; import { type TokenDocumentation, resolveName, genReference, genToken, genParameter, generatePath } from './parse.js';
import type { DocBlockJSON } from './tsdoc/CommentBlock'; import type { DocBlockJSON } from './tsdoc/CommentBlock.js';
import type { AnyDocNodeJSON } from './tsdoc/CommentNode'; import type { AnyDocNodeJSON } from './tsdoc/CommentNode.js';
import { type DocNodeContainerJSON, nodeContainer } from './tsdoc/CommentNodeContainer.js'; import { type DocNodeContainerJSON, nodeContainer } from './tsdoc/CommentNodeContainer.js';
import { createCommentNode } from './tsdoc/index.js'; import { createCommentNode } from './tsdoc/index.js';
@@ -140,7 +140,6 @@ export interface ApiConstructorJSON extends ApiItemJSON, ApiParameterListJSON {
protected: boolean; protected: boolean;
} }
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class ApiNodeJSONEncoder { export class ApiNodeJSONEncoder {
public static encode(model: ApiModel, node: ApiItem, version: string) { public static encode(model: ApiModel, node: ApiItem, version: string) {
if (!(node instanceof ApiDeclaredItem)) { if (!(node instanceof ApiDeclaredItem)) {

View File

@@ -1,11 +1,11 @@
import type { DocNode, DocNodeKind } from '@microsoft/tsdoc'; import type { DocNode, DocNodeKind } from '@microsoft/tsdoc';
import type { DocBlockJSON } from './CommentBlock'; import type { DocBlockJSON } from './CommentBlock.js';
import type { DocCodeSpanJSON } from './CommentCodeSpan'; import type { DocCodeSpanJSON } from './CommentCodeSpan.js';
import type { DocNodeContainerJSON } from './CommentNodeContainer'; import type { DocNodeContainerJSON } from './CommentNodeContainer.js';
import type { DocFencedCodeJSON } from './FencedCodeCommentNode'; import type { DocFencedCodeJSON } from './FencedCodeCommentNode.js';
import type { DocLinkTagJSON } from './LinkTagCommentNode'; import type { DocLinkTagJSON } from './LinkTagCommentNode.js';
import type { DocPlainTextJSON } from './PlainTextCommentNode'; import type { DocPlainTextJSON } from './PlainTextCommentNode.js';
import type { DocCommentJSON } from './RootComment'; import type { DocCommentJSON } from './RootComment.js';
export interface DocNodeJSON { export interface DocNodeJSON {
kind: DocNodeKind; kind: DocNodeKind;

View File

@@ -71,7 +71,7 @@ describe('Button Components', () => {
}).toThrowError(); }).toThrowError();
expect(() => { expect(() => {
// @ts-expect-error: invalid emoji // @ts-expect-error: Invalid emoji
const button = buttonComponent().setEmoji('test'); const button = buttonComponent().setEmoji('test');
button.toJSON(); button.toJSON();
}).toThrowError(); }).toThrowError();
@@ -103,9 +103,9 @@ describe('Button Components', () => {
expect(() => buttonComponent().setStyle(24)).toThrowError(); expect(() => buttonComponent().setStyle(24)).toThrowError();
expect(() => buttonComponent().setLabel(longStr)).toThrowError(); expect(() => buttonComponent().setLabel(longStr)).toThrowError();
// @ts-expect-error: invalid parameter for disabled // @ts-expect-error: Invalid parameter for disabled
expect(() => buttonComponent().setDisabled(0)).toThrowError(); expect(() => buttonComponent().setDisabled(0)).toThrowError();
// @ts-expect-error: invalid emoji // @ts-expect-error: Invalid emoji
expect(() => buttonComponent().setEmoji('foo')).toThrowError(); expect(() => buttonComponent().setEmoji('foo')).toThrowError();
expect(() => buttonComponent().setURL('foobar')).toThrowError(); expect(() => buttonComponent().setURL('foobar')).toThrowError();

View File

@@ -98,30 +98,30 @@ describe('Select Menu Components', () => {
expect(() => selectMenu().setCustomId(longStr)).toThrowError(); expect(() => selectMenu().setCustomId(longStr)).toThrowError();
expect(() => selectMenu().setMaxValues(30)).toThrowError(); expect(() => selectMenu().setMaxValues(30)).toThrowError();
expect(() => selectMenu().setMinValues(-20)).toThrowError(); expect(() => selectMenu().setMinValues(-20)).toThrowError();
// @ts-expect-error: invalid disabled value // @ts-expect-error: Invalid disabled value
expect(() => selectMenu().setDisabled(0)).toThrowError(); expect(() => selectMenu().setDisabled(0)).toThrowError();
expect(() => selectMenu().setPlaceholder(longStr)).toThrowError(); expect(() => selectMenu().setPlaceholder(longStr)).toThrowError();
// @ts-expect-error: invalid option // @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions({ label: 'test' })).toThrowError(); expect(() => selectMenu().addOptions({ label: 'test' })).toThrowError();
expect(() => selectMenu().addOptions({ label: longStr, value: 'test' })).toThrowError(); expect(() => selectMenu().addOptions({ label: longStr, value: 'test' })).toThrowError();
expect(() => selectMenu().addOptions({ value: longStr, label: 'test' })).toThrowError(); expect(() => selectMenu().addOptions({ value: longStr, label: 'test' })).toThrowError();
expect(() => selectMenu().addOptions({ label: 'test', value: 'test', description: longStr })).toThrowError(); expect(() => selectMenu().addOptions({ label: 'test', value: 'test', description: longStr })).toThrowError();
// @ts-expect-error: invalid option // @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions({ label: 'test', value: 'test', default: 100 })).toThrowError(); expect(() => selectMenu().addOptions({ label: 'test', value: 'test', default: 100 })).toThrowError();
// @ts-expect-error: invalid option // @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions({ value: 'test' })).toThrowError(); expect(() => selectMenu().addOptions({ value: 'test' })).toThrowError();
// @ts-expect-error: invalid option // @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions({ default: true })).toThrowError(); expect(() => selectMenu().addOptions({ default: true })).toThrowError();
// @ts-expect-error: invalid option // @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions([{ label: 'test' }])).toThrowError(); expect(() => selectMenu().addOptions([{ label: 'test' }])).toThrowError();
expect(() => selectMenu().addOptions([{ label: longStr, value: 'test' }])).toThrowError(); expect(() => selectMenu().addOptions([{ label: longStr, value: 'test' }])).toThrowError();
expect(() => selectMenu().addOptions([{ value: longStr, label: 'test' }])).toThrowError(); expect(() => selectMenu().addOptions([{ value: longStr, label: 'test' }])).toThrowError();
expect(() => selectMenu().addOptions([{ label: 'test', value: 'test', description: longStr }])).toThrowError(); expect(() => selectMenu().addOptions([{ label: 'test', value: 'test', description: longStr }])).toThrowError();
// @ts-expect-error: invalid option // @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions([{ label: 'test', value: 'test', default: 100 }])).toThrowError(); expect(() => selectMenu().addOptions([{ label: 'test', value: 'test', default: 100 }])).toThrowError();
// @ts-expect-error: invalid option // @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions([{ value: 'test' }])).toThrowError(); expect(() => selectMenu().addOptions([{ value: 'test' }])).toThrowError();
// @ts-expect-error: invalid option // @ts-expect-error: Invalid option
expect(() => selectMenu().addOptions([{ default: true }])).toThrowError(); expect(() => selectMenu().addOptions([{ default: true }])).toThrowError();
const tooManyOptions = Array.from<APISelectMenuOption>({ length: 26 }).fill({ label: 'test', value: 'test' }); const tooManyOptions = Array.from<APISelectMenuOption>({ length: 26 }).fill({ label: 'test', value: 'test' });
@@ -144,9 +144,9 @@ describe('Select Menu Components', () => {
selectMenuOption() selectMenuOption()
.setLabel(longStr) .setLabel(longStr)
.setValue(longStr) .setValue(longStr)
// @ts-expect-error: invalid default value // @ts-expect-error: Invalid default value
.setDefault(-1) .setDefault(-1)
// @ts-expect-error: invalid emoji // @ts-expect-error: Invalid emoji
.setEmoji({ name: 1 }) .setEmoji({ name: 1 })
.setDescription(longStr); .setDescription(longStr);
}).toThrowError(); }).toThrowError();

View File

@@ -85,7 +85,7 @@ describe('Text Input Components', () => {
expect(() => { expect(() => {
// Issue #8107 // Issue #8107
// @ts-expect-error: shapeshift maps the enum key to the value when parsing // @ts-expect-error: Shapeshift maps the enum key to the value when parsing
textInputComponent().setCustomId('Custom').setLabel('Guess').setStyle('Short').toJSON(); textInputComponent().setCustomId('Custom').setLabel('Guess').setStyle('Short').toJSON();
}).not.toThrowError(); }).not.toThrowError();
}); });

View File

@@ -105,9 +105,9 @@ describe('Context Menu Commands', () => {
}); });
test('GIVEN invalid name localizations THEN does throw error', () => { test('GIVEN invalid name localizations THEN does throw error', () => {
// @ts-expect-error: invalid localization // @ts-expect-error: Invalid localization
expect(() => getBuilder().setNameLocalization('en-U', 'foobar')).toThrowError(); expect(() => getBuilder().setNameLocalization('en-U', 'foobar')).toThrowError();
// @ts-expect-error: invalid localization // @ts-expect-error: Invalid localization
expect(() => getBuilder().setNameLocalizations({ 'en-U': 'foobar' })).toThrowError(); expect(() => getBuilder().setNameLocalizations({ 'en-U': 'foobar' })).toThrowError();
}); });

View File

@@ -101,7 +101,8 @@ describe('Application Command toJSON() results', () => {
max_value: 10, max_value: 10,
min_value: -1, min_value: -1,
autocomplete: true, autocomplete: true,
// @ts-expect-error TODO: you *can* send an empty array with autocomplete: true, should correct that in types // TODO
// @ts-expect-error You *can* send an empty array with autocomplete: true, should correct that in types
choices: [], choices: [],
}); });
@@ -145,7 +146,8 @@ describe('Application Command toJSON() results', () => {
max_value: 10, max_value: 10,
min_value: -1.23, min_value: -1.23,
autocomplete: true, autocomplete: true,
// @ts-expect-error TODO: you *can* send an empty array with autocomplete: true, should correct that in types // TODO
// @ts-expect-error You *can* send an empty array with autocomplete: true, should correct that in types
choices: [], choices: [],
}); });
@@ -187,7 +189,8 @@ describe('Application Command toJSON() results', () => {
type: ApplicationCommandOptionType.String, type: ApplicationCommandOptionType.String,
required: true, required: true,
autocomplete: true, autocomplete: true,
// @ts-expect-error TODO: you *can* send an empty array with autocomplete: true, should correct that in types // TODO
// @ts-expect-error you *can* send an empty array with autocomplete: true, should correct that in types
choices: [], choices: [],
}); });

View File

@@ -176,7 +176,7 @@ describe('Slash Commands', () => {
}); });
test('GIVEN a builder with invalid autocomplete THEN does throw an error', () => { test('GIVEN a builder with invalid autocomplete THEN does throw an error', () => {
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addStringOption(getStringOption().setAutocomplete('not a boolean'))).toThrowError(); expect(() => getBuilder().addStringOption(getStringOption().setAutocomplete('not a boolean'))).toThrowError();
}); });
@@ -246,16 +246,16 @@ describe('Slash Commands', () => {
}); });
test('GIVEN a builder with invalid number min/max options THEN does throw an error', () => { test('GIVEN a builder with invalid number min/max options THEN does throw an error', () => {
// @ts-expect-error: invalid max value // @ts-expect-error: Invalid max value
expect(() => getBuilder().addNumberOption(getNumberOption().setMaxValue('test'))).toThrowError(); expect(() => getBuilder().addNumberOption(getNumberOption().setMaxValue('test'))).toThrowError();
// @ts-expect-error: invalid max value // @ts-expect-error: Invalid max value
expect(() => getBuilder().addIntegerOption(getIntegerOption().setMaxValue('test'))).toThrowError(); expect(() => getBuilder().addIntegerOption(getIntegerOption().setMaxValue('test'))).toThrowError();
// @ts-expect-error: invalid min value // @ts-expect-error: Invalid min value
expect(() => getBuilder().addNumberOption(getNumberOption().setMinValue('test'))).toThrowError(); expect(() => getBuilder().addNumberOption(getNumberOption().setMinValue('test'))).toThrowError();
// @ts-expect-error: invalid min value // @ts-expect-error: Invalid min value
expect(() => getBuilder().addIntegerOption(getIntegerOption().setMinValue('test'))).toThrowError(); expect(() => getBuilder().addIntegerOption(getIntegerOption().setMinValue('test'))).toThrowError();
expect(() => getBuilder().addIntegerOption(getIntegerOption().setMinValue(1.5))).toThrowError(); expect(() => getBuilder().addIntegerOption(getIntegerOption().setMinValue(1.5))).toThrowError();
@@ -292,10 +292,10 @@ describe('Slash Commands', () => {
}); });
test('GIVEN no valid return for an addOption method THEN throw error', () => { test('GIVEN no valid return for an addOption method THEN throw error', () => {
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption()).toThrowError(); expect(() => getBuilder().addBooleanOption()).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption(getRoleOption())).toThrowError(); expect(() => getBuilder().addBooleanOption(getRoleOption())).toThrowError();
}); });
@@ -316,18 +316,18 @@ describe('Slash Commands', () => {
}); });
test('GIVEN invalid returns for builder THEN throw error', () => { test('GIVEN invalid returns for builder THEN throw error', () => {
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption(true)).toThrowError(); expect(() => getBuilder().addBooleanOption(true)).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption(null)).toThrowError(); expect(() => getBuilder().addBooleanOption(null)).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption(undefined)).toThrowError(); expect(() => getBuilder().addBooleanOption(undefined)).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption(() => SlashCommandStringOption)).toThrowError(); expect(() => getBuilder().addBooleanOption(() => SlashCommandStringOption)).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addBooleanOption(() => new Collection())).toThrowError(); expect(() => getBuilder().addBooleanOption(() => new Collection())).toThrowError();
}); });
@@ -387,30 +387,29 @@ describe('Slash Commands', () => {
test('GIVEN builder with a subcommand that tries to add an invalid result THEN throw error', () => { test('GIVEN builder with a subcommand that tries to add an invalid result THEN throw error', () => {
expect(() => expect(() =>
// @ts-expect-error Checking if check works JS-side too // @ts-expect-error: Checking if check works JS-side too
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call
getNamedBuilder().addSubcommand(getSubcommand()).addInteger(getInteger()), getNamedBuilder().addSubcommand(getSubcommand()).addInteger(getInteger()),
).toThrowError(); ).toThrowError();
}); });
test('GIVEN no valid return for an addSubcommand(Group) method THEN throw error', () => { test('GIVEN no valid return for an addSubcommand(Group) method THEN throw error', () => {
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addSubcommandGroup()).toThrowError(); expect(() => getBuilder().addSubcommandGroup()).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addSubcommand()).toThrowError(); expect(() => getBuilder().addSubcommand()).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getBuilder().addSubcommand(getSubcommandGroup())).toThrowError(); expect(() => getBuilder().addSubcommand(getSubcommandGroup())).toThrowError();
}); });
}); });
describe('Subcommand group builder', () => { describe('Subcommand group builder', () => {
test('GIVEN no valid subcommand THEN throw error', () => { test('GIVEN no valid subcommand THEN throw error', () => {
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getSubcommandGroup().addSubcommand()).toThrowError(); expect(() => getSubcommandGroup().addSubcommand()).toThrowError();
// @ts-expect-error Checking if not providing anything, or an invalid return type causes an error // @ts-expect-error: Checking if not providing anything, or an invalid return type causes an error
expect(() => getSubcommandGroup().addSubcommand(getSubcommandGroup())).toThrowError(); expect(() => getSubcommandGroup().addSubcommand(getSubcommandGroup())).toThrowError();
}); });
@@ -442,9 +441,9 @@ describe('Slash Commands', () => {
}); });
test('GIVEN invalid name localizations THEN does throw error', () => { test('GIVEN invalid name localizations THEN does throw error', () => {
// @ts-expect-error: invalid localization // @ts-expect-error: Invalid localization
expect(() => getBuilder().setNameLocalization('en-U', 'foobar')).toThrowError(); expect(() => getBuilder().setNameLocalization('en-U', 'foobar')).toThrowError();
// @ts-expect-error: invalid localization // @ts-expect-error: Invalid localization
expect(() => getBuilder().setNameLocalizations({ 'en-U': 'foobar' })).toThrowError(); expect(() => getBuilder().setNameLocalizations({ 'en-U': 'foobar' })).toThrowError();
}); });
@@ -465,9 +464,9 @@ describe('Slash Commands', () => {
}); });
test('GIVEN invalid description localizations THEN does throw error', () => { test('GIVEN invalid description localizations THEN does throw error', () => {
// @ts-expect-error: invalid localization description // @ts-expect-error: Invalid localization description
expect(() => getBuilder().setDescriptionLocalization('en-U', 'foobar')).toThrowError(); expect(() => getBuilder().setDescriptionLocalization('en-U', 'foobar')).toThrowError();
// @ts-expect-error: invalid localization description // @ts-expect-error: Invalid localization description
expect(() => getBuilder().setDescriptionLocalizations({ 'en-U': 'foobar' })).toThrowError(); expect(() => getBuilder().setDescriptionLocalizations({ 'en-U': 'foobar' })).toThrowError();
}); });

View File

@@ -46,7 +46,7 @@ describe('Modals', () => {
test('GIVEN invalid required parameters THEN validator does throw', () => { test('GIVEN invalid required parameters THEN validator does throw', () => {
expect(() => expect(() =>
// @ts-expect-error: missing required parameter // @ts-expect-error: Missing required parameter
validateRequiredParameters('123', undefined, [new ActionRowBuilder(), new ButtonBuilder()]), validateRequiredParameters('123', undefined, [new ActionRowBuilder(), new ButtonBuilder()]),
).toThrowError(); ).toThrowError();
}); });
@@ -66,7 +66,7 @@ describe('Modals', () => {
test('GIVEN invalid fields THEN builder does throw', () => { test('GIVEN invalid fields THEN builder does throw', () => {
expect(() => modal().setTitle('test').setCustomId('foobar').toJSON()).toThrowError(); expect(() => modal().setTitle('test').setCustomId('foobar').toJSON()).toThrowError();
// @ts-expect-error: customId is invalid // @ts-expect-error: CustomId is invalid
expect(() => modal().setTitle('test').setCustomId(42).toJSON()).toThrowError(); expect(() => modal().setTitle('test').setCustomId(42).toJSON()).toThrowError();
}); });

View File

@@ -130,9 +130,9 @@ describe('Embed', () => {
test('GIVEN an embed with an invalid color THEN throws error', () => { test('GIVEN an embed with an invalid color THEN throws error', () => {
const embed = new EmbedBuilder(); const embed = new EmbedBuilder();
// @ts-expect-error: invalid color // @ts-expect-error: Invalid color
expect(() => embed.setColor('RED')).toThrowError(); expect(() => embed.setColor('RED')).toThrowError();
// @ts-expect-error: invalid color // @ts-expect-error: Invalid color
expect(() => embed.setColor([42, 36])).toThrowError(); expect(() => embed.setColor([42, 36])).toThrowError();
expect(() => embed.setColor([42, 36, 1_000])).toThrowError(); expect(() => embed.setColor([42, 36, 1_000])).toThrowError();
}); });

View File

@@ -8,9 +8,9 @@ import {
import { normalizeArray, type RestOrArray } from '../util/normalizeArray.js'; import { normalizeArray, type RestOrArray } from '../util/normalizeArray.js';
import { ComponentBuilder } from './Component.js'; import { ComponentBuilder } from './Component.js';
import { createComponentBuilder } from './Components.js'; import { createComponentBuilder } from './Components.js';
import type { ButtonBuilder } from './button/Button'; import type { ButtonBuilder } from './button/Button.js';
import type { SelectMenuBuilder } from './selectMenu/SelectMenu'; import type { SelectMenuBuilder } from './selectMenu/SelectMenu.js';
import type { TextInputBuilder } from './textInput/TextInput'; import type { TextInputBuilder } from './textInput/TextInput.js';
export type MessageComponentBuilder = export type MessageComponentBuilder =
| ActionRowBuilder<MessageActionRowComponentBuilder> | ActionRowBuilder<MessageActionRowComponentBuilder>
@@ -62,7 +62,6 @@ export class ActionRowBuilder<T extends AnyComponentBuilder> extends ComponentBu
* {@inheritDoc ComponentBuilder.toJSON} * {@inheritDoc ComponentBuilder.toJSON}
*/ */
public toJSON(): APIActionRowComponent<ReturnType<T['toJSON']>> { public toJSON(): APIActionRowComponent<ReturnType<T['toJSON']>> {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return { return {
...this.data, ...this.data,
components: this.components.map((component) => component.toJSON()), components: this.components.map((component) => component.toJSON()),

View File

@@ -45,7 +45,6 @@ export function createComponentBuilder(
return new TextInputBuilder(data); return new TextInputBuilder(data);
default: default:
// @ts-expect-error: This case can still occur if we get a newer unsupported component type // @ts-expect-error: This case can still occur if we get a newer unsupported component type
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`Cannot properly serialize component type: ${data.type}`); throw new Error(`Cannot properly serialize component type: ${data.type}`);
} }
} }

View File

@@ -129,7 +129,7 @@ export class ButtonBuilder extends ComponentBuilder<APIButtonComponent> {
(this.data as APIButtonComponentWithCustomId).custom_id, (this.data as APIButtonComponentWithCustomId).custom_id,
(this.data as APIButtonComponentWithURL).url, (this.data as APIButtonComponentWithURL).url,
); );
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return { return {
...this.data, ...this.data,
} as APIButtonComponent; } as APIButtonComponent;

View File

@@ -123,7 +123,7 @@ export class SelectMenuBuilder extends ComponentBuilder<APISelectMenuComponent>
*/ */
public toJSON(): APISelectMenuComponent { public toJSON(): APISelectMenuComponent {
validateRequiredSelectMenuParameters(this.options, this.data.custom_id); validateRequiredSelectMenuParameters(this.options, this.data.custom_id);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return { return {
...this.data, ...this.data,
options: this.options.map((option) => option.toJSON()), options: this.options.map((option) => option.toJSON()),

View File

@@ -68,7 +68,7 @@ export class SelectMenuOptionBuilder implements JSONEncodable<APISelectMenuOptio
*/ */
public toJSON(): APISelectMenuOption { public toJSON(): APISelectMenuOption {
validateRequiredSelectMenuOptionParameters(this.data.label, this.data.value); validateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return { return {
...this.data, ...this.data,
} as APISelectMenuOption; } as APISelectMenuOption;

View File

@@ -108,7 +108,7 @@ export class TextInputBuilder
*/ */
public toJSON(): APITextInputComponent { public toJSON(): APITextInputComponent {
validateRequiredParameters(this.data.custom_id, this.data.style, this.data.label); validateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return { return {
...this.data, ...this.data,
} as APITextInputComponent; } as APITextInputComponent;

View File

@@ -1,7 +1,7 @@
import { s } from '@sapphire/shapeshift'; import { s } from '@sapphire/shapeshift';
import { ApplicationCommandType } from 'discord-api-types/v10'; import { ApplicationCommandType } from 'discord-api-types/v10';
import { isValidationEnabled } from '../../util/validation.js'; import { isValidationEnabled } from '../../util/validation.js';
import type { ContextMenuCommandType } from './ContextMenuCommandBuilder'; import type { ContextMenuCommandType } from './ContextMenuCommandBuilder.js';
const namePredicate = s.string const namePredicate = s.string
.lengthGreaterThanOrEqual(1) .lengthGreaterThanOrEqual(1)

View File

@@ -76,7 +76,7 @@ export class ModalBuilder implements JSONEncodable<APIModalInteractionResponseCa
*/ */
public toJSON(): APIModalInteractionResponseCallbackData { public toJSON(): APIModalInteractionResponseCallbackData {
validateRequiredParameters(this.data.custom_id, this.data.title, this.components); validateRequiredParameters(this.data.custom_id, this.data.title, this.components);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return { return {
...this.data, ...this.data,
components: this.components.map((component) => component.toJSON()), components: this.components.map((component) => component.toJSON()),

View File

@@ -1,9 +1,9 @@
import { s } from '@sapphire/shapeshift'; import { s } from '@sapphire/shapeshift';
import { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10'; import { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10';
import { isValidationEnabled } from '../../util/validation.js'; import { isValidationEnabled } from '../../util/validation.js';
import type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder'; import type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';
import type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands'; import type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';
import type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase'; import type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';
const namePredicate = s.string const namePredicate = s.string
.lengthGreaterThanOrEqual(1) .lengthGreaterThanOrEqual(1)

View File

@@ -6,7 +6,7 @@ import {
import { mix } from 'ts-mixer'; import { mix } from 'ts-mixer';
import { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js'; import { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js';
import type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js'; import type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';
import type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase'; import type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';
import { SharedNameAndDescription } from './mixins/NameAndDescription.js'; import { SharedNameAndDescription } from './mixins/NameAndDescription.js';
import { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js'; import { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';

View File

@@ -96,7 +96,6 @@ export function hideLinkEmbed<C extends string>(url: C): `<${C}>`;
*/ */
export function hideLinkEmbed(url: URL): `<${string}>`; export function hideLinkEmbed(url: URL): `<${string}>`;
export function hideLinkEmbed(url: URL | string) { export function hideLinkEmbed(url: URL | string) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return `<${url}>`; return `<${url}>`;
} }
@@ -142,7 +141,6 @@ export function hyperlink<C extends string, U extends string, T extends string>(
title: T, title: T,
): `[${C}](${U} "${T}")`; ): `[${C}](${U} "${T}")`;
export function hyperlink(content: string, url: URL | string, title?: string) { export function hyperlink(content: string, url: URL | string, title?: string) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`; return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`;
} }

View File

@@ -20,7 +20,6 @@ function createTestCollection(): TestCollection {
function expectInvalidFunctionError(cb: () => unknown, val?: unknown): void { function expectInvalidFunctionError(cb: () => unknown, val?: unknown): void {
expect(() => { expect(() => {
cb(); cb();
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
}).toThrowError(new TypeError(`${val} is not a function`)); }).toThrowError(new TypeError(`${val} is not a function`));
} }
@@ -133,9 +132,9 @@ describe('each() tests', () => {
const coll = createTestCollection(); const coll = createTestCollection();
test('throws if fn is not a function', () => { test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.each()); expectInvalidFunctionError(() => coll.each());
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.each(123), 123); expectInvalidFunctionError(() => coll.each(123), 123);
}); });
@@ -154,7 +153,7 @@ describe('each() tests', () => {
describe('ensure() tests', () => { describe('ensure() tests', () => {
test('throws if defaultValueGenerator is not a function', () => { test('throws if defaultValueGenerator is not a function', () => {
const coll = createTestCollection(); const coll = createTestCollection();
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.ensure('d', 'abc'), 'abc'); expectInvalidFunctionError(() => coll.ensure('d', 'abc'), 'abc');
}); });
@@ -178,7 +177,7 @@ describe('equals() tests', () => {
const coll2 = createTestCollection(); const coll2 = createTestCollection();
test('returns false if no collection is passed', () => { test('returns false if no collection is passed', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expect(coll1.equals()).toBeFalsy(); expect(coll1.equals()).toBeFalsy();
}); });
@@ -200,9 +199,9 @@ describe('every() tests', () => {
const coll = createTestCollection(); const coll = createTestCollection();
test('throws if fn is not a function', () => { test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.every()); expectInvalidFunctionError(() => coll.every());
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.every(123), 123); expectInvalidFunctionError(() => coll.every(123), 123);
}); });
@@ -226,9 +225,9 @@ describe('filter() tests', () => {
const coll = createTestCollection(); const coll = createTestCollection();
test('throws if fn is not a function', () => { test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.filter()); expectInvalidFunctionError(() => coll.filter());
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.filter(123), 123); expectInvalidFunctionError(() => coll.filter(123), 123);
}); });
@@ -253,9 +252,9 @@ describe('find() tests', () => {
const coll = createTestCollection(); const coll = createTestCollection();
test('throws if fn is not a function', () => { test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => createCollection().find()); expectInvalidFunctionError(() => createCollection().find());
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => createCollection().find(123), 123); expectInvalidFunctionError(() => createCollection().find(123), 123);
}); });
@@ -277,9 +276,9 @@ describe('findKey() tests', () => {
const coll = createTestCollection(); const coll = createTestCollection();
test('throws if fn is not a function', () => { test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.findKey()); expectInvalidFunctionError(() => coll.findKey());
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.findKey(123), 123); expectInvalidFunctionError(() => coll.findKey(123), 123);
}); });
@@ -508,9 +507,9 @@ describe('map() tests', () => {
const coll = createTestCollection(); const coll = createTestCollection();
test('throws if fn is not a function', () => { test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.map()); expectInvalidFunctionError(() => coll.map());
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.map(123), 123); expectInvalidFunctionError(() => coll.map(123), 123);
}); });
@@ -531,9 +530,9 @@ describe('mapValues() tests', () => {
const coll = createTestCollection(); const coll = createTestCollection();
test('throws if fn is not a function', () => { test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.mapValues()); expectInvalidFunctionError(() => coll.mapValues());
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.mapValues(123), 123); expectInvalidFunctionError(() => coll.mapValues(123), 123);
}); });
@@ -608,9 +607,9 @@ describe('partition() tests', () => {
const coll = createTestCollection(); const coll = createTestCollection();
test('throws if fn is not a function', () => { test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.partition()); expectInvalidFunctionError(() => coll.partition());
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.partition(123), 123); expectInvalidFunctionError(() => coll.partition(123), 123);
}); });
@@ -692,9 +691,9 @@ describe('reduce() tests', () => {
const coll = createTestCollection(); const coll = createTestCollection();
test('throws if fn is not a function', () => { test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.reduce()); expectInvalidFunctionError(() => coll.reduce());
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.reduce(123), 123); expectInvalidFunctionError(() => coll.reduce(123), 123);
}); });
@@ -731,9 +730,9 @@ describe('some() tests', () => {
const coll = createTestCollection(); const coll = createTestCollection();
test('throws if fn is not a function', () => { test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.some()); expectInvalidFunctionError(() => coll.some());
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.some(123), 123); expectInvalidFunctionError(() => coll.some(123), 123);
}); });
@@ -775,9 +774,9 @@ describe('sweep() test', () => {
const coll = createTestCollection(); const coll = createTestCollection();
test('throws if fn is not a function', () => { test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.sweep()); expectInvalidFunctionError(() => coll.sweep());
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.sweep(123), 123); expectInvalidFunctionError(() => coll.sweep(123), 123);
}); });
@@ -802,9 +801,9 @@ describe('tap() tests', () => {
const coll = createTestCollection(); const coll = createTestCollection();
test('throws if fn is not a function', () => { test('throws if fn is not a function', () => {
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.tap()); expectInvalidFunctionError(() => coll.tap());
// @ts-expect-error: invalid function // @ts-expect-error: Invalid function
expectInvalidFunctionError(() => coll.tap(123), 123); expectInvalidFunctionError(() => coll.tap(123), 123);
}); });

View File

@@ -85,12 +85,10 @@ export class Collection<K, V> extends Map<K, V> {
public first(): V | undefined; public first(): V | undefined;
public first(amount: number): V[]; public first(amount: number): V[];
public first(amount?: number): V | V[] | undefined { public first(amount?: number): V | V[] | undefined {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
if (typeof amount === 'undefined') return this.values().next().value; if (typeof amount === 'undefined') return this.values().next().value;
if (amount < 0) return this.last(amount * -1); if (amount < 0) return this.last(amount * -1);
amount = Math.min(this.size, amount); amount = Math.min(this.size, amount);
const iter = this.values(); const iter = this.values();
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return Array.from({ length: amount }, (): V => iter.next().value); return Array.from({ length: amount }, (): V => iter.next().value);
} }
@@ -104,12 +102,10 @@ export class Collection<K, V> extends Map<K, V> {
public firstKey(): K | undefined; public firstKey(): K | undefined;
public firstKey(amount: number): K[]; public firstKey(amount: number): K[];
public firstKey(amount?: number): K | K[] | undefined { public firstKey(amount?: number): K | K[] | undefined {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
if (typeof amount === 'undefined') return this.keys().next().value; if (typeof amount === 'undefined') return this.keys().next().value;
if (amount < 0) return this.lastKey(amount * -1); if (amount < 0) return this.lastKey(amount * -1);
amount = Math.min(this.size, amount); amount = Math.min(this.size, amount);
const iter = this.keys(); const iter = this.keys();
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return Array.from({ length: amount }, (): K => iter.next().value); return Array.from({ length: amount }, (): K => iter.next().value);
} }
@@ -426,9 +422,7 @@ export class Collection<K, V> extends Map<K, V> {
if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg); if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
const iter = this.entries(); const iter = this.entries();
return Array.from({ length: this.size }, (): T => { return Array.from({ length: this.size }, (): T => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const [key, value] = iter.next().value; const [key, value] = iter.next().value;
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
return fn(value, key, this); return fn(value, key, this);
}); });
} }
@@ -636,7 +630,6 @@ export class Collection<K, V> extends Map<K, V> {
* @returns Whether the collections have identical contents * @returns Whether the collections have identical contents
*/ */
public equals(collection: ReadonlyCollection<K, V>) { public equals(collection: ReadonlyCollection<K, V>) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!collection) return false; // runtime check if (!collection) return false; // runtime check
if (this === collection) return true; if (this === collection) return true;
if (this.size !== collection.size) return false; if (this.size !== collection.size) return false;

View File

@@ -123,7 +123,6 @@ export class Documentation {
case 'Method': { case 'Method': {
const event = prop?.groups?.find((group) => group.title === 'Events'); const event = prop?.groups?.find((group) => group.title === 'Events');
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if ((event?.children as unknown as number[])?.includes(member.id)) { if ((event?.children as unknown as number[])?.includes(member.id)) {
item = new DocumentedEvent(member, this.config); item = new DocumentedEvent(member, this.config);
break; break;
@@ -139,7 +138,6 @@ export class Documentation {
} }
default: { default: {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
console.warn(`- Unknown documentation kind "${member.kindString}" - \n${JSON.stringify(member)}\n`); console.warn(`- Unknown documentation kind "${member.kindString}" - \n${JSON.stringify(member)}\n`);
} }
} }
@@ -212,7 +210,6 @@ export class Documentation {
default: { default: {
// @ts-expect-error: This is a valid case // @ts-expect-error: This is a valid case
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
console.warn(`- Unknown documentation kind "${member.kind}" - \n${JSON.stringify(member)}\n`); console.warn(`- Unknown documentation kind "${member.kind}" - \n${JSON.stringify(member)}\n`);
} }
} }
@@ -233,7 +230,6 @@ export class Documentation {
const info = []; const info = [];
const name = (member.name || item?.data.name) ?? 'UNKNOWN'; const name = (member.name || item?.data.name) ?? 'UNKNOWN';
// @ts-expect-error: Typescript can't infer this // @ts-expect-error: Typescript can't infer this
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unnecessary-condition
const memberof = member.memberof ?? item?.data?.memberof; const memberof = member.memberof ?? item?.data?.memberof;
const meta = const meta =
member.kind === 'constructor' member.kind === 'constructor'

View File

@@ -2,9 +2,9 @@ import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, extname, basename, relative } from 'node:path'; import { dirname, join, extname, basename, relative } from 'node:path';
import jsdoc2md from 'jsdoc-to-markdown'; import jsdoc2md from 'jsdoc-to-markdown';
import { type DeclarationReflection, Application, TSConfigReader } from 'typedoc'; import { type DeclarationReflection, Application, TSConfigReader } from 'typedoc';
import type { CLIOptions } from './cli'; import type { CLIOptions } from './cli.js';
import { Documentation } from './documentation.js'; import { Documentation } from './documentation.js';
import type { RootTypes, ChildTypes, CustomDocs } from './interfaces'; import type { RootTypes, ChildTypes, CustomDocs } from './interfaces/index.js';
interface CustomFiles { interface CustomFiles {
files: { files: {

View File

@@ -58,7 +58,6 @@ export class DocumentedClass extends DocumentedItem<Class | DeclarationReflectio
this.construct = item; this.construct = item;
} else if (item instanceof DocumentedMethod) { } else if (item instanceof DocumentedMethod) {
// @ts-expect-error: No type for methods // @ts-expect-error: No type for methods
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const prefix = item.data.scope === 'static' || item.data.flags?.isStatic ? 's-' : ''; const prefix = item.data.scope === 'static' || item.data.flags?.isStatic ? 's-' : '';
if (this.methods.has(prefix + item.data.name)) { if (this.methods.has(prefix + item.data.name)) {
throw new Error(`Doc ${this.data.name} already has method ${item.data.name}`); throw new Error(`Doc ${this.data.name} already has method ${item.data.name}`);
@@ -91,7 +90,6 @@ export class DocumentedClass extends DocumentedItem<Class | DeclarationReflectio
meta = new DocumentedItemMeta(sources, this.config).serialize(); meta = new DocumentedItemMeta(sources, this.config).serialize();
} }
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length
? signature.comment.blockTags ? signature.comment.blockTags
.filter((block) => block.tag === '@see') .filter((block) => block.tag === '@see')
@@ -100,7 +98,6 @@ export class DocumentedClass extends DocumentedItem<Class | DeclarationReflectio
return { return {
// @ts-expect-error: Type cannot be inferred // @ts-expect-error: Type cannot be inferred
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
name: signature.name === 'default' ? parse(meta?.file ?? 'default').name : signature.name, name: signature.name === 'default' ? parse(meta?.file ?? 'default').name : signature.name,
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: signature.comment?.summary.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined, description: signature.comment?.summary.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
@@ -109,13 +106,11 @@ export class DocumentedClass extends DocumentedItem<Class | DeclarationReflectio
implements: this.implements?.serialize(), implements: this.implements?.serialize(),
access: access:
data.flags.isPrivate || data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal') signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private' ? 'private'
: undefined, : undefined,
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, @typescript-eslint/no-unnecessary-condition // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
abstract: signature.comment?.blockTags?.some((block) => block.tag === '@abstract') || undefined, abstract: signature.comment?.blockTags?.some((block) => block.tag === '@abstract') || undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated') deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? signature.comment.blockTags ? signature.comment.blockTags
.find((block) => block.tag === '@deprecated') .find((block) => block.tag === '@deprecated')

View File

@@ -9,7 +9,6 @@ export class DocumentedConstructor extends DocumentedItem<Constructor | Declarat
const data = this.data as DeclarationReflection; const data = this.data as DeclarationReflection;
const signature = (data.signatures ?? [])[0] ?? data; const signature = (data.signatures ?? [])[0] ?? data;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length
? signature.comment.blockTags ? signature.comment.blockTags
.filter((block) => block.tag === '@see') .filter((block) => block.tag === '@see')
@@ -18,12 +17,11 @@ export class DocumentedConstructor extends DocumentedItem<Constructor | Declarat
return { return {
name: signature.name, name: signature.name,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined, description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see, see,
access: access:
data.flags.isPrivate || data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal') signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private' ? 'private'
: undefined, : undefined,

View File

@@ -18,14 +18,12 @@ export class DocumentedEvent extends DocumentedItem<DeclarationReflection | Even
meta = new DocumentedItemMeta(sources, this.config).serialize(); meta = new DocumentedItemMeta(sources, this.config).serialize();
} }
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length
? signature.comment.blockTags ? signature.comment.blockTags
.filter((block) => block.tag === '@see') .filter((block) => block.tag === '@see')
.map((block) => block.content.find((contentText) => contentText.kind === 'text')?.text.trim()) .map((block) => block.content.find((contentText) => contentText.kind === 'text')?.text.trim())
: undefined; : undefined;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const examples = signature.comment?.blockTags?.filter((block) => block.tag === '@example').length const examples = signature.comment?.blockTags?.filter((block) => block.tag === '@example').length
? signature.comment.blockTags ? signature.comment.blockTags
.filter((block) => block.tag === '@example') .filter((block) => block.tag === '@example')
@@ -35,19 +33,16 @@ export class DocumentedEvent extends DocumentedItem<DeclarationReflection | Even
return { return {
// @ts-expect-error: No type for params // @ts-expect-error: No type for params
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
name: signature.parameters?.[0]?.type?.value, name: signature.parameters?.[0]?.type?.value,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined, description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see, see,
access: access:
data.flags.isPrivate || data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal') signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private' ? 'private'
: undefined, : undefined,
examples, examples,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated') deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? signature.comment.blockTags ? signature.comment.blockTags
.find((block) => block.tag === '@deprecated') .find((block) => block.tag === '@deprecated')
@@ -68,7 +63,6 @@ export class DocumentedEvent extends DocumentedItem<DeclarationReflection | Even
names: [parseType(signature.type)], names: [parseType(signature.type)],
description: description:
signature.comment?.blockTags signature.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns') ?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -81,7 +75,6 @@ export class DocumentedEvent extends DocumentedItem<DeclarationReflection | Even
: undefined, : undefined,
returnsDescription: returnsDescription:
signature.comment?.blockTags signature.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns') ?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')

View File

@@ -18,7 +18,6 @@ export class DocumentedMember extends DocumentedItem<DeclarationReflection | Mem
meta = new DocumentedItemMeta(sources, this.config).serialize(); meta = new DocumentedItemMeta(sources, this.config).serialize();
} }
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length
? signature.comment.blockTags ? signature.comment.blockTags
.filter((block) => block.tag === '@see') .filter((block) => block.tag === '@see')
@@ -27,20 +26,18 @@ export class DocumentedMember extends DocumentedItem<DeclarationReflection | Mem
const base = { const base = {
name: signature.name, name: signature.name,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined, description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see, see,
scope: data.flags.isStatic ? 'static' : undefined, scope: data.flags.isStatic ? 'static' : undefined,
access: access:
data.flags.isPrivate || data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal') signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private' ? 'private'
: undefined, : undefined,
readonly: data.flags.isReadonly, readonly: data.flags.isReadonly,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
abstract: signature.comment?.blockTags?.some((block) => block.tag === '@abstract') || undefined, abstract: signature.comment?.blockTags?.some((block) => block.tag === '@abstract') || undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated') deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? signature.comment.blockTags ? signature.comment.blockTags
.find((block) => block.tag === '@deprecated') .find((block) => block.tag === '@deprecated')
@@ -51,7 +48,6 @@ export class DocumentedMember extends DocumentedItem<DeclarationReflection | Mem
default: default:
(data.defaultValue === '...' ? undefined : data.defaultValue) ?? (data.defaultValue === '...' ? undefined : data.defaultValue) ??
(signature.comment?.blockTags (signature.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@default') ?.find((block) => block.tag === '@default')
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -76,7 +72,6 @@ export class DocumentedMember extends DocumentedItem<DeclarationReflection | Mem
base.readonly = true; base.readonly = true;
} }
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = getter.comment?.blockTags?.filter((block) => block.tag === '@see').length const see = getter.comment?.blockTags?.filter((block) => block.tag === '@see').length
? getter.comment.blockTags ? getter.comment.blockTags
.filter((block) => block.tag === '@see') .filter((block) => block.tag === '@see')
@@ -85,19 +80,17 @@ export class DocumentedMember extends DocumentedItem<DeclarationReflection | Mem
return { return {
...base, ...base,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: getter.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined, description: getter.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see, see,
access: access:
data.flags.isPrivate || data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
getter.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal') getter.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private' ? 'private'
: undefined, : undefined,
readonly: base.readonly || !hasSetter, readonly: base.readonly || !hasSetter,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
abstract: getter.comment?.blockTags?.some((block) => block.tag === '@abstract') || undefined, abstract: getter.comment?.blockTags?.some((block) => block.tag === '@abstract') || undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: getter.comment?.blockTags?.some((block) => block.tag === '@deprecated') deprecated: getter.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? getter.comment.blockTags ? getter.comment.blockTags
.find((block) => block.tag === '@deprecated') .find((block) => block.tag === '@deprecated')
@@ -108,7 +101,6 @@ export class DocumentedMember extends DocumentedItem<DeclarationReflection | Mem
default: default:
base.default ?? base.default ??
(getter.comment?.blockTags (getter.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@default') ?.find((block) => block.tag === '@default')
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')

View File

@@ -18,14 +18,12 @@ export class DocumentedMethod extends DocumentedItem<DeclarationReflection | Met
meta = new DocumentedItemMeta(sources, this.config).serialize(); meta = new DocumentedItemMeta(sources, this.config).serialize();
} }
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length
? signature.comment.blockTags ? signature.comment.blockTags
.filter((block) => block.tag === '@see') .filter((block) => block.tag === '@see')
.map((block) => block.content.find((innerContent) => innerContent.kind === 'text')?.text.trim()) .map((block) => block.content.find((innerContent) => innerContent.kind === 'text')?.text.trim())
: undefined; : undefined;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const examples = signature.comment?.blockTags?.filter((block) => block.tag === '@example').length const examples = signature.comment?.blockTags?.filter((block) => block.tag === '@example').length
? signature.comment.blockTags ? signature.comment.blockTags
.filter((block) => block.tag === '@example') .filter((block) => block.tag === '@example')
@@ -35,20 +33,18 @@ export class DocumentedMethod extends DocumentedItem<DeclarationReflection | Met
return { return {
name: signature.name, name: signature.name,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined, description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see, see,
scope: data.flags.isStatic ? 'static' : undefined, scope: data.flags.isStatic ? 'static' : undefined,
access: access:
data.flags.isPrivate || data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal') signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private' ? 'private'
: undefined, : undefined,
examples, examples,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
abstract: signature.comment?.blockTags?.some((block) => block.tag === '@abstract') || undefined, abstract: signature.comment?.blockTags?.some((block) => block.tag === '@abstract') || undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated') deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? signature.comment.blockTags ? signature.comment.blockTags
.find((block) => block.tag === '@deprecated') .find((block) => block.tag === '@deprecated')
@@ -56,7 +52,6 @@ export class DocumentedMethod extends DocumentedItem<DeclarationReflection | Met
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')
.trim() ?? true .trim() ?? true
: undefined, : undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
// emits: signature.comment?.blockTags?.filter((t) => t.tag === '@emits').map((t) => t.content), // emits: signature.comment?.blockTags?.filter((t) => t.tag === '@emits').map((t) => t.content),
// @ts-expect-error: Typescript doesn't know that this is a SignatureReflection // @ts-expect-error: Typescript doesn't know that this is a SignatureReflection
params: signature.parameters params: signature.parameters
@@ -71,7 +66,6 @@ export class DocumentedMethod extends DocumentedItem<DeclarationReflection | Met
names: [parseType(signature.type)], names: [parseType(signature.type)],
description: description:
signature.comment?.blockTags signature.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns') ?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -84,7 +78,6 @@ export class DocumentedMethod extends DocumentedItem<DeclarationReflection | Met
: undefined, : undefined,
returnsDescription: returnsDescription:
signature.comment?.blockTags signature.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns') ?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')

View File

@@ -11,13 +11,12 @@ export class DocumentedParam extends DocumentedItem<Param | ParameterReflection>
return { return {
name: data.name, name: data.name,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: data.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined, description: data.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
optional: data.flags.isOptional || typeof data.defaultValue !== 'undefined', optional: data.flags.isOptional || typeof data.defaultValue !== 'undefined',
default: default:
(data.defaultValue === '...' ? undefined : data.defaultValue) ?? (data.defaultValue === '...' ? undefined : data.defaultValue) ??
(data.comment?.blockTags (data.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@default') ?.find((block) => block.tag === '@default')
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')

View File

@@ -19,7 +19,6 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
meta = new DocumentedItemMeta(sources, this.config).serialize(); meta = new DocumentedItemMeta(sources, this.config).serialize();
} }
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length const see = signature.comment?.blockTags?.filter((block) => block.tag === '@see').length
? signature.comment.blockTags ? signature.comment.blockTags
.filter((block) => block.tag === '@see') .filter((block) => block.tag === '@see')
@@ -28,16 +27,14 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
const baseReturn = { const baseReturn = {
name: signature.name, name: signature.name,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined, description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see, see,
access: access:
data.flags.isPrivate || data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal') signature.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private' ? 'private'
: undefined, : undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated') deprecated: signature.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? signature.comment.blockTags ? signature.comment.blockTags
.find((block) => block.tag === '@deprecated') .find((block) => block.tag === '@deprecated')
@@ -64,7 +61,7 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
name: child.name, name: child.name,
description: description:
child.comment?.summary child.comment?.summary
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, no-param-reassign // eslint-disable-next-line no-param-reassign
?.reduce((prev, curr) => (prev += curr.text), '') ?.reduce((prev, curr) => (prev += curr.text), '')
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
.trim() || undefined, .trim() || undefined,
@@ -82,18 +79,17 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
name: child.name, name: child.name,
description: description:
child.comment?.summary child.comment?.summary
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, no-param-reassign // eslint-disable-next-line no-param-reassign
?.reduce((prev, curr) => (prev += curr.text), '') ?.reduce((prev, curr) => (prev += curr.text), '')
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
.trim() || .trim() ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
child.signatures?.[0]?.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || child.signatures?.[0]?.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() ||
undefined, undefined,
optional: child.flags.isOptional || typeof child.defaultValue !== 'undefined', optional: child.flags.isOptional || typeof child.defaultValue !== 'undefined',
default: default:
(child.defaultValue === '...' ? undefined : child.defaultValue) ?? (child.defaultValue === '...' ? undefined : child.defaultValue) ??
(child.comment?.blockTags (child.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@default') ?.find((block) => block.tag === '@default')
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -112,7 +108,6 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
}), }),
], ],
description: child.signatures?.[0]?.comment?.blockTags description: child.signatures?.[0]?.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns') ?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -134,13 +129,12 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
const params = sig?.parameters?.map((param) => ({ const params = sig?.parameters?.map((param) => ({
name: param.name, name: param.name,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: param.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined, description: param.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
optional: param.flags.isOptional || typeof param.defaultValue !== 'undefined', optional: param.flags.isOptional || typeof param.defaultValue !== 'undefined',
default: default:
(param.defaultValue === '...' ? undefined : param.defaultValue) ?? (param.defaultValue === '...' ? undefined : param.defaultValue) ??
(param.comment?.blockTags (param.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@default') ?.find((block) => block.tag === '@default')
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -152,7 +146,6 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
: undefined, : undefined,
})); }));
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const see = sig?.comment?.blockTags?.filter((block) => block.tag === '@see').length const see = sig?.comment?.blockTags?.filter((block) => block.tag === '@see').length
? sig.comment.blockTags ? sig.comment.blockTags
.filter((block) => block.tag === '@see') .filter((block) => block.tag === '@see')
@@ -161,16 +154,14 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
return { return {
...baseReturn, ...baseReturn,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing, no-param-reassign // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign
description: sig?.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined, description: sig?.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see, see,
access: access:
sig?.flags.isPrivate || sig?.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
sig?.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal') sig?.comment?.blockTags?.some((block) => block.tag === '@private' || block.tag === '@internal')
? 'private' ? 'private'
: undefined, : undefined,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: sig?.comment?.blockTags?.some((block) => block.tag === '@deprecated') deprecated: sig?.comment?.blockTags?.some((block) => block.tag === '@deprecated')
? sig.comment.blockTags ? sig.comment.blockTags
.find((block) => block.tag === '@deprecated') .find((block) => block.tag === '@deprecated')
@@ -186,7 +177,6 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
names: [parseType(sig.type)], names: [parseType(sig.type)],
description: description:
sig.comment?.blockTags sig.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns') ?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')
@@ -199,7 +189,6 @@ export class DocumentedTypeDef extends DocumentedItem<DeclarationReflection | Ty
: undefined, : undefined,
returnsDescription: returnsDescription:
sig?.comment?.blockTags sig?.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((block) => block.tag === '@returns') ?.find((block) => block.tag === '@returns')
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
?.content.reduce((prev, curr) => (prev += curr.text), '') ?.content.reduce((prev, curr) => (prev += curr.text), '')

View File

@@ -91,7 +91,6 @@ export function parseType(someType: JSONOutput.SomeType | JSONOutput.Type | stri
return `'${someType.value}'`; return `'${someType.value}'`;
} }
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return `${someType.value}`; return `${someType.value}`;
} }

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import type { JSONOutput } from 'typedoc'; import type { JSONOutput } from 'typedoc';
interface QueryType { interface QueryType {

View File

@@ -9,7 +9,6 @@ if (!process.env.DISCORD_TOKEN) {
// We want to let upstream handle retrying // We want to let upstream handle retrying
const api = new REST({ rejectOnRateLimit: () => true, retries: 0 }).setToken(process.env.DISCORD_TOKEN); const api = new REST({ rejectOnRateLimit: () => true, retries: 0 }).setToken(process.env.DISCORD_TOKEN);
// eslint-disable-next-line @typescript-eslint/no-misused-promises
const server = createServer(proxyRequests(api)); const server = createServer(proxyRequests(api));
const port = Number.parseInt(process.env.PORT ?? '8080', 10); const port = Number.parseInt(process.env.PORT ?? '8080', 10);

View File

@@ -16,7 +16,6 @@ const responseOptions: MockInterceptor.MockResponseOptions = {
}; };
const api = new REST().setToken('A-Very-Fake-Token'); const api = new REST().setToken('A-Very-Fake-Token');
// eslint-disable-next-line @typescript-eslint/no-misused-promises
const server = createServer(proxyRequests(api)); const server = createServer(proxyRequests(api));
beforeEach(() => { beforeEach(() => {

View File

@@ -58,7 +58,6 @@ const sublimit = { body: { name: 'newname' } };
const noSublimit = { body: { bitrate: 40_000 } }; const noSublimit = { body: { bitrate: 40_000 } };
function startSublimitIntervals() { function startSublimitIntervals() {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!sublimitIntervals.reset) { if (!sublimitIntervals.reset) {
sublimitResetAfter = Date.now() + 250; sublimitResetAfter = Date.now() + 250;
sublimitIntervals.reset = setInterval(() => { sublimitIntervals.reset = setInterval(() => {
@@ -67,7 +66,6 @@ function startSublimitIntervals() {
}, 250); }, 250);
} }
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!sublimitIntervals.retry) { if (!sublimitIntervals.retry) {
retryAfter = Date.now() + 1_000; retryAfter = Date.now() + 1_000;
sublimitIntervals.retry = setInterval(() => { sublimitIntervals.retry = setInterval(() => {

View File

@@ -62,7 +62,7 @@ test('resolveBody', async () => {
}; };
await expect(resolveBody(asyncIterable)).resolves.toStrictEqual(Buffer.from([1, 2, 3, 1, 2, 3, 1, 2, 3])); await expect(resolveBody(asyncIterable)).resolves.toStrictEqual(Buffer.from([1, 2, 3, 1, 2, 3, 1, 2, 3]));
// unknown type // Unknown type
// @ts-expect-error This test is ensuring that this throws // @ts-expect-error: This test is ensuring that this throws
await expect(resolveBody(true)).rejects.toThrow(TypeError); await expect(resolveBody(true)).rejects.toThrow(TypeError);
}); });

View File

@@ -11,7 +11,7 @@ import {
type RequestData, type RequestData,
type RouteLike, type RouteLike,
} from './RequestManager.js'; } from './RequestManager.js';
import type { IHandler } from './handlers/IHandler'; import type { IHandler } from './handlers/IHandler.js';
import { DefaultRestOptions, RESTEvents } from './utils/constants.js'; import { DefaultRestOptions, RESTEvents } from './utils/constants.js';
import { parseResponse } from './utils/utils.js'; import { parseResponse } from './utils/utils.js';

View File

@@ -5,8 +5,8 @@ import type { URLSearchParams } from 'node:url';
import { Collection } from '@discordjs/collection'; import { Collection } from '@discordjs/collection';
import { DiscordSnowflake } from '@sapphire/snowflake'; import { DiscordSnowflake } from '@sapphire/snowflake';
import { FormData, type RequestInit, type BodyInit, type Dispatcher, type Agent } from 'undici'; import { FormData, type RequestInit, type BodyInit, type Dispatcher, type Agent } from 'undici';
import type { RESTOptions, RestEvents, RequestOptions } from './REST'; import type { RESTOptions, RestEvents, RequestOptions } from './REST.js';
import type { IHandler } from './handlers/IHandler'; import type { IHandler } from './handlers/IHandler.js';
import { SequentialHandler } from './handlers/SequentialHandler.js'; import { SequentialHandler } from './handlers/SequentialHandler.js';
import { DefaultRestOptions, DefaultUserAgent, RESTEvents } from './utils/constants.js'; import { DefaultRestOptions, DefaultUserAgent, RESTEvents } from './utils/constants.js';
import { resolveBody } from './utils/utils.js'; import { resolveBody } from './utils/utils.js';
@@ -208,7 +208,6 @@ export class RequestManager extends EventEmitter {
*/ */
public readonly handlers = new Collection<string, IHandler>(); public readonly handlers = new Collection<string, IHandler>();
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
#token: string | null = null; #token: string | null = null;
private hashTimer!: NodeJS.Timer; private hashTimer!: NodeJS.Timer;
@@ -422,7 +421,6 @@ export class RequestManager extends EventEmitter {
const contentType = file.contentType ?? (await fileTypeFromBuffer(file.data))?.mime; const contentType = file.contentType ?? (await fileTypeFromBuffer(file.data))?.mime;
formData.append(fileKey, new Blob([file.data], { type: contentType }), file.name); formData.append(fileKey, new Blob([file.data], { type: contentType }), file.name);
} else { } else {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
formData.append(fileKey, new Blob([`${file.data}`], { type: file.contentType }), file.name); formData.append(fileKey, new Blob([`${file.data}`], { type: file.contentType }), file.name);
} }
} }
@@ -457,7 +455,6 @@ export class RequestManager extends EventEmitter {
finalBody = await resolveBody(finalBody); finalBody = await resolveBody(finalBody);
const fetchOptions: RequestOptions = { const fetchOptions: RequestOptions = {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
headers: { ...request.headers, ...additionalHeaders, ...headers } as Record<string, string>, headers: { ...request.headers, ...additionalHeaders, ...headers } as Record<string, string>,
method: request.method.toUpperCase() as Dispatcher.HttpMethod, method: request.method.toUpperCase() as Dispatcher.HttpMethod,
}; };

View File

@@ -101,13 +101,11 @@ export class DiscordAPIError extends Error {
if (typeof val === 'string') { if (typeof val === 'string') {
yield val; yield val;
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
} else if (isErrorGroupWrapper(val)) { } else if (isErrorGroupWrapper(val)) {
for (const error of val._errors) { for (const error of val._errors) {
yield* this.flattenDiscordError(error, nextKey); yield* this.flattenDiscordError(error, nextKey);
} }
} else { } else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
yield* this.flattenDiscordError(val, nextKey); yield* this.flattenDiscordError(val, nextKey);
} }
} }

View File

@@ -10,7 +10,6 @@ export interface IHandler {
/** /**
* If the bucket is currently inactive (no pending requests) * If the bucket is currently inactive (no pending requests)
*/ */
// eslint-disable-next-line @typescript-eslint/method-signature-style -- This is meant to be a getter returning a bool
get inactive(): boolean; get inactive(): boolean;
/** /**
* Queues a request to be sent * Queues a request to be sent

View File

@@ -53,25 +53,21 @@ export class SequentialHandler implements IHandler {
/** /**
* The interface used to sequence async requests sequentially * The interface used to sequence async requests sequentially
*/ */
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
#asyncQueue = new AsyncQueue(); #asyncQueue = new AsyncQueue();
/** /**
* The interface used to sequence sublimited async requests sequentially * The interface used to sequence sublimited async requests sequentially
*/ */
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
#sublimitedQueue: AsyncQueue | null = null; #sublimitedQueue: AsyncQueue | null = null;
/** /**
* A promise wrapper for when the sublimited queue is finished being processed or null when not being processed * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed
*/ */
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
#sublimitPromise: { promise: Promise<void>; resolve(): void } | null = null; #sublimitPromise: { promise: Promise<void>; resolve(): void } | null = null;
/** /**
* Whether the sublimit queue needs to be shifted in the finally block * Whether the sublimit queue needs to be shifted in the finally block
*/ */
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
#shiftSublimit = false; #shiftSublimit = false;
/** /**

View File

@@ -2,10 +2,9 @@ import process from 'node:process';
import { APIVersion } from 'discord-api-types/v10'; import { APIVersion } from 'discord-api-types/v10';
import { getGlobalDispatcher } from 'undici'; import { getGlobalDispatcher } from 'undici';
import type { RESTOptions } from '../REST.js'; import type { RESTOptions } from '../REST.js';
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
const Package = require('../../../package.json'); const Package = require('../../../package.json');
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-unsafe-member-access
export const DefaultUserAgent = `DiscordBot (${Package.homepage}, ${Package.version})`; export const DefaultUserAgent = `DiscordBot (${Package.homepage}, ${Package.version})`;
export const DefaultRestOptions: Required<RESTOptions> = { export const DefaultRestOptions: Required<RESTOptions> = {

View File

@@ -113,7 +113,6 @@ export async function resolveBody(body: RequestInit['body']): Promise<RequestOpt
return new Uint8Array(await body.arrayBuffer()); return new Uint8Array(await body.arrayBuffer());
} else if (body instanceof FormData) { } else if (body instanceof FormData) {
return body; return body;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
} else if ((body as Iterable<Uint8Array>)[Symbol.iterator]) { } else if ((body as Iterable<Uint8Array>)[Symbol.iterator]) {
const chunks = [...(body as Iterable<Uint8Array>)]; const chunks = [...(body as Iterable<Uint8Array>)];
const length = chunks.reduce((a, b) => a + b.length, 0); const length = chunks.reduce((a, b) => a + b.length, 0);
@@ -126,7 +125,6 @@ export async function resolveBody(body: RequestInit['body']): Promise<RequestOpt
lengthUsed += b.length; lengthUsed += b.length;
return a; return a;
}, uint8); }, uint8);
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
} else if ((body as AsyncIterable<Uint8Array>)[Symbol.asyncIterator]) { } else if ((body as AsyncIterable<Uint8Array>)[Symbol.asyncIterator]) {
const chunks: Uint8Array[] = []; const chunks: Uint8Array[] = [];

View File

@@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/unbound-method */ /* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/dot-notation */ /* eslint-disable @typescript-eslint/dot-notation */
import { Buffer } from 'node:buffer'; import { Buffer } from 'node:buffer';
import { once } from 'node:events'; import { once } from 'node:events';
@@ -8,7 +6,7 @@ import process from 'node:process';
import { Readable } from 'node:stream'; import { Readable } from 'node:stream';
import { addAudioPlayer, deleteAudioPlayer } from '../src/DataStore'; import { addAudioPlayer, deleteAudioPlayer } from '../src/DataStore';
import { VoiceConnection, VoiceConnectionStatus } from '../src/VoiceConnection'; import { VoiceConnection, VoiceConnectionStatus } from '../src/VoiceConnection';
import { createAudioPlayer, AudioPlayerStatus, SILENCE_FRAME, type AudioPlayerState } from '../src/audio/AudioPlayer'; import { createAudioPlayer, AudioPlayerStatus, SILENCE_FRAME } from '../src/audio/AudioPlayer';
import { AudioPlayerError } from '../src/audio/AudioPlayerError'; import { AudioPlayerError } from '../src/audio/AudioPlayerError';
import { AudioResource } from '../src/audio/AudioResource'; import { AudioResource } from '../src/audio/AudioResource';
import { NoSubscriberBehavior } from '../src/index'; import { NoSubscriberBehavior } from '../src/index';
@@ -23,7 +21,6 @@ const AudioPlayerErrorMock = AudioPlayerError as unknown as jest.Mock<typeof Aud
const VoiceConnectionMock = VoiceConnection as unknown as jest.Mock<VoiceConnection>; const VoiceConnectionMock = VoiceConnection as unknown as jest.Mock<VoiceConnection>;
function* silence() { function* silence() {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
while (true) { while (true) {
yield Buffer.from([0xf8, 0xff, 0xfe]); yield Buffer.from([0xf8, 0xff, 0xfe]);
} }

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
import { Buffer } from 'node:buffer'; import { Buffer } from 'node:buffer';
import process from 'node:process'; import process from 'node:process';
import { PassThrough, Readable } from 'node:stream'; import { PassThrough, Readable } from 'node:stream';
@@ -26,7 +25,7 @@ async function started(resource: AudioResource) {
const findPipeline = _findPipeline as unknown as jest.MockedFunction<typeof _findPipeline>; const findPipeline = _findPipeline as unknown as jest.MockedFunction<typeof _findPipeline>;
beforeAll(() => { beforeAll(() => {
// @ts-expect-error no type // @ts-expect-error: No type
findPipeline.mockImplementation((from: StreamType, constraint: (path: Edge[]) => boolean) => { findPipeline.mockImplementation((from: StreamType, constraint: (path: Edge[]) => boolean) => {
const base = [ const base = [
{ {
@@ -38,7 +37,6 @@ beforeAll(() => {
if (constraint === VOLUME_CONSTRAINT) { if (constraint === VOLUME_CONSTRAINT) {
base.push({ base.push({
cost: 1, cost: 1,
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
transformer: () => new VolumeTransformer({} as any), transformer: () => new VolumeTransformer({} as any),
type: TransformerType.InlineVolume, type: TransformerType.InlineVolume,
}); });
@@ -98,7 +96,6 @@ describe('createAudioResource', () => {
}); });
test('Infers from VolumeTransformer', () => { test('Infers from VolumeTransformer', () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const stream = new VolumeTransformer({} as any); const stream = new VolumeTransformer({} as any);
const resource = createAudioResource(stream, { inlineVolume: true }); const resource = createAudioResource(stream, { inlineVolume: true });
expect(findPipeline).toHaveBeenCalledWith(StreamType.Raw, NO_CONSTRAINT); expect(findPipeline).toHaveBeenCalledWith(StreamType.Raw, NO_CONSTRAINT);

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/dot-notation */ /* eslint-disable @typescript-eslint/dot-notation */
import { GatewayOpcodes } from 'discord-api-types/v10'; import { GatewayOpcodes } from 'discord-api-types/v10';
import * as DataStore from '../src/DataStore'; import * as DataStore from '../src/DataStore';

View File

@@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */ import { type EventEmitter, once } from 'node:events';
import type EventEmitter from 'node:events';
import { once } from 'node:events';
import process from 'node:process'; import process from 'node:process';
import { SSRCMap, type VoiceUserData } from '../src/receive/SSRCMap'; import { SSRCMap, type VoiceUserData } from '../src/receive/SSRCMap';

View File

@@ -1,10 +1,6 @@
/* eslint-disable @typescript-eslint/unbound-method */ /* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
/* eslint-disable @typescript-eslint/dot-notation */ /* eslint-disable @typescript-eslint/dot-notation */
import EventEmitter from 'node:events'; import { EventEmitter } from 'node:events';
import * as _DataStore from '../src/DataStore'; import * as _DataStore from '../src/DataStore';
import { import {
createVoiceConnection, createVoiceConnection,

View File

@@ -1,5 +1,4 @@
/* eslint-disable id-length */ /* eslint-disable id-length */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/dot-notation */ /* eslint-disable @typescript-eslint/dot-notation */
import { Buffer } from 'node:buffer'; import { Buffer } from 'node:buffer';
import { once } from 'node:events'; import { once } from 'node:events';
@@ -39,7 +38,6 @@ describe('VoiceReceiver', () => {
let receiver: VoiceReceiver; let receiver: VoiceReceiver;
beforeEach(() => { beforeEach(() => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
voiceConnection = new VoiceConnection({} as any, {} as any); voiceConnection = new VoiceConnection({} as any, {} as any);
voiceConnection.state = { voiceConnection.state = {
status: VoiceConnectionStatus.Signalling, status: VoiceConnectionStatus.Signalling,

View File

@@ -1,9 +1,6 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-empty-function */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Buffer } from 'node:buffer'; import { Buffer } from 'node:buffer';
import { createSocket as _createSocket } from 'node:dgram'; import { createSocket as _createSocket } from 'node:dgram';
import EventEmitter, { once } from 'node:events'; import { EventEmitter } from 'node:events';
import { VoiceUDPSocket } from '../src/networking/VoiceUDPSocket'; import { VoiceUDPSocket } from '../src/networking/VoiceUDPSocket';
jest.mock('node:dgram'); jest.mock('node:dgram');

View File

@@ -1,5 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { type EventEmitter, once } from 'node:events'; import { type EventEmitter, once } from 'node:events';
import { VoiceOpcodes } from 'discord-api-types/voice/v4'; import { VoiceOpcodes } from 'discord-api-types/voice/v4';
import WS from 'jest-websocket-mock'; import WS from 'jest-websocket-mock';
@@ -115,7 +113,6 @@ describe.skip('VoiceWebSocket: heartbeating', () => {
const endpoint = 'ws://localhost:1234'; const endpoint = 'ws://localhost:1234';
const server = new WS(endpoint, { jsonProtocol: true }); const server = new WS(endpoint, { jsonProtocol: true });
const ws = new VoiceWebSocket(endpoint, false); const ws = new VoiceWebSocket(endpoint, false);
// eslint-disable-next-line @typescript-eslint/no-empty-function
ws.on('error', () => {}); ws.on('error', () => {});
await server.connected; await server.connected;
const rcv = onceIgnoreError(ws, 'close'); const rcv = onceIgnoreError(ws, 'close');

View File

@@ -1,6 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { Buffer } from 'node:buffer'; import { Buffer } from 'node:buffer';
import EventEmitter, { once } from 'node:events'; import EventEmitter, { once } from 'node:events';
import process from 'node:process'; import process from 'node:process';
@@ -27,8 +24,7 @@ async function* gen(num: number) {
} }
function range(num: number) { function range(num: number) {
// eslint-disable-next-line unicorn/no-new-array return Buffer.from(Array.from(Array.from({ length: num }).keys()));
return Buffer.from(Array.from(new Array(num).keys()));
} }
const validHead = Buffer.from([ const validHead = Buffer.from([
@@ -80,7 +76,6 @@ describe('demuxProbe', () => {
test('Detects WebM', async () => { test('Detects WebM', async () => {
const stream = Readable.from(gen(10), { objectMode: false }); const stream = Readable.from(gen(10), { objectMode: false });
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
webmWrite.mockImplementation(function mock(data: Buffer) { webmWrite.mockImplementation(function mock(data: Buffer) {
if (data[0] === 5) this.emit('head', validHead); if (data[0] === 5) this.emit('head', validHead);
} as any); } as any);
@@ -91,7 +86,6 @@ describe('demuxProbe', () => {
test('Detects Ogg', async () => { test('Detects Ogg', async () => {
const stream = Readable.from(gen(10), { objectMode: false }); const stream = Readable.from(gen(10), { objectMode: false });
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
oggWrite.mockImplementation(function mock(data: Buffer) { oggWrite.mockImplementation(function mock(data: Buffer) {
if (data[0] === 5) this.emit('head', validHead); if (data[0] === 5) this.emit('head', validHead);
} as any); } as any);
@@ -102,7 +96,6 @@ describe('demuxProbe', () => {
test('Rejects invalid OpusHead', async () => { test('Rejects invalid OpusHead', async () => {
const stream = Readable.from(gen(10), { objectMode: false }); const stream = Readable.from(gen(10), { objectMode: false });
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
oggWrite.mockImplementation(function mock(data: Buffer) { oggWrite.mockImplementation(function mock(data: Buffer) {
if (data[0] === 5) this.emit('head', invalidHead); if (data[0] === 5) this.emit('head', invalidHead);
} as any); } as any);

View File

@@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */ import { EventEmitter } from 'node:events';
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import EventEmitter from 'node:events';
import process from 'node:process'; import process from 'node:process';
import { VoiceConnectionStatus, type VoiceConnection } from '../src/VoiceConnection'; import { VoiceConnectionStatus, type VoiceConnection } from '../src/VoiceConnection';
import { entersState } from '../src/util/entersState'; import { entersState } from '../src/util/entersState';
@@ -19,7 +17,6 @@ describe('entersState', () => {
test('Returns the target once the state has been entered before timeout', async () => { test('Returns the target once the state has been entered before timeout', async () => {
jest.useRealTimers(); jest.useRealTimers();
const vc = createFakeVoiceConnection(); const vc = createFakeVoiceConnection();
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
process.nextTick(() => vc.emit(VoiceConnectionStatus.Ready, null as any, null as any)); process.nextTick(() => vc.emit(VoiceConnectionStatus.Ready, null as any, null as any));
const result = await entersState(vc, VoiceConnectionStatus.Ready, 1_000); const result = await entersState(vc, VoiceConnectionStatus.Ready, 1_000);
expect(result).toEqual(vc); expect(result).toEqual(vc);
@@ -36,7 +33,6 @@ describe('entersState', () => {
jest.useRealTimers(); jest.useRealTimers();
const vc = createFakeVoiceConnection(); const vc = createFakeVoiceConnection();
const ac = new AbortController(); const ac = new AbortController();
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
process.nextTick(() => vc.emit(VoiceConnectionStatus.Ready, null as any, null as any)); process.nextTick(() => vc.emit(VoiceConnectionStatus.Ready, null as any, null as any));
const result = await entersState(vc, VoiceConnectionStatus.Ready, ac.signal); const result = await entersState(vc, VoiceConnectionStatus.Ready, ac.signal);
expect(result).toEqual(vc); expect(result).toEqual(vc);

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
import * as VoiceConnection from '../src/VoiceConnection'; import * as VoiceConnection from '../src/VoiceConnection';
import { joinVoiceChannel } from '../src/joinVoiceChannel'; import { joinVoiceChannel } from '../src/joinVoiceChannel';

View File

@@ -4,7 +4,6 @@ import Discord, { Interaction, Constants } from 'discord.js';
import { deploy } from './deploy'; import { deploy } from './deploy';
import { interactionHandlers } from './interactions'; import { interactionHandlers } from './interactions';
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
const { token } = require('../auth.json') as { token: string }; const { token } = require('../auth.json') as { token: string };
const client = new Discord.Client({ const client = new Discord.Client({

View File

@@ -1,6 +1,6 @@
import { GatewayOpcodes } from 'discord-api-types/v10'; import { GatewayOpcodes } from 'discord-api-types/v10';
import type { VoiceConnection } from './VoiceConnection'; import type { VoiceConnection } from './VoiceConnection';
import type { AudioPlayer } from './audio'; import type { AudioPlayer } from './audio/index';
export interface JoinConfig { export interface JoinConfig {
channelId: string | null; channelId: string | null;

View File

@@ -325,7 +325,6 @@ export class VoiceConnection extends EventEmitter {
this.emit('stateChange', oldState, newState); this.emit('stateChange', oldState, newState);
if (oldState.status !== newState.status) { if (oldState.status !== newState.status) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this.emit(newState.status, oldState, newState as any); this.emit(newState.status, oldState, newState as any);
} }
} }
@@ -391,7 +390,6 @@ export class VoiceConnection extends EventEmitter {
newUdp?.on('message', this.receiver.onUdpMessage); newUdp?.on('message', this.receiver.onUdpMessage);
} }
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.receiver.connectionData = Reflect.get(newState, 'connectionData') ?? {}; this.receiver.connectionData = Reflect.get(newState, 'connectionData') ?? {};
} }

View File

@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/prefer-ts-expect-error, @typescript-eslint/method-signature-style */ /* eslint-disable @typescript-eslint/prefer-ts-expect-error, @typescript-eslint/method-signature-style */
import { Buffer } from 'node:buffer'; import { Buffer } from 'node:buffer';
import EventEmitter from 'node:events'; import { EventEmitter } from 'node:events';
import { addAudioPlayer, deleteAudioPlayer } from '../DataStore'; import { addAudioPlayer, deleteAudioPlayer } from '../DataStore';
import { VoiceConnectionStatus, type VoiceConnection } from '../VoiceConnection'; import { VoiceConnectionStatus, type VoiceConnection } from '../VoiceConnection';
import { noop } from '../util/util'; import { noop } from '../util/util';
@@ -356,7 +356,6 @@ export class AudioPlayer extends EventEmitter {
this.emit('stateChange', oldState, this._state); this.emit('stateChange', oldState, this._state);
if (oldState.status !== newState.status || didChangeResources) { if (oldState.status !== newState.status || didChangeResources) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this.emit(newState.status, oldState, this._state as any); this.emit(newState.status, oldState, this._state as any);
} }
@@ -600,7 +599,6 @@ export class AudioPlayer extends EventEmitter {
*/ */
const packet: Buffer | null = state.resource.read(); const packet: Buffer | null = state.resource.read();
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (state.status === AudioPlayerStatus.Playing) { if (state.status === AudioPlayerStatus.Playing) {
if (packet) { if (packet) {
this._preparePacket(packet, playable, state); this._preparePacket(packet, playable, state);

View File

@@ -387,22 +387,16 @@ export class Networking extends EventEmitter {
* @param packet - The received packet * @param packet - The received packet
*/ */
private onWsPacket(packet: any) { private onWsPacket(packet: any) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (packet.op === VoiceOpcodes.Hello && this.state.code !== NetworkingStatusCode.Closed) { if (packet.op === VoiceOpcodes.Hello && this.state.code !== NetworkingStatusCode.Closed) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
this.state.ws.setHeartbeatInterval(packet.d.heartbeat_interval); this.state.ws.setHeartbeatInterval(packet.d.heartbeat_interval);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
} else if (packet.op === VoiceOpcodes.Ready && this.state.code === NetworkingStatusCode.Identifying) { } else if (packet.op === VoiceOpcodes.Ready && this.state.code === NetworkingStatusCode.Identifying) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
const { ip, port, ssrc, modes } = packet.d; const { ip, port, ssrc, modes } = packet.d;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const udp = new VoiceUDPSocket({ ip, port }); const udp = new VoiceUDPSocket({ ip, port });
udp.on('error', this.onChildError); udp.on('error', this.onChildError);
udp.on('debug', this.onUdpDebug); udp.on('debug', this.onUdpDebug);
udp.once('close', this.onUdpClose); udp.once('close', this.onUdpClose);
udp udp
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
.performIPDiscovery(ssrc) .performIPDiscovery(ssrc)
// eslint-disable-next-line promise/prefer-await-to-then // eslint-disable-next-line promise/prefer-await-to-then
.then((localConfig) => { .then((localConfig) => {
@@ -414,7 +408,6 @@ export class Networking extends EventEmitter {
data: { data: {
address: localConfig.ip, address: localConfig.ip,
port: localConfig.port, port: localConfig.port,
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
mode: chooseEncryptionMode(modes), mode: chooseEncryptionMode(modes),
}, },
}, },
@@ -432,25 +425,20 @@ export class Networking extends EventEmitter {
code: NetworkingStatusCode.UdpHandshaking, code: NetworkingStatusCode.UdpHandshaking,
udp, udp,
connectionData: { connectionData: {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
ssrc, ssrc,
}, },
}; };
} else if ( } else if (
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
packet.op === VoiceOpcodes.SessionDescription && packet.op === VoiceOpcodes.SessionDescription &&
this.state.code === NetworkingStatusCode.SelectingProtocol this.state.code === NetworkingStatusCode.SelectingProtocol
) { ) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
const { mode: encryptionMode, secret_key: secretKey } = packet.d; const { mode: encryptionMode, secret_key: secretKey } = packet.d;
this.state = { this.state = {
...this.state, ...this.state,
code: NetworkingStatusCode.Ready, code: NetworkingStatusCode.Ready,
connectionData: { connectionData: {
...this.state.connectionData, ...this.state.connectionData,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
encryptionMode, encryptionMode,
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
secretKey: new Uint8Array(secretKey), secretKey: new Uint8Array(secretKey),
sequence: randomNBit(16), sequence: randomNBit(16),
timestamp: randomNBit(32), timestamp: randomNBit(32),
@@ -460,7 +448,6 @@ export class Networking extends EventEmitter {
packetsPlayed: 0, packetsPlayed: 0,
}, },
}; };
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
} else if (packet.op === VoiceOpcodes.Resumed && this.state.code === NetworkingStatusCode.Resuming) { } else if (packet.op === VoiceOpcodes.Resumed && this.state.code === NetworkingStatusCode.Resuming) {
this.state = { this.state = {
...this.state, ...this.state,

View File

@@ -73,7 +73,6 @@ export class VoiceWebSocket extends EventEmitter {
this.ws = new WebSocket(address); this.ws = new WebSocket(address);
this.ws.onmessage = (err) => this.onMessage(err); this.ws.onmessage = (err) => this.onMessage(err);
this.ws.onopen = (err) => this.emit('open', err); this.ws.onopen = (err) => this.emit('open', err);
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this.ws.onerror = (err: Error | WebSocket.ErrorEvent) => this.emit('error', err instanceof Error ? err : err.error); this.ws.onerror = (err: Error | WebSocket.ErrorEvent) => this.emit('error', err instanceof Error ? err : err.error);
this.ws.onclose = (err) => this.emit('close', err); this.ws.onclose = (err) => this.emit('close', err);
@@ -110,7 +109,6 @@ export class VoiceWebSocket extends EventEmitter {
let packet: any; let packet: any;
try { try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
packet = JSON.parse(event.data); packet = JSON.parse(event.data);
} catch (error) { } catch (error) {
const err = error as Error; const err = error as Error;
@@ -118,7 +116,6 @@ export class VoiceWebSocket extends EventEmitter {
return; return;
} }
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (packet.op === VoiceOpcodes.HeartbeatAck) { if (packet.op === VoiceOpcodes.HeartbeatAck) {
this.lastHeartbeatAck = Date.now(); this.lastHeartbeatAck = Date.now();
this.missedHeartbeats = 0; this.missedHeartbeats = 0;

View File

@@ -85,6 +85,5 @@ export class AudioReceiveStream extends Readable {
this.endTimeout = setTimeout(() => this.push(null), end.duration); this.endTimeout = setTimeout(() => this.push(null), end.duration);
} }
// eslint-disable-next-line @typescript-eslint/no-empty-function
public override _read() {} public override _read() {}
} }

View File

@@ -64,34 +64,22 @@ export class VoiceReceiver {
* @internal * @internal
*/ */
public onWsPacket(packet: any) { public onWsPacket(packet: any) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (packet.op === VoiceOpcodes.ClientDisconnect && typeof packet.d?.user_id === 'string') { if (packet.op === VoiceOpcodes.ClientDisconnect && typeof packet.d?.user_id === 'string') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
this.ssrcMap.delete(packet.d.user_id); this.ssrcMap.delete(packet.d.user_id);
} else if ( } else if (
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
packet.op === VoiceOpcodes.Speaking && packet.op === VoiceOpcodes.Speaking &&
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
typeof packet.d?.user_id === 'string' && typeof packet.d?.user_id === 'string' &&
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
typeof packet.d?.ssrc === 'number' typeof packet.d?.ssrc === 'number'
) { ) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
this.ssrcMap.update({ userId: packet.d.user_id, audioSSRC: packet.d.ssrc }); this.ssrcMap.update({ userId: packet.d.user_id, audioSSRC: packet.d.ssrc });
} else if ( } else if (
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
packet.op === VoiceOpcodes.ClientConnect && packet.op === VoiceOpcodes.ClientConnect &&
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
typeof packet.d?.user_id === 'string' && typeof packet.d?.user_id === 'string' &&
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
typeof packet.d?.audio_ssrc === 'number' typeof packet.d?.audio_ssrc === 'number'
) { ) {
this.ssrcMap.update({ this.ssrcMap.update({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
userId: packet.d.user_id, userId: packet.d.user_id,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
audioSSRC: packet.d.audio_ssrc, audioSSRC: packet.d.audio_ssrc,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
videoSSRC: packet.d.video_ssrc === 0 ? undefined : packet.d.video_ssrc, videoSSRC: packet.d.video_ssrc === 0 ? undefined : packet.d.video_ssrc,
}); });
} }

View File

@@ -9,56 +9,40 @@ interface Methods {
const libs = { const libs = {
'sodium-native': (sodium: any): Methods => ({ 'sodium-native': (sodium: any): Methods => ({
open: (buffer: Buffer, nonce: Buffer, secretKey: Uint8Array) => { open: (buffer: Buffer, nonce: Buffer, secretKey: Uint8Array) => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (buffer) { if (buffer) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const output = Buffer.allocUnsafe(buffer.length - sodium.crypto_box_MACBYTES); const output = Buffer.allocUnsafe(buffer.length - sodium.crypto_box_MACBYTES);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
if (sodium.crypto_secretbox_open_easy(output, buffer, nonce, secretKey)) return output; if (sodium.crypto_secretbox_open_easy(output, buffer, nonce, secretKey)) return output;
} }
return null; return null;
}, },
close: (opusPacket: Buffer, nonce: Buffer, secretKey: Uint8Array) => { close: (opusPacket: Buffer, nonce: Buffer, secretKey: Uint8Array) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument, @typescript-eslint/restrict-plus-operands // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
const output = Buffer.allocUnsafe(opusPacket.length + sodium.crypto_box_MACBYTES); const output = Buffer.allocUnsafe(opusPacket.length + sodium.crypto_box_MACBYTES);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
sodium.crypto_secretbox_easy(output, opusPacket, nonce, secretKey); sodium.crypto_secretbox_easy(output, opusPacket, nonce, secretKey);
return output; return output;
}, },
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
random: (num: number, buffer: Buffer = Buffer.allocUnsafe(num)) => { random: (num: number, buffer: Buffer = Buffer.allocUnsafe(num)) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
sodium.randombytes_buf(buffer); sodium.randombytes_buf(buffer);
return buffer; return buffer;
}, },
}), }),
sodium: (sodium: any): Methods => ({ sodium: (sodium: any): Methods => ({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
open: sodium.api.crypto_secretbox_open_easy, open: sodium.api.crypto_secretbox_open_easy,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
close: sodium.api.crypto_secretbox_easy, close: sodium.api.crypto_secretbox_easy,
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
random: (num: number, buffer: Buffer = Buffer.allocUnsafe(num)) => { random: (num: number, buffer: Buffer = Buffer.allocUnsafe(num)) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
sodium.api.randombytes_buf(buffer); sodium.api.randombytes_buf(buffer);
return buffer; return buffer;
}, },
}), }),
'libsodium-wrappers': (sodium: any): Methods => ({ 'libsodium-wrappers': (sodium: any): Methods => ({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
open: sodium.crypto_secretbox_open_easy, open: sodium.crypto_secretbox_open_easy,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
close: sodium.crypto_secretbox_easy, close: sodium.crypto_secretbox_easy,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
random: sodium.randombytes_buf, random: sodium.randombytes_buf,
}), }),
tweetnacl: (tweetnacl: any): Methods => ({ tweetnacl: (tweetnacl: any): Methods => ({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
open: tweetnacl.secretbox.open, open: tweetnacl.secretbox.open,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
close: tweetnacl.secretbox, close: tweetnacl.secretbox,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
random: tweetnacl.randomBytes, random: tweetnacl.randomBytes,
}), }),
} as const; } as const;
@@ -82,7 +66,6 @@ void (async () => {
try { try {
// eslint-disable-next-line unicorn/no-abusive-eslint-disable, @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires // eslint-disable-next-line unicorn/no-abusive-eslint-disable, @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
const lib = require(libName); const lib = require(libName);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (libName === 'libsodium-wrappers' && lib.ready) await lib.ready; if (libName === 'libsodium-wrappers' && lib.ready) await lib.ready;
Object.assign(methods, libs[libName](lib)); Object.assign(methods, libs[libName](lib));
break; break;

View File

@@ -7,7 +7,6 @@ export function abortAfter(delay: number): [AbortController, AbortSignal] {
const ac = new AbortController(); const ac = new AbortController();
const timeout = setTimeout(() => ac.abort(), delay); const timeout = setTimeout(() => ac.abort(), delay);
// @ts-expect-error: No type for timeout // @ts-expect-error: No type for timeout
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
ac.signal.addEventListener('abort', () => clearTimeout(timeout)); ac.signal.addEventListener('abort', () => clearTimeout(timeout));
return [ac, ac.signal]; return [ac, ac.signal];
} }

View File

@@ -18,11 +18,8 @@ function findPackageJSON(
if (depth === 0) return undefined; if (depth === 0) return undefined;
const attemptedPath = resolve(dir, './package.json'); const attemptedPath = resolve(dir, './package.json');
try { try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const pkg = require(attemptedPath); const pkg = require(attemptedPath);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (pkg.name !== packageName) throw new Error('package.json does not match'); if (pkg.name !== packageName) throw new Error('package.json does not match');
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return pkg; return pkg;
} catch { } catch {
return findPackageJSON(resolve(dir, '..'), packageName, depth - 1); return findPackageJSON(resolve(dir, '..'), packageName, depth - 1);
@@ -36,12 +33,10 @@ function findPackageJSON(
*/ */
function version(name: string): string { function version(name: string): string {
try { try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const pkg = const pkg =
name === '@discordjs/voice' name === '@discordjs/voice'
? require('../../package.json') ? require('../../package.json')
: findPackageJSON(dirname(require.resolve(name)), name, 3); : findPackageJSON(dirname(require.resolve(name)), name, 3);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access
return pkg?.version ?? 'not found'; return pkg?.version ?? 'not found';
} catch { } catch {
return 'not found'; return 'not found';

View File

@@ -1,2 +1 @@
// eslint-disable-next-line @typescript-eslint/no-empty-function
export const noop = () => {}; export const noop = () => {};

View File

@@ -67,7 +67,6 @@ function resolveIcon(item: keyof GroupedMembers) {
} }
const useStyles = createStyles((theme) => ({ const useStyles = createStyles((theme) => ({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
link: { link: {
...theme.fn.focusStyles(), ...theme.fn.focusStyles(),
fontWeight: 500, fontWeight: 500,

View File

@@ -4,7 +4,6 @@ import { useMemo } from 'react';
import { VscListSelection, VscSymbolMethod, VscSymbolProperty } from 'react-icons/vsc'; import { VscListSelection, VscSymbolMethod, VscSymbolProperty } from 'react-icons/vsc';
const useStyles = createStyles((theme) => ({ const useStyles = createStyles((theme) => ({
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
link: { link: {
...theme.fn.focusStyles(), ...theme.fn.focusStyles(),
fontWeight: 500, fontWeight: 500,

View File

@@ -47,16 +47,13 @@ export const getStaticPaths: GetStaticPaths = async () => {
let versions: string[] = []; let versions: string[] = [];
if (process.env.NEXT_PUBLIC_LOCAL_DEV) { if (process.env.NEXT_PUBLIC_LOCAL_DEV) {
const res = await readFile(join(cwd(), '..', packageName, 'docs', 'docs.api.json'), 'utf8'); const res = await readFile(join(cwd(), '..', packageName, 'docs', 'docs.api.json'), 'utf8');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
data = JSON.parse(res); data = JSON.parse(res);
} else { } else {
const response = await fetch(`https://docs.discordjs.dev/api/info?package=${packageName}`); const response = await fetch(`https://docs.discordjs.dev/api/info?package=${packageName}`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
versions = await response.json(); versions = await response.json();
for (const version of versions) { for (const version of versions) {
const res = await fetch(`https://docs.discordjs.dev/docs/${packageName}/${version}.api.json`); const res = await fetch(`https://docs.discordjs.dev/docs/${packageName}/${version}.api.json`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
data = [...data, await res.json()]; data = [...data, await res.json()];
} }
} }
@@ -142,11 +139,9 @@ export const getStaticProps: GetStaticProps = async ({ params }) => {
let data; let data;
if (process.env.NEXT_PUBLIC_LOCAL_DEV) { if (process.env.NEXT_PUBLIC_LOCAL_DEV) {
const res = await readFile(join(cwd(), '..', packageName, 'docs', 'docs.api.json'), 'utf8'); const res = await readFile(join(cwd(), '..', packageName, 'docs', 'docs.api.json'), 'utf8');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
data = JSON.parse(res); data = JSON.parse(res);
} else { } else {
const res = await fetch(`https://docs.discordjs.dev/docs/${packageName}/${branchName}.api.json`); const res = await fetch(`https://docs.discordjs.dev/docs/${packageName}/${branchName}.api.json`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
data = await res.json(); data = await res.json();
} }

View File

@@ -38,7 +38,6 @@ export const getStaticProps: GetStaticProps = async ({ params }) => {
try { try {
const res = await fetch(`https://docs.discordjs.dev/api/info?package=${packageName ?? 'builders'}`); const res = await fetch(`https://docs.discordjs.dev/api/info?package=${packageName ?? 'builders'}`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const data: string[] = await res.json(); const data: string[] = await res.json();
if (!data.length) { if (!data.length) {

View File

@@ -1,6 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { ApiModel, ApiItem, type ApiPackage } from '@microsoft/api-extractor-model'; import { ApiModel, ApiItem, type ApiPackage } from '@microsoft/api-extractor-model';
import { TSDocConfiguration } from '@microsoft/tsdoc'; import { TSDocConfiguration } from '@microsoft/tsdoc';
import { TSDocConfigFile } from '@microsoft/tsdoc-config'; import { TSDocConfigFile } from '@microsoft/tsdoc-config';
@@ -11,7 +8,6 @@ export function createApiModel(data: any) {
const tsdocConfigFile = TSDocConfigFile.loadFromObject(data.metadata.tsdocConfig); const tsdocConfigFile = TSDocConfigFile.loadFromObject(data.metadata.tsdocConfig);
tsdocConfigFile.configureParser(tsdocConfiguration); tsdocConfigFile.configureParser(tsdocConfiguration);
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const apiPackage = ApiItem.deserialize(data, { const apiPackage = ApiItem.deserialize(data, {
apiJsonFilename: '', apiJsonFilename: '',
toolPackage: data.metadata.toolPackage, toolPackage: data.metadata.toolPackage,

View File

@@ -50,14 +50,12 @@ vi.mock('node:worker_threads', async () => {
class MockWorker extends EventEmitter { class MockWorker extends EventEmitter {
public constructor(...args: any[]) { public constructor(...args: any[]) {
super(); super();
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
mockConstructor(...args); mockConstructor(...args);
// need to delay this by an event loop cycle to allow the strategy to attach a listener // need to delay this by an event loop cycle to allow the strategy to attach a listener
setImmediate(() => this.emit('online')); setImmediate(() => this.emit('online'));
} }
public postMessage(message: WorkerSendPayload) { public postMessage(message: WorkerSendPayload) {
// eslint-disable-next-line default-case
switch (message.op) { switch (message.op) {
case WorkerSendPayloadOp.Connect: { case WorkerSendPayloadOp.Connect: {
const response: WorkerRecievePayload = { const response: WorkerRecievePayload = {
@@ -180,7 +178,6 @@ test('spawn, connect, send a message, session info, and destroy', async () => {
await manager.connect(); await manager.connect();
expect(mockConstructor).toHaveBeenCalledWith( expect(mockConstructor).toHaveBeenCalledWith(
expect.stringContaining('worker.cjs'), expect.stringContaining('worker.cjs'),
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
expect.objectContaining({ workerData: expect.objectContaining({ shardIds: [0, 1] }) }), expect.objectContaining({ workerData: expect.objectContaining({ shardIds: [0, 1] }) }),
); );

View File

@@ -1,3 +1,4 @@
/* eslint-disable unicorn/require-post-message-target-origin */
import { isMainThread, parentPort } from 'node:worker_threads'; import { isMainThread, parentPort } from 'node:worker_threads';
import { Collection } from '@discordjs/collection'; import { Collection } from '@discordjs/collection';
import type { SessionInfo } from '../../ws/WebSocketManager.js'; import type { SessionInfo } from '../../ws/WebSocketManager.js';
@@ -35,7 +36,6 @@ export class WorkerContextFetchingStrategy implements IContextFetchingStrategy {
}; };
// eslint-disable-next-line no-promise-executor-return // eslint-disable-next-line no-promise-executor-return
const promise = new Promise<SessionInfo | null>((resolve) => this.sessionPromises.set(nonce, resolve)); const promise = new Promise<SessionInfo | null>((resolve) => this.sessionPromises.set(nonce, resolve));
// eslint-disable-next-line unicorn/require-post-message-target-origin
parentPort!.postMessage(payload); parentPort!.postMessage(payload);
return promise; return promise;
} }
@@ -46,7 +46,6 @@ export class WorkerContextFetchingStrategy implements IContextFetchingStrategy {
shardId, shardId,
session: sessionInfo, session: sessionInfo,
}; };
// eslint-disable-next-line unicorn/require-post-message-target-origin
parentPort!.postMessage(payload); parentPort!.postMessage(payload);
} }
} }

View File

@@ -1,3 +1,4 @@
/* eslint-disable unicorn/require-post-message-target-origin */
import { once } from 'node:events'; import { once } from 'node:events';
import { join } from 'node:path'; import { join } from 'node:path';
import { Worker } from 'node:worker_threads'; import { Worker } from 'node:worker_threads';
@@ -100,7 +101,6 @@ export class WorkerShardingStrategy implements IShardingStrategy {
.on('messageerror', (err) => { .on('messageerror', (err) => {
throw err; throw err;
}) })
// eslint-disable-next-line @typescript-eslint/no-misused-promises
.on('message', async (payload: WorkerRecievePayload) => this.onMessage(worker, payload)); .on('message', async (payload: WorkerRecievePayload) => this.onMessage(worker, payload));
this.#workers.push(worker); this.#workers.push(worker);
@@ -128,7 +128,6 @@ export class WorkerShardingStrategy implements IShardingStrategy {
// eslint-disable-next-line no-promise-executor-return // eslint-disable-next-line no-promise-executor-return
const promise = new Promise<void>((resolve) => this.connectPromises.set(shardId, resolve)); const promise = new Promise<void>((resolve) => this.connectPromises.set(shardId, resolve));
// eslint-disable-next-line unicorn/require-post-message-target-origin
worker.postMessage(payload); worker.postMessage(payload);
promises.push(promise); promises.push(promise);
} }
@@ -153,7 +152,6 @@ export class WorkerShardingStrategy implements IShardingStrategy {
// eslint-disable-next-line no-promise-executor-return, promise/prefer-await-to-then // eslint-disable-next-line no-promise-executor-return, promise/prefer-await-to-then
new Promise<void>((resolve) => this.destroyPromises.set(shardId, resolve)).then(async () => worker.terminate()), new Promise<void>((resolve) => this.destroyPromises.set(shardId, resolve)).then(async () => worker.terminate()),
); );
// eslint-disable-next-line unicorn/require-post-message-target-origin
worker.postMessage(payload); worker.postMessage(payload);
} }
@@ -177,12 +175,10 @@ export class WorkerShardingStrategy implements IShardingStrategy {
shardId, shardId,
payload: data, payload: data,
}; };
// eslint-disable-next-line unicorn/require-post-message-target-origin
worker.postMessage(payload); worker.postMessage(payload);
} }
private async onMessage(worker: Worker, payload: WorkerRecievePayload) { private async onMessage(worker: Worker, payload: WorkerRecievePayload) {
// eslint-disable-next-line default-case
switch (payload.op) { switch (payload.op) {
case WorkerRecievePayloadOp.Connected: { case WorkerRecievePayloadOp.Connected: {
const resolve = this.connectPromises.get(payload.shardId)!; const resolve = this.connectPromises.get(payload.shardId)!;
@@ -199,7 +195,6 @@ export class WorkerShardingStrategy implements IShardingStrategy {
} }
case WorkerRecievePayloadOp.Event: { case WorkerRecievePayloadOp.Event: {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this.manager.emit(payload.event, { ...payload.data, shardId: payload.shardId }); this.manager.emit(payload.event, { ...payload.data, shardId: payload.shardId });
break; break;
} }
@@ -211,7 +206,6 @@ export class WorkerShardingStrategy implements IShardingStrategy {
nonce: payload.nonce, nonce: payload.nonce,
session, session,
}; };
// eslint-disable-next-line unicorn/require-post-message-target-origin
worker.postMessage(response); worker.postMessage(response);
break; break;
} }

View File

@@ -58,9 +58,7 @@ parentPort!
.on('messageerror', (err) => { .on('messageerror', (err) => {
throw err; throw err;
}) })
// eslint-disable-next-line @typescript-eslint/no-misused-promises
.on('message', async (payload: WorkerSendPayload) => { .on('message', async (payload: WorkerSendPayload) => {
// eslint-disable-next-line default-case
switch (payload.op) { switch (payload.op) {
case WorkerSendPayloadOp.Connect: { case WorkerSendPayloadOp.Connect: {
await connect(payload.shardId); await connect(payload.shardId);

View File

@@ -21,10 +21,8 @@ export enum CompressionMethod {
} }
const packageJson = readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf8'); const packageJson = readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf8');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const Package = JSON.parse(packageJson); const Package = JSON.parse(packageJson);
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-unsafe-member-access
export const DefaultDeviceProperty = `@discordjs/ws ${Package.version}`; export const DefaultDeviceProperty = `@discordjs/ws ${Package.version}`;
const getDefaultSessionStore = lazy(() => new Collection<number, SessionInfo | null>()); const getDefaultSessionStore = lazy(() => new Collection<number, SessionInfo | null>());

View File

@@ -384,7 +384,6 @@ export class WebSocketShard extends AsyncEventEmitter<WebSocketShardEventsMap> {
return; return;
} }
// eslint-disable-next-line default-case
switch (payload.op) { switch (payload.op) {
case GatewayOpcodes.Dispatch: { case GatewayOpcodes.Dispatch: {
if (this.status === WebSocketShardStatus.Ready || this.status === WebSocketShardStatus.Resuming) { if (this.status === WebSocketShardStatus.Ready || this.status === WebSocketShardStatus.Resuming) {