Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

style: enable all biomejs recommended rules #7153

Merged
merged 41 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from 39 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
bc6ea37
Enable recomended correctness/noVoidTypeReturn
nazarhussain Oct 11, 2024
ab71719
Enable recomended rule correctness/useYield
nazarhussain Oct 11, 2024
91f6054
Enable recomended rule performance/noAccumulatingSpread
nazarhussain Oct 11, 2024
6cc060b
Enable recomended rule performance/noDelete
nazarhussain Oct 11, 2024
07f7cd4
Enable recomended rule suspicious/noAsyncPromiseExecutor
nazarhussain Oct 11, 2024
edd44b1
Enable recommended rule suspicious/noDoubleEquals
nazarhussain Oct 11, 2024
3cf245a
Enable recommended rule suspicious/noDuplicateTestHooks
nazarhussain Oct 11, 2024
3d67f6a
Enable recommended rule suspicious/noExportsInTest
nazarhussain Oct 11, 2024
24ebdc0
Enable recommended rule suspicious/noFallthroughSwitchClause
nazarhussain Oct 11, 2024
f2756df
Enable recommended rule suspicious/noGlobalIsFinite
nazarhussain Oct 11, 2024
d6b4206
Enable recommended rule suspicious/noGlobalIsNan
nazarhussain Oct 11, 2024
019c3de
Enable recommended rule suspicious/noPrototypeBuiltins
nazarhussain Oct 11, 2024
2630c5e
Enable recommended rule suspicious/noShadowRestrictedNames
nazarhussain Oct 11, 2024
04a1138
Enable recommended rule suspicious/useDefaultSwitchClauseLast
nazarhussain Oct 11, 2024
65a9d2a
Enable recommended rule suspicious/useGetterReturn
nazarhussain Oct 11, 2024
224a439
Enable recommended rule style/noUnusedTemplateLiteral
nazarhussain Oct 11, 2024
2a5b647
Convert default case to unreachable code
nazarhussain Oct 11, 2024
51c6048
Enable recommended rule complexity/noForEach
nazarhussain Oct 11, 2024
9f526e7
Enable recommended rule complexity/noThisInStatic
nazarhussain Oct 11, 2024
630ce11
Enable recommended rule complexity/useFlatMap
nazarhussain Oct 11, 2024
a0045ea
Enable recommended rule complexity/useOptionalChain
nazarhussain Oct 11, 2024
7a7b367
Enable recommended rule complexity/useRegexLiterals
nazarhussain Oct 11, 2024
7e3d613
Reorganize the config structure
nazarhussain Oct 11, 2024
d96b4d6
Fix few typos
nazarhussain Oct 14, 2024
69b7fa6
Merge branch 'unstable' into nh/biome-rules
nazarhussain Oct 14, 2024
4578725
Revert "Enable recomended rule performance/noDelete"
nazarhussain Oct 14, 2024
a04912c
Fix formatting
nazarhussain Oct 14, 2024
655a4d1
Enable recommended rule style/noUselessElse
nazarhussain Oct 14, 2024
ff5bb90
Enable recommended rule complexity/useLiteralKeys
nazarhussain Oct 14, 2024
dff8184
Enable recommended rule complexity/useArrowFunction
nazarhussain Oct 14, 2024
2309803
Fix few types
nazarhussain Oct 14, 2024
d67458d
Fix a test file
nazarhussain Oct 14, 2024
7cfc88e
Fix formatting
nazarhussain Oct 14, 2024
6472918
Enable recommended rule suspicious/noImplicitAnyLet
nazarhussain Oct 14, 2024
b3243c1
Enable recommended rule complexity/noUselessEmptyExport
nazarhussain Oct 14, 2024
38e0c50
Fix types
nazarhussain Oct 14, 2024
a6531c7
Fix unti tests
nazarhussain Oct 14, 2024
b103cf5
Fix unit test
nazarhussain Oct 14, 2024
384b5cb
Fix lint error
nazarhussain Oct 14, 2024
d449d16
Fix a unit test pattern
nazarhussain Oct 14, 2024
4f31ed9
Fix formatting
nazarhussain Oct 14, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
88 changes: 33 additions & 55 deletions biome.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -24,27 +24,8 @@
"enabled": true,
"rules": {
"recommended": true,
"complexity": {
"noForEach": "off",
"noStaticOnlyClass": "off",
"noThisInStatic": "off",
"noUselessEmptyExport": "off",
"noUselessTypeConstraint": "error",
"useArrowFunction": "off",
"useFlatMap": "off",
"useLiteralKeys": "off",
"useOptionalChain": "off",
"useRegexLiterals": "off",
"noBannedTypes": "error",
"noUselessThisAlias": "error"
},
"correctness": {
"noInvalidConstructorSuper": "off",
"noInvalidUseBeforeDeclaration": "off",
"noPrecisionLoss": "error",
"noUnusedVariables": "error",
"noVoidTypeReturn": "off",
"useYield": "off",
"useImportExtensions": {
"level": "error",
"options": {
Expand All @@ -57,33 +38,41 @@
}
},
"useArrayLiterals": "error",
"noUndeclaredDependencies": "off", // TODO: Need to see why this rule is not detecting monorepo packages
"noUndeclaredVariables": "error"
},
"performance": {
"noAccumulatingSpread": "off",
// This rule should be enabled but with considerations and careful review
"noDelete": "off"
},
"style": {
// The code usage looks suspicious so it should be enabled in a separate PR
"noCommaOperator": "off",
"noInferrableTypes": "off",
"noNonNullAssertion": "error",
// There are a lot of places we mutate params, should be fixed in an independent PR.
"noParameterAssign": "off",
"noRestrictedGlobals": {
"level": "error",
"options": {
"deniedGlobals": ["fetch"]
}
},
"noUnusedTemplateLiteral": "off",
"noUselessElse": "off",
"noVar": "error",
"useConst": "error",
"useEnumInitializers": "off",
// We prefer to use `Math.pow` over `**` operator
"useExponentiationOperator": "off",
// In some cases the enums are initialized with values of other enums
"useLiteralEnumMembers": "off",
// We prefer to have multiple declarations lines
"useSingleVarDeclarator": "off",
// We use `+` operator for string concatenation a lot
"useTemplate": "off",
// We use to export types and object without differentiating
"useExportType": "off",
wemeetagain marked this conversation as resolved.
Show resolved Hide resolved
// We use to import types and object without differentiating
"useImportType": "off",
"useLiteralEnumMembers": "off",
// It's nice to use `Number` namespace but should be done in a separate PR
"useNumberNamespace": "off",
// We prefer to auto-initialize enums
"useEnumInitializers": "off",
"noVar": "error",
"useConst": "error",
"useNamingConvention": {
"level": "error",
"options": {
Expand Down Expand Up @@ -194,34 +183,14 @@
]
}
},
"useNumberNamespace": "off",
"useSingleVarDeclarator": "off",
"useTemplate": "off",
"noNamespace": "error",
"useAsConstAssertion": "error"
"noNamespace": "error"
},
"suspicious": {
"noAssignInExpressions": "error",
"noAsyncPromiseExecutor": "off",
// `void` as type is useful in our case when used as generic constraint e.g. K extends number | void
"noConfusingVoidType": "off",
"noConsoleLog": "error",
"noDoubleEquals": "off",
"noDuplicateTestHooks": "off",
"noExplicitAny": "error",
"noExportsInTest": "off",
"noFallthroughSwitchClause": "off",
"noGlobalIsFinite": "off",
"noGlobalIsNan": "off",
"noImplicitAnyLet": "off",
"noPrototypeBuiltins": "off",
"noRedundantUseStrict": "off",
"noShadowRestrictedNames": "off",
"useDefaultSwitchClauseLast": "off",
"useGetterReturn": "off",
"noExtraNonNullAssertion": "error",
"noMisleadingInstantiator": "error",
"noUnsafeDeclarationMerging": "error",
"noEmptyBlockStatements": "off" // There is a lot of empty code blocks, should be enabled and clean up separately.
// There is a lot of empty code blocks, should be enabled and clean up separately.
"noEmptyBlockStatements": "off",
"noConsoleLog": "error"
},
"nursery": {
"useConsistentMemberAccessibility": {
Expand Down Expand Up @@ -369,7 +338,16 @@
{
"include": ["**/test/**/*.test.ts"],
"linter": {
"rules": {}
"rules": {
"complexity": {
// During tests we often need to use private/protected attributes, which is only possible with literal keys
"useLiteralKeys": "off"
},
"suspicious": {
// During tests it's quicker to define variables with `let` without specifying types
"noImplicitAnyLet": "off"
}
}
}
}
]
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/beacon/server/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ export function getRoutes(config: ChainForkConfig, methods: ApplicationMethods<E
try {
// Add injected headers from other plugins. This is required for fastify-cors for example
// From: https://github.com/NodeFactoryIo/fastify-sse-v2/blob/b1686a979fbf655fb9936c0560294a0c094734d4/src/plugin.ts
Object.entries(res.getHeaders()).forEach(([key, value]) => {
for (const [key, value] of Object.entries(res.getHeaders())) {
if (value !== undefined) res.raw.setHeader(key, value);
});
}

res.raw.setHeader("Content-Type", "text/event-stream");
res.raw.setHeader("Cache-Control", "no-cache,no-transform");
Expand Down
3 changes: 1 addition & 2 deletions packages/api/src/utils/client/eventSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
export async function getEventSource(): Promise<typeof EventSource> {
if (globalThis.EventSource) {
return EventSource;
} else {
return (await import("eventsource")).default as unknown as typeof EventSource;
}
return (await import("eventsource")).default as unknown as typeof EventSource;
}
36 changes: 17 additions & 19 deletions packages/api/src/utils/client/httpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,10 @@ export class HttpClient implements IHttpClient {

if (init.retries > 0) {
return this.requestWithRetries(definition, args, init);
} else {
return this.getRequestMethod(init)(definition, args, init);
}
} else {
return this.requestWithFallbacks(definition, args, localInit);
return this.getRequestMethod(init)(definition, args, init);
}
return this.requestWithFallbacks(definition, args, localInit);
}

/**
Expand Down Expand Up @@ -252,19 +250,16 @@ export class HttpClient implements IHttpClient {
});
if (res.ok) {
return res;
} else {
if (i >= this.urlsInits.length - 1) {
return res;
} else {
this.logger?.debug("Request error, retrying", {}, res.error() as Error);
}
}
if (i >= this.urlsInits.length - 1) {
return res;
}
this.logger?.debug("Request error, retrying", {}, res.error() as Error);
} catch (e) {
if (i >= this.urlsInits.length - 1) {
throw e;
} else {
this.logger?.debug("Request error, retrying", {}, e as Error);
}
this.logger?.debug("Request error, retrying", {}, e as Error);
}
}

Expand Down Expand Up @@ -352,7 +347,9 @@ export class HttpClient implements IHttpClient {

// Attach global/local signal to this request's controller
const onSignalAbort = (): void => controller.abort();
abortSignals.forEach((s) => s?.addEventListener("abort", onSignalAbort));
for (const s of abortSignals) {
s?.addEventListener("abort", onSignalAbort);
}

const routeId = definition.operationId;
const {printableUrl, requestWireFormat, responseWireFormat} = init;
Expand Down Expand Up @@ -389,19 +386,20 @@ export class HttpClient implements IHttpClient {
if (isAbortedError(e)) {
if (abortSignals.some((s) => s?.aborted)) {
throw new ErrorAborted(`${routeId} request`);
} else if (controller.signal.aborted) {
}
if (controller.signal.aborted) {
throw new TimeoutError(`${routeId} request`);
} else {
throw Error("Unknown aborted error");
}
} else {
throw e;
throw Error("Unknown aborted error");
}
throw e;
} finally {
timer?.();

clearTimeout(timeout);
abortSignals.forEach((s) => s?.removeEventListener("abort", onSignalAbort));
for (const s of abortSignals) {
s?.removeEventListener("abort", onSignalAbort);
}
}
}

Expand Down
6 changes: 2 additions & 4 deletions packages/api/src/utils/client/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,8 @@ export class ApiResponse<E extends Endpoint> extends Response {
if (this.status === HttpStatusCode.NO_CONTENT) {
this._wireFormat = null;
return this._wireFormat;
} else {
throw Error("Content-Type header is required in response");
}
throw Error("Content-Type header is required in response");
}

const mediaType = parseContentTypeHeader(contentType);
Expand Down Expand Up @@ -197,9 +196,8 @@ export class ApiResponse<E extends Endpoint> extends Response {
return `${errJson.message}\n` + errJson.failures.map((e) => e.message).join("\n");
}
return errJson.message;
} else {
return errBody;
}
return errBody;
} catch (_e) {
return errBody || this.statusText;
}
Expand Down
6 changes: 3 additions & 3 deletions packages/api/src/utils/codecs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,11 @@ export const EmptyResponseCodec: ResponseCodec<EmptyResponseEndpoint> = {
export function ArrayOf<T>(elementType: Type<T>, limit = Infinity): ArrayType<Type<T>, unknown, unknown> {
if (isCompositeType(elementType)) {
return new ListCompositeType(elementType, limit) as unknown as ArrayType<Type<T>, unknown, unknown>;
} else if (isBasicType(elementType)) {
}
if (isBasicType(elementType)) {
return new ListBasicType(elementType, limit) as unknown as ArrayType<Type<T>, unknown, unknown>;
} else {
throw Error(`Unknown type ${elementType.typeName}`);
}
throw Error(`Unknown type ${elementType.typeName}`);
}

export function WithMeta<T, M extends {version: ForkName}>(getType: (m: M) => Type<T>): ResponseDataCodec<T, M> {
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/utils/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export function parseAcceptHeader(accept?: string, supported = SUPPORTED_MEDIA_T
}

const qvalue = +weight.replace("q=", "");
if (isNaN(qvalue) || qvalue > 1 || qvalue <= 0) {
if (Number.isNaN(qvalue) || qvalue > 1 || qvalue <= 0) {
// If we can't convert the qvalue to a valid number, move on
return best;
}
Expand Down
2 changes: 0 additions & 2 deletions packages/api/src/utils/httpStatusCode.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
"use strict";

/**
* Hypertext Transfer Protocol (HTTP) response status codes.
* @see {@link https://www.rfc-editor.org/rfc/rfc7231#section-6}
Expand Down
5 changes: 2 additions & 3 deletions packages/api/src/utils/serdes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ export function querySerializeProofPathsArr(paths: JsonPath[]): string[] {
export function queryParseProofPathsArr(pathStrs: string | string[]): JsonPath[] {
if (Array.isArray(pathStrs)) {
return pathStrs.map((pathStr) => queryParseProofPaths(pathStr));
} else {
return [queryParseProofPaths(pathStrs)];
}
return [queryParseProofPaths(pathStrs)];
}

/**
Expand Down Expand Up @@ -50,7 +49,7 @@ export type U64Str = string;

export function fromU64Str(u64Str: U64Str): number {
const u64 = parseInt(u64Str, 10);
if (!isFinite(u64)) {
if (!Number.isFinite(u64)) {
throw Error(`Invalid uin64 ${u64Str}`);
}
return u64;
Expand Down
6 changes: 3 additions & 3 deletions packages/api/test/unit/client/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import http from "node:http";
import {describe, it, expect, afterEach} from "vitest";
import {FetchError, FetchErrorType, fetch} from "../../../src/utils/client/fetch.js";

describe("FetchError", function () {
describe("FetchError", () => {
const port = 37421;
const randomHex = crypto.randomBytes(32).toString("hex");

Expand Down Expand Up @@ -87,7 +87,7 @@ describe("FetchError", function () {

const afterHooks: (() => Promise<void>)[] = [];

afterEach(async function () {
afterEach(async () => {
while (afterHooks.length) {
const afterHook = afterHooks.pop();
if (afterHook)
Expand All @@ -100,7 +100,7 @@ describe("FetchError", function () {
for (const testCase of testCases) {
const {id, url = `http://localhost:${port}`, requestListener, signalHandler} = testCase;

it(id, async function () {
it(id, async () => {
if (requestListener) {
const server = http.createServer(requestListener);
await new Promise<void>((resolve) => server.listen(port, resolve));
Expand Down
8 changes: 4 additions & 4 deletions packages/api/test/unit/client/httpClientFallback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@ describe("httpClient fallback", () => {
// which is handled separately from network errors
// but the fallback logic should be the same
return new Response(null, {status: 500});
} else {
throw Error(`test_error_server_${i}`);
}
} else {
return new Response(null, {status: 200});

throw Error(`test_error_server_${i}`);
}

return new Response(null, {status: 200});
});
});

Expand Down
10 changes: 6 additions & 4 deletions packages/api/test/utils/checkAgainstSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,13 @@ export function runTestCheckAgainstSpec<Es extends Record<string, Endpoint>>(
}
});

it(`${operationId}_route`, function () {
it(`${operationId}_route`, () => {
expect(routeDef.method.toLowerCase()).toBe(routeSpec.method.toLowerCase());
expect(routeDef.url).toBe(routeSpec.url);
});

if (requestSchema != null) {
it(`${operationId}_request`, function () {
it(`${operationId}_request`, () => {
const reqJson = isRequestWithoutBody(routeDef)
? routeDef.req.writeReq(testData.args)
: (routeDef.req as RequestWithBodyCodec<Es[string]>).writeReqJson(testData.args);
Expand Down Expand Up @@ -135,7 +135,7 @@ export function runTestCheckAgainstSpec<Es extends Record<string, Endpoint>>(
}

if (responseOkSchema) {
it(`${operationId}_response`, function () {
it(`${operationId}_response`, () => {
const data = routeDef.resp.data.toJson(testData.res?.data, testData.res?.meta);
const metaJson = routeDef.resp.meta.toJson(testData.res?.meta);
const headers = parseHeaders(routeDef.resp.meta.toHeadersObject(testData.res?.meta));
Expand Down Expand Up @@ -218,7 +218,9 @@ type StringifiedProperty = string | StringifiedProperty[];
function stringifyProperty(value: unknown): StringifiedProperty {
if (typeof value === "number") {
return value.toString(10);
} else if (Array.isArray(value)) {
}

if (Array.isArray(value)) {
return value.map(stringifyProperty);
}
return String(value);
Expand Down
2 changes: 1 addition & 1 deletion packages/api/test/utils/parseOpenApiSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ function preprocessSchema(schema: JsonSchema): void {

// Remove non-intersecting allOf enum
applyRecursively(schema, (obj) => {
if (obj.allOf && obj.allOf.every((s) => s.enum)) {
if (obj.allOf?.every((s) => s.enum)) {
obj.allOf = [obj.allOf[0]];
}
});
Expand Down
Loading
Loading