Skip to content

Commit

Permalink
Fix eslint actually this time
Browse files Browse the repository at this point in the history
  • Loading branch information
MaddyGuthridge committed Oct 15, 2024
1 parent 5c481c9 commit 26e82d9
Show file tree
Hide file tree
Showing 65 changed files with 234 additions and 223 deletions.
18 changes: 15 additions & 3 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ export default ts.config(
parserOptions: {
// ...
project: true,
extraFileExtensions: [".svelte"], // This is a required setting in `@typescript-eslint/parser` v4.24.0.
extraFileExtensions: ['.svelte'], // This is a required setting in `@typescript-eslint/parser` v4.24.0.
},
},
},
{
files: ["**/*.svelte", "*.svelte"],
files: ['**/*.svelte', '*.svelte'],
languageOptions: {
parser: svelteParser,
// Parse the `<script>` in `.svelte` as TypeScript by adding the following configuration.
Expand All @@ -50,8 +50,20 @@ export default ts.config(
}],
// Disallow floating promises to avoid random crashes
'@typescript-eslint/no-floating-promises': 'error',
//
// Single quotes where possible
quotes: ['error', 'single', { 'avoidEscape': true, 'allowTemplateLiterals': false }],
// Allow some `any` expressions since otherwise they seriously mess with tests, or enforce
// strictness in areas where it really doesn't matter (eg error handling)
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-argument': 'off',
// Also disable template expression checks, since they're also error handling stuff
// TODO: Enable them at some point when I get around to actually tidying things up
'@typescript-eslint/no-base-to-string': 'off',
'@typescript-eslint/restrict-template-expressions': 'off',
// FIXME: When I get around to hardening the request body validation, enable this rule again
'@typescript-eslint/no-unsafe-member-access': 'off',
// Allow empty functions, as they are useful to silence promise errors
'@typescript-eslint/no-empty-function': 'off',
},
},
{
Expand Down
4 changes: 2 additions & 2 deletions src/components/AsciinemaPlayer.svelte
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<script lang="ts">
<!-- <script lang="ts">
import { onMount } from 'svelte';
import 'asciinema-player/dist/bundle/asciinema-player.css';
// @ts-expect-error -- asciinema doesn't have a types module
Expand All @@ -17,4 +17,4 @@
</script>
<div id="asciinema-player">
</div>
</div> -->
8 changes: 4 additions & 4 deletions src/components/EditControls.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import { createEventDispatcher } from 'svelte';
/** Whether edit mode is currently enabled */
export let editing: boolean;
Expand All @@ -15,10 +15,10 @@
{#if loggedIn}
<div class="edit-buttons">
{#if editing}
<button on:click={() => dispatch("finishEdits", false)}>Cancel</button>
<button on:click={() => dispatch("finishEdits", true)}>Done</button>
<button on:click={() => dispatch('finishEdits', false)}>Cancel</button>
<button on:click={() => dispatch('finishEdits', true)}>Done</button>
{:else}
<button on:click={() => dispatch("beginEdits")}>Edit</button>
<button on:click={() => dispatch('beginEdits')}>Edit</button>
{/if}
</div>
{/if}
Expand Down
10 changes: 5 additions & 5 deletions src/components/markdown/Markdown.svelte
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
<script lang="ts">
import { marked } from "marked";
import hljs from "highlight.js";
import "highlight.js/styles/stackoverflow-light.css";
import { marked } from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/stackoverflow-light.css';
export let source: string;
// https://github.com/markedjs/marked/discussions/2982#discussioncomment-6979586
const renderer = {
link(href: string, title: string | null | undefined, text: string) {
const link = marked.Renderer.prototype.link.call(this, href, title, text);
return link.replace("<a", "<a target='_blank' rel='noreferrer' ");
return link.replace('<a', "<a target='_blank' rel='noreferrer' ");
},
};
marked.use({ renderer });
Expand All @@ -31,7 +31,7 @@
// function when we just subscribe to what their contents are supposed to
// be
setTimeout(() => {
renderElement.querySelectorAll("pre code").forEach((el) => {
renderElement.querySelectorAll('pre code').forEach((el) => {
hljs.highlightElement(el as HTMLElement);
});
});
Expand Down
20 changes: 10 additions & 10 deletions src/components/navbar/Navbar.svelte
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<script lang="ts">
import { dev } from "$app/environment";
import { goto } from "$app/navigation";
import api from "$endpoints";
import type { ConfigJson } from "$lib/server/data/config";
import Separator from "$components/Separator.svelte";
import { dev } from '$app/environment';
import { goto } from '$app/navigation';
import api from '$endpoints';
import type { ConfigJson } from '$lib/server/data/config';
import Separator from '$components/Separator.svelte';
export let path: { url: string; txt: string }[];
export let config: ConfigJson;
Expand All @@ -26,7 +26,7 @@
/** Clear all data, and take the user to the firstrun page */
async function clear() {
await api().debug.clear();
await goto("/admin/firstrun");
await goto('/admin/firstrun');
}
// This function needs to accept `path` as an input, otherwise the links
Expand All @@ -35,7 +35,7 @@
return path
.slice(0, i + 1)
.map((p) => p.url)
.join("/");
.join('/');
}
</script>

Expand All @@ -48,7 +48,7 @@
<a href="/">{config.siteShortName}</a> /
{#each path.slice(0, -1) as p, i}
<a href="/{pathTo(path, i)}">{p.txt}</a>
{"/ "}
{'/ '}
{/each}
{path[path.length - 1].txt}
</h1>
Expand All @@ -58,14 +58,14 @@
<!-- Control buttons -->
<span id="control-buttons">
{#if loggedIn}
<button on:click={() => goto("/admin")}> Admin </button>
<button on:click={() => goto('/admin')}> Admin </button>
<button on:click={logOut}> Log out </button>
{:else if loggedIn !== undefined}
<!-- Only include a login button if logging in is enabled -->
<button on:click={gotoLogin}> Log in </button>
{/if}
<!-- About button navigates to about page -->
<button on:click={() => goto("/about")}> About </button>
<button on:click={() => goto('/about')}> About </button>
<!-- In dev mode, add a quick shortcut to delete everything -->
{#if dev}
<Separator />
Expand Down
4 changes: 2 additions & 2 deletions src/endpoints/admin/firstrun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import { apiFetch, json } from '../fetch';
export default async function (
username: string,
password: string,
repoUrl?: string | undefined,
branch?: string | undefined,
repoUrl?: string ,
branch?: string ,
) {
return json(apiFetch(
'POST',
Expand Down
2 changes: 1 addition & 1 deletion src/endpoints/admin/keys.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { apiFetch, json } from "$endpoints/fetch"
import { apiFetch, json } from '$endpoints/fetch'

export default function keys(token: string | undefined) {
const get = async () => {
Expand Down
6 changes: 3 additions & 3 deletions src/endpoints/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ function getUrl() {
// Running in node
dotenv.config();

const PORT = process.env.PORT as string;
const HOST = process.env.HOST as string;
const PORT = process.env.PORT!;
const HOST = process.env.HOST!;
return `http://${HOST}:${PORT}`;
}
}
Expand Down Expand Up @@ -60,7 +60,7 @@ export async function apiFetch(
// GET and DELETE use params
url
= `${URL}${route}?`
+ new URLSearchParams(bodyParams as Record<string, string>);
+ new URLSearchParams(bodyParams as Record<string, string>).toString();
body = null;
}

Expand Down
2 changes: 1 addition & 1 deletion src/endpoints/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import group from './group';
import readme from './readme';

/** Create an instance of the API client with the given token */
export default function api(token?: string | undefined) {
export default function api(token?: string ) {
return {
admin: admin(token),
debug: debug(token),
Expand Down
2 changes: 1 addition & 1 deletion src/lib/repoInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const repoProviders: Record<RepoProvider, RepoProviderInfo> = {
// https://github.com/orgs/community/discussions/31111#discussioncomment-3492603
const res = await fetch(`https://api.github.com/repos/${repo}`);
const json = await res.json();
return json.stargazers_count;
return json.stargazers_count as number;
},
},
// GitLab
Expand Down
2 changes: 1 addition & 1 deletion src/lib/server/auth/passwords.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export function hashAndSalt(salt: string, password: string): string {
export async function validateCredentials(
username: string,
password: string,
code: number = 403,
code = 403,
): Promise<string> {
const local = await getLocalConfig();

Expand Down
4 changes: 2 additions & 2 deletions src/lib/server/auth/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export function getTokenFromRequest(req: { request: Request, cookies: Cookies })
const tokenFromHeader = req.request.headers.get('Authorization');
const tokenFromCookie = req.cookies.get('token');

return tokenFromHeader || tokenFromCookie;
return tokenFromHeader ?? tokenFromCookie;
}

/** Revoke the session of the given token */
Expand Down Expand Up @@ -134,7 +134,7 @@ export async function revokeSession(token: string): Promise<void> {
export async function validateTokenFromRequest(req: { request: Request, cookies: Cookies }): Promise<string> {
const token = getTokenFromRequest(req);
if (!token) {
throw error(401, 'A token is required to access this endpoint');
error(401, 'A token is required to access this endpoint');
}
const data = await validateToken(token).catch(e => {
// Remove token from cookies, as it is invalid
Expand Down
2 changes: 1 addition & 1 deletion src/lib/server/data/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ async function loadPortfolioGlobals(): Promise<PortfolioGlobals> {
// Yucky nesting, but it should be somewhat parallel at least
// Basically, this is a nested version of the code for loading all group data
const items: Record<string, Record<string, ItemData>> = Object.fromEntries(await Promise.all(
groupIds.map(async (g) => [
groupIds.map(async (g): Promise<[string, Record<string, ItemData>]> => [
g,
Object.fromEntries(await Promise.all(
(await listItems(g)).map(async i => [i, await getItemData(g, i)])
Expand Down
8 changes: 4 additions & 4 deletions src/lib/server/data/migrations/unsafeLoad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,20 @@ import fs from 'fs/promises';

/** Load old config.json */
export async function unsafeLoadConfig(dataDir: string): Promise<object> {
return JSON.parse(await fs.readFile(`${dataDir}/config.json`, { encoding: 'utf-8' }));
return JSON.parse(await fs.readFile(`${dataDir}/config.json`, { encoding: 'utf-8' })) as object;
}

/** Load old config.local.json */
export async function unsafeLoadLocalConfig(privateDataDir: string): Promise<object> {
return JSON.parse(await fs.readFile(`${privateDataDir}/config.local.json`, { encoding: 'utf-8' }));
return JSON.parse(await fs.readFile(`${privateDataDir}/config.local.json`, { encoding: 'utf-8' })) as object;
}

/** Load item info in old format */
export async function unsafeLoadItemInfo(dataDir: string, groupId: string, itemId: string): Promise<object> {
return JSON.parse(await fs.readFile(`${dataDir}/${groupId}/${itemId}/info.json`, { encoding: 'utf-8' }));
return JSON.parse(await fs.readFile(`${dataDir}/${groupId}/${itemId}/info.json`, { encoding: 'utf-8' })) as object;
}

/** Load group info in old format */
export async function unsafeLoadGroupInfo(dataDir: string, groupId: string): Promise<object> {
return JSON.parse(await fs.readFile(`${dataDir}/${groupId}/info.json`, { encoding: 'utf-8' }));
return JSON.parse(await fs.readFile(`${dataDir}/${groupId}/info.json`, { encoding: 'utf-8' })) as object;
}
11 changes: 5 additions & 6 deletions src/lib/server/data/migrations/v0.1.0.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import type { PackageInfo } from '../itemPackage';
import { LinksArray, listItems, setItemInfo } from '../item';
import type { Infer } from 'superstruct';
import { version } from '$app/environment';
import { setupGitignore } from '../../git';
import { capitalize } from '$lib/util';
import { unsafeLoadConfig, unsafeLoadGroupInfo, unsafeLoadItemInfo } from './unsafeLoad';

Expand Down Expand Up @@ -106,9 +105,9 @@ export default async function migrate(dataDir: string) {

await migrateConfig(dataDir);
await migrateReadme(dataDir);
// Set up gitignore
console.log(' .gitignore');
await setupGitignore();
// // Set up gitignore
// console.log(' .gitignore');
// await setupGitignore();
console.log('Data migration complete!');
}

Expand Down Expand Up @@ -229,7 +228,7 @@ function groupLinkPropertyOr<T extends keyof GroupLinkDisplayOptions>(
property: T,
fallback: GroupLinkDisplayOptions[T],
): GroupLinkDisplayOptions[T] {
return group.associations && group.associations[linkedGroup]
return group.associations?.[linkedGroup]
? group.associations[linkedGroup][property]
: fallback;
}
Expand Down Expand Up @@ -269,7 +268,7 @@ async function migrateGroupInfo(globals: OldGlobals, groupId: string) {
filterGroups: Object.keys(globals.groups).filter(g => g !== groupId),
// List all items, and sort them based on the given sort value
listedItems: Object.keys(globals.items[groupId]).toSorted(
(i1, i2) => (globals.items[groupId][i1].sort || 0) - (globals.items[groupId][i2].sort || 0)
(i1, i2) => (globals.items[groupId][i1].sort ?? 0) - (globals.items[groupId][i2].sort ?? 0)
).toReversed(),
// Use all items for filtering where the visibility setting isn't "filtered"
filterItems: Object.keys(globals.items[groupId]).filter(i => globals.items[groupId][i].visibility !== 'filtered'),
Expand Down
6 changes: 3 additions & 3 deletions src/lib/server/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export async function getRepoStatus(): Promise<RepoStatus> {
export async function setupGitRepo(repo: string, branch?: string | null) {
// Check whether the data repo is set up
if (await serverIsSetUp()) {
throw error(403, 'Data repo is already set up');
error(403, 'Data repo is already set up');
}

const dir = getDataDir();
Expand All @@ -134,7 +134,7 @@ export async function setupGitRepo(repo: string, branch?: string | null) {
await simpleGit().clone(repo, dir, options);
} catch (e: any) {
console.log(e);
throw error(400, `${e}`);
error(400, `${e}`);
}

// If there are files in the repo, we should validate that it is a proper
Expand All @@ -144,7 +144,7 @@ export async function setupGitRepo(repo: string, branch?: string | null) {
if (!await dataDirContainsData()) {
// Clean up and delete repo before giving error
await rimraf(getDataDir());
throw error(
error(
400,
'The repo directory is non-empty, but does not contain a config.json file'
);
Expand Down
8 changes: 4 additions & 4 deletions src/lib/server/util.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { error } from "@sveltejs/kit";
import { create, type Struct } from "superstruct";
import { error } from '@sveltejs/kit';
import { create, type Struct } from 'superstruct';

/**
* A wrapper around superstruct's assert, making it async to make error
* handling easier.
*
* By default this throws an error 400.
*/
export async function applyStruct<T, S>(
export function applyStruct<T, S>(
value: unknown,
struct: Struct<T, S>,
message?: string,
): Promise<T> {
): T {
try {
return create(value, struct, message);
} catch (e) {
Expand Down
Loading

0 comments on commit 26e82d9

Please sign in to comment.