refactor: 🚨 Turn every linter rule on and fix issues (there were a LOT :3)

This commit is contained in:
Jesse Wierzbinski 2024-06-12 16:26:43 -10:00
parent 2e98859153
commit a1e02d0d78
No known key found for this signature in database
177 changed files with 1826 additions and 1248 deletions

View file

@ -1,7 +1,7 @@
import type { InferSelectModel } from "drizzle-orm";
import { db } from "~/drizzle/db";
import type { Applications } from "~/drizzle/schema";
import type { Application as APIApplication } from "~/types/mastodon/application";
import type { Application as apiApplication } from "~/types/mastodon/application";
export type Application = InferSelectModel<typeof Applications>;
@ -27,7 +27,7 @@ export const getFromToken = async (
* Converts this application to an API application.
* @returns The API application representation of this application.
*/
export const applicationToAPI = (app: Application): APIApplication => {
export const applicationToApi = (app: Application): apiApplication => {
return {
name: app.name,
website: app.website,

View file

@ -2,7 +2,7 @@ import { MediaBackendType } from "media-manager";
import type { Config } from "~/packages/config-manager";
export const getUrl = (name: string, config: Config) => {
if (config.media.backend === MediaBackendType.LOCAL) {
if (config.media.backend === MediaBackendType.Local) {
return new URL(`/media/${name}`, config.http.base_url).toString();
}
if (config.media.backend === MediaBackendType.S3) {

View file

@ -4,8 +4,8 @@ import type { EntityValidator } from "@lysand-org/federation";
import { type InferSelectModel, and, eq } from "drizzle-orm";
import { db } from "~/drizzle/db";
import { Emojis, Instances } from "~/drizzle/schema";
import type { Emoji as APIEmoji } from "~/types/mastodon/emoji";
import { addInstanceIfNotExists } from "./Instance";
import type { Emoji as apiEmoji } from "~/types/mastodon/emoji";
import { addInstanceIfNotExists } from "./instance";
export type EmojiWithInstance = InferSelectModel<typeof Emojis> & {
instance: InferSelectModel<typeof Instances> | null;
@ -18,7 +18,9 @@ export type EmojiWithInstance = InferSelectModel<typeof Emojis> & {
*/
export const parseEmojis = async (text: string) => {
const matches = text.match(emojiValidatorWithColons);
if (!matches) return [];
if (!matches) {
return [];
}
const emojis = await db.query.Emojis.findMany({
where: (emoji, { eq, or }) =>
or(
@ -56,11 +58,12 @@ export const fetchEmoji = async (
)
.limit(1);
if (existingEmoji[0])
if (existingEmoji[0]) {
return {
...existingEmoji[0].Emojis,
instance: existingEmoji[0].Instances,
};
}
const foundInstance = host ? await addInstanceIfNotExists(host) : null;
@ -90,7 +93,7 @@ export const fetchEmoji = async (
* Converts the emoji to an APIEmoji object.
* @returns The APIEmoji object.
*/
export const emojiToAPI = (emoji: EmojiWithInstance): APIEmoji => {
export const emojiToApi = (emoji: EmojiWithInstance): apiEmoji => {
return {
// @ts-expect-error ID is not in regular Mastodon API
id: emoji.id,

View file

@ -7,7 +7,7 @@ import { config } from "config-manager";
import type { User } from "~/packages/database-interface/user";
import { LogLevel, LogManager } from "~/packages/log-manager";
export const localObjectURI = (id: string) =>
export const localObjectUri = (id: string) =>
new URL(`/objects/${id}`, config.http.base_url).toString();
export const objectToInboxRequest = async (
@ -52,14 +52,14 @@ export const objectToInboxRequest = async (
// Log public key
new LogManager(Bun.stdout).log(
LogLevel.DEBUG,
LogLevel.Debug,
"Inbox.Signature",
`Sender public key: ${author.data.publicKey}`,
);
// Log signed string
new LogManager(Bun.stdout).log(
LogLevel.DEBUG,
LogLevel.Debug,
"Inbox.Signature",
`Signed string:\n${signedString}`,
);

View file

@ -19,9 +19,9 @@ export const addInstanceIfNotExists = async (url: string) => {
where: (instance, { eq }) => eq(instance.baseUrl, host),
});
if (found) return found;
console.log(`Fetching instance metadata for ${origin}`);
if (found) {
return found;
}
// Fetch the instance configuration
const metadata = (await fetch(new URL("/.well-known/lysand", origin)).then(

View file

@ -3,14 +3,14 @@ import { db } from "~/drizzle/db";
import type { Notifications } from "~/drizzle/schema";
import { Note } from "~/packages/database-interface/note";
import { User } from "~/packages/database-interface/user";
import type { Notification as APINotification } from "~/types/mastodon/notification";
import type { StatusWithRelations } from "./Status";
import type { Notification as apiNotification } from "~/types/mastodon/notification";
import type { StatusWithRelations } from "./status";
import {
type UserWithRelations,
transformOutputToUserWithRelations,
userExtrasTemplate,
userRelations,
} from "./User";
} from "./user";
export type Notification = InferSelectModel<typeof Notifications>;
@ -48,17 +48,17 @@ export const findManyNotifications = async (
);
};
export const notificationToAPI = async (
export const notificationToApi = async (
notification: NotificationWithRelations,
): Promise<APINotification> => {
): Promise<apiNotification> => {
const account = new User(notification.account);
return {
account: account.toAPI(),
account: account.toApi(),
created_at: new Date(notification.createdAt).toISOString(),
id: notification.id,
type: notification.type,
status: notification.status
? await new Note(notification.status).toAPI(account)
? await new Note(notification.status).toApi(account)
: undefined,
};
};

View file

@ -2,7 +2,7 @@ import type { InferSelectModel } from "drizzle-orm";
import { db } from "~/drizzle/db";
import { Relationships } from "~/drizzle/schema";
import type { User } from "~/packages/database-interface/user";
import type { Relationship as APIRelationship } from "~/types/mastodon/relationship";
import type { Relationship as apiRelationship } from "~/types/mastodon/relationship";
export type Relationship = InferSelectModel<typeof Relationships> & {
requestedBy: boolean;
@ -76,7 +76,7 @@ export const checkForBidirectionalRelationships = async (
* Converts the relationship to an API-friendly format.
* @returns The API-friendly relationship.
*/
export const relationshipToAPI = (rel: Relationship): APIRelationship => {
export const relationshipToApi = (rel: Relationship): apiRelationship => {
return {
blocked_by: rel.blockedBy,
blocking: rel.blocking,

View file

@ -36,9 +36,9 @@ import {
import type { Note } from "~/packages/database-interface/note";
import { User } from "~/packages/database-interface/user";
import { LogLevel } from "~/packages/log-manager";
import type { Application } from "./Application";
import type { EmojiWithInstance } from "./Emoji";
import { objectToInboxRequest } from "./Federation";
import type { Application } from "./application";
import type { EmojiWithInstance } from "./emoji";
import { objectToInboxRequest } from "./federation";
import {
type UserWithInstance,
type UserWithRelations,
@ -46,7 +46,7 @@ import {
transformOutputToUserWithRelations,
userExtrasTemplate,
userRelations,
} from "./User";
} from "./user";
export type Status = InferSelectModel<typeof Notes>;
@ -258,7 +258,9 @@ export const findManyNotes = async (
*/
export const parseTextMentions = async (text: string): Promise<User[]> => {
const mentionedPeople = [...text.matchAll(mentionValidator)] ?? [];
if (mentionedPeople.length === 0) return [];
if (mentionedPeople.length === 0) {
return [];
}
const baseUrlHost = new URL(config.http.base_url).host;
@ -287,11 +289,13 @@ export const parseTextMentions = async (text: string): Promise<User[]> => {
const notFoundRemoteUsers = mentionedPeople.filter(
(person) =>
!isLocal(person?.[2]) &&
!foundUsers.find(
(user) =>
user.username === person?.[1] &&
user.baseUrl === person?.[2],
!(
isLocal(person?.[2]) ||
foundUsers.find(
(user) =>
user.username === person?.[1] &&
user.baseUrl === person?.[2],
)
),
);
@ -320,7 +324,7 @@ export const parseTextMentions = async (text: string): Promise<User[]> => {
return finalList;
};
export const replaceTextMentions = async (text: string, mentions: User[]) => {
export const replaceTextMentions = (text: string, mentions: User[]) => {
let finalText = text;
for (const mention of mentions) {
const user = mention.data;
@ -412,7 +416,7 @@ export const markdownParse = async (content: string) => {
return (await getMarkdownRenderer()).render(content);
};
export const getMarkdownRenderer = async () => {
export const getMarkdownRenderer = () => {
const renderer = MarkdownIt({
html: true,
linkify: true,
@ -448,12 +452,12 @@ export const federateNote = async (note: Note) => {
if (!response.ok) {
dualLogger.log(
LogLevel.DEBUG,
LogLevel.Debug,
"Federation.Status",
await response.text(),
);
dualLogger.log(
LogLevel.ERROR,
LogLevel.Error,
"Federation.Status",
`Failed to federate status ${note.data.id} to ${user.getUri()}`,
);

View file

@ -5,7 +5,7 @@ import type { Tokens } from "~/drizzle/schema";
* The type of token.
*/
export enum TokenType {
BEARER = "Bearer",
Bearer = "Bearer",
}
export type Token = InferSelectModel<typeof Tokens>;

View file

@ -14,15 +14,15 @@ import {
} from "~/drizzle/schema";
import { User } from "~/packages/database-interface/user";
import { LogLevel } from "~/packages/log-manager";
import type { Application } from "./Application";
import type { EmojiWithInstance } from "./Emoji";
import { objectToInboxRequest } from "./Federation";
import type { Application } from "./application";
import type { EmojiWithInstance } from "./emoji";
import { objectToInboxRequest } from "./federation";
import {
type Relationship,
checkForBidirectionalRelationships,
createNewRelationship,
} from "./Relationship";
import type { Token } from "./Token";
} from "./relationship";
import type { Token } from "./token";
export type UserType = InferSelectModel<typeof Users>;
@ -175,13 +175,13 @@ export const followRequestUser = async (
if (!response.ok) {
dualLogger.log(
LogLevel.DEBUG,
LogLevel.Debug,
"Federation.FollowRequest",
await response.text(),
);
dualLogger.log(
LogLevel.ERROR,
LogLevel.Error,
"Federation.FollowRequest",
`Failed to federate follow request from ${
follower.id
@ -230,13 +230,13 @@ export const sendFollowAccept = async (follower: User, followee: User) => {
if (!response.ok) {
dualLogger.log(
LogLevel.DEBUG,
LogLevel.Debug,
"Federation.FollowAccept",
await response.text(),
);
dualLogger.log(
LogLevel.ERROR,
LogLevel.Error,
"Federation.FollowAccept",
`Failed to federate follow accept from ${
followee.id
@ -258,13 +258,13 @@ export const sendFollowReject = async (follower: User, followee: User) => {
if (!response.ok) {
dualLogger.log(
LogLevel.DEBUG,
LogLevel.Debug,
"Federation.FollowReject",
await response.text(),
);
dualLogger.log(
LogLevel.ERROR,
LogLevel.Error,
"Federation.FollowReject",
`Failed to federate follow reject from ${
followee.id
@ -352,7 +352,9 @@ export const findFirstUser = async (
},
});
if (!output) return null;
if (!output) {
return null;
}
return transformOutputToUserWithRelations(output);
};
@ -373,7 +375,9 @@ export const resolveWebFinger = async (
.where(and(eq(Users.username, identifier), eq(Instances.baseUrl, host)))
.limit(1);
if (foundUser[0]) return await User.fromId(foundUser[0].Users.id);
if (foundUser[0]) {
return await User.fromId(foundUser[0].Users.id);
}
const hostWithProtocol = host.startsWith("http") ? host : `https://${host}`;
@ -405,7 +409,7 @@ export const resolveWebFinger = async (
}[];
};
if (!data.subject || !data.links) {
if (!(data.subject && data.links)) {
throw new Error(
"Invalid WebFinger data (missing subject or links from response)",
);
@ -428,13 +432,17 @@ export const resolveWebFinger = async (
* @returns The user associated with the given access token.
*/
export const retrieveUserFromToken = async (
access_token: string,
accessToken: string,
): Promise<User | null> => {
if (!access_token) return null;
if (!accessToken) {
return null;
}
const token = await retrieveToken(access_token);
const token = await retrieveToken(accessToken);
if (!token || !token.userId) return null;
if (!token?.userId) {
return null;
}
const user = await User.fromId(token.userId);
@ -442,12 +450,14 @@ export const retrieveUserFromToken = async (
};
export const retrieveUserAndApplicationFromToken = async (
access_token: string,
accessToken: string,
): Promise<{
user: User | null;
application: Application | null;
}> => {
if (!access_token) return { user: null, application: null };
if (!accessToken) {
return { user: null, application: null };
}
const output = (
await db
@ -457,11 +467,13 @@ export const retrieveUserAndApplicationFromToken = async (
})
.from(Tokens)
.leftJoin(Applications, eq(Tokens.applicationId, Applications.id))
.where(eq(Tokens.accessToken, access_token))
.where(eq(Tokens.accessToken, accessToken))
.limit(1)
)[0];
if (!output?.token.userId) return { user: null, application: null };
if (!output?.token.userId) {
return { user: null, application: null };
}
const user = await User.fromId(output.token.userId);
@ -469,13 +481,15 @@ export const retrieveUserAndApplicationFromToken = async (
};
export const retrieveToken = async (
access_token: string,
accessToken: string,
): Promise<Token | null> => {
if (!access_token) return null;
if (!accessToken) {
return null;
}
return (
(await db.query.Tokens.findFirst({
where: (tokens, { eq }) => eq(tokens.accessToken, access_token),
where: (tokens, { eq }) => eq(tokens.accessToken, accessToken),
})) ?? null
);
};