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

fix(lint): Upgrade ESLint #704

Merged
merged 16 commits into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions bin/cli/src/lib/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export class LabeledProcessRunner {
}

let maxLength = 0;
for (let pre in this.prefixColors) {
for (const pre in this.prefixColors) {
if (pre.length > maxLength) {
maxLength = pre.length;
}
Expand All @@ -50,7 +50,7 @@ export class LabeledProcessRunner {
private sanitizeInput(input) {
// A basic pattern that allows letters, numbers, dashes, underscores, and periods
// Adjust the pattern to fit the expected input format
const sanitizedInput = input.replace(/[^a-zA-Z0-9-_\.]/g, "");
const sanitizedInput = input.replace(/[^a-zA-Z0-9-_.]/g, "");
return sanitizedInput;
}

Expand Down Expand Up @@ -90,7 +90,7 @@ export class LabeledProcessRunner {
const handleOutput = (data: Buffer, prefix: string, silenced: boolean) => {
const paddedPrefix = this.formattedPrefix(prefix);
if (!silenced)
for (let line of data.toString().split("\n")) {
for (const line of data.toString().split("\n")) {
process.stdout.write(`${paddedPrefix} ${line}\n`);
}
};
Expand Down
5 changes: 3 additions & 2 deletions bin/cli/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
} from "./commands";

yargs
.fail((msg, err, _) => {
.fail((msg, err) => {
if (err) throw err;
if (msg) console.error(msg);
process.exit(1);
Expand All @@ -32,4 +32,5 @@ yargs
.command(getCost)
.strict()
.scriptName("run")
.demandCommand(1, "").argv;
.demandCommand(1, "")
.parse();
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Calling .parse() with no arguments is equivalent to calling .argv:
require('yargs/yargs')(process.argv.slice(2)).parse()

docs

Binary file modified bun.lockb
Binary file not shown.
2 changes: 1 addition & 1 deletion docs/_deploy-metrics/components/CheckboxFilter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type CheckboxFilterProps = Omit<UI.CheckboxGroupProps, "onChange"> & {
};

export const CheckboxFilter = (props: CheckboxFilterProps) => {
const { options, label, spacing = "2", showSearch, ...rest } = props;
const { options, label, spacing = "2", ...rest } = props;

return (
<UI.Stack as="fieldset" spacing={spacing}>
Expand Down
6 changes: 4 additions & 2 deletions docs/_deploy-metrics/components/ResourceTable.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
/* eslint-disable */

import * as UI from "@chakra-ui/react";
import { formatDistance } from "date-fns";
import { Resource } from "../lib/getAwsResources";

const ResourceTypeLabel = ({ type }: { type: string }) => {
let iconName = type.split("::")[1];
const iconName = type.split("::")[1];
try {
var ICON = require(`react-aws-icons/dist/aws/logo/${iconName}`).default;
} catch (ex) {
} catch {
var ICON = require(`react-aws-icons/dist/aws/logo/AWS`).default;
}

Expand Down
2 changes: 2 additions & 0 deletions docs/_deploy-metrics/lib/formData.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* eslint no-prototype-builtins: 0 */ // --> OFF

export type FormResult = {
version: string;
data: any; // replace 'any' with the actual type of the data returned from the API
Expand Down
2 changes: 2 additions & 0 deletions docs/_deploy-metrics/next.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* eslint no-undef: 0 */ // --> OFF

/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
Expand Down
60 changes: 60 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// @ts-check
import react from "eslint-plugin-react";
import eslintReactHooks from "eslint-plugin-react-hooks";
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
import { fixupPluginRules, includeIgnoreFile } from "@eslint/compat";
import { fileURLToPath } from "url";
import path from "path";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const gitignorePath = path.resolve(__dirname, ".gitignore");

export default tseslint.config(
eslint.configs.recommended,
...tseslint.configs.recommended,
// @ts-expect-error https://github.com/typescript-eslint/typescript-eslint/issues/8522
includeIgnoreFile(gitignorePath),
{
plugins: {
react,
// @ts-expect-error https://github.com/facebook/react/pull/28773#issuecomment-2147149016
"react-hooks": fixupPluginRules(eslintReactHooks),
},
languageOptions: {
ecmaVersion: 2020,
sourceType: "module",

parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
},

settings: {
react: {
version: "detect",
},
},

rules: {
"@typescript-eslint/no-empty-interface": "off",
"react/react-in-jsx-scope": "off",
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/ban-ts-comment": [
"off",
{
"ts-ignore": false,
"ts-nocheck": false,
"ts-check": true,
"ts-expect-error": true,
},
],
},
},
);
4 changes: 0 additions & 4 deletions lib/lambda/checkConsumerLag.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { handler } from "./checkConsumerLag";
import { Kafka } from "kafkajs";
import {
LambdaClient,
ListEventSourceMappingsCommand,
} from "@aws-sdk/client-lambda";

const mockKafkaAdmin = {
connect: vi.fn(),
Expand Down
1 change: 0 additions & 1 deletion lib/lambda/createTriggers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
CreateEventSourceMappingCommand,
GetEventSourceMappingCommand,
} from "@aws-sdk/client-lambda";
import { randomUUID } from "crypto";

vi.mock("@aws-sdk/client-lambda", () => ({
LambdaClient: vi.fn().mockImplementation(() => ({
Expand Down
3 changes: 1 addition & 2 deletions lib/lambda/deleteTriggers.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { handler, deleteAllTriggersForFunctions } from "./deleteTriggers";
import { handler } from "./deleteTriggers";
import {
LambdaClient,
ListEventSourceMappingsCommand,
DeleteEventSourceMappingCommand,
GetEventSourceMappingCommand,
} from "@aws-sdk/client-lambda";

vi.mock("@aws-sdk/client-lambda", () => ({
Expand Down
2 changes: 0 additions & 2 deletions lib/lambda/getAttachmentUrl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { APIGatewayEvent } from "aws-lambda";
import { handler } from "./getAttachmentUrl";
import { response } from "libs/handler-lib";
import { STSClient, AssumeRoleCommand } from "@aws-sdk/client-sts";
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { getStateFilter } from "../libs/api/auth/user";
import { getPackage, getPackageChangelog } from "../libs/api/package";
Expand Down
2 changes: 1 addition & 1 deletion lib/lambda/getCpocs.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { APIGatewayEvent } from "aws-lambda";
import { handler, queryCpocs } from "./getCpocs";
import { handler } from "./getCpocs";
import { response } from "libs/handler-lib";
import * as os from "libs/opensearch-lib";

Expand Down
2 changes: 1 addition & 1 deletion lib/lambda/getPackageActions.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { APIGatewayEvent } from "aws-lambda";
import { handler, getPackageActions } from "./getPackageActions";
import { handler } from "./getPackageActions";
import { response } from "libs/handler-lib";
import { getAvailableActions } from "shared-utils";
import { getPackage } from "../libs/api/package/getPackage";
Expand Down
2 changes: 1 addition & 1 deletion lib/lambda/getSubTypes.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { APIGatewayEvent } from "aws-lambda";
import { handler, querySubTypes } from "./getSubTypes";
import { handler } from "./getSubTypes";
import { response } from "libs/handler-lib";
import * as os from "libs/opensearch-lib";

Expand Down
2 changes: 1 addition & 1 deletion lib/lambda/getTypes.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { APIGatewayEvent } from "aws-lambda";
import { handler, queryTypes } from "./getTypes";
import { handler } from "./getTypes";
import { response } from "libs/handler-lib";
import * as os from "libs/opensearch-lib";

Expand Down
21 changes: 12 additions & 9 deletions lib/lambda/getUploadUrl.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { describe, it, expect, vi, beforeEach, Mock } from "vitest";
import { APIGatewayEvent } from "aws-lambda";
import { handler } from "./getUploadUrl";
import { response } from "libs/handler-lib";
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { v4 as uuidv4 } from "uuid";
import * as path from "node:path";

vi.mock("libs/handler-lib", () => ({
response: vi.fn(),
Expand All @@ -29,7 +27,7 @@ describe("Handler for generating signed URL", () => {
vi.clearAllMocks();
process.env.attachmentsBucketName = "test-bucket";
process.env.attachmentsBucketRegion = "test-region";
(uuidv4 as vi.Mock).mockReturnValue("123e4567-e89b-12d3-a456-426614174000");
(uuidv4 as Mock).mockReturnValue("123e4567-e89b-12d3-a456-426614174000");
});

it("should return 400 if event body is missing", async () => {
Expand All @@ -45,7 +43,7 @@ describe("Handler for generating signed URL", () => {

it("should return 200 with signed URL, bucket, and key", async () => {
const mockUrl = "https://example.com/signed-url";
(getSignedUrl as vi.Mock).mockResolvedValueOnce(mockUrl);
(getSignedUrl as Mock).mockResolvedValueOnce(mockUrl);

const event = {
body: JSON.stringify({ fileName: "test-file.pdf" }),
Expand All @@ -61,11 +59,11 @@ describe("Handler for generating signed URL", () => {
key: "123e4567-e89b-12d3-a456-426614174000.pdf",
},
});
expect(getSignedUrl).toHaveBeenCalled;
expect(getSignedUrl).toHaveBeenCalled();
});

it("should return 500 if an error occurs during processing", async () => {
(getSignedUrl as vi.Mock).mockRejectedValueOnce(new Error("Test error"));
(getSignedUrl as Mock).mockRejectedValueOnce(new Error("Test error"));

const event = {
body: JSON.stringify({ fileName: "test-file.pdf" }),
Expand All @@ -79,9 +77,14 @@ describe("Handler for generating signed URL", () => {
});
});

it("should throw an error if required environment variables are missing", () => {
it("should throw an error if required environment variables are missing", async () => {
delete process.env.attachmentsBucketName;

expect(() => handler({} as APIGatewayEvent)).toThrowError;
await handler({} as APIGatewayEvent);
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test never ran as it was never called – eslint caught the error and I fixed it

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

handler can't have thrown an error because it was being mocked, so we had to spy on the response function like we did in the previous tests


expect(response).toHaveBeenCalledWith({
statusCode: 500,
body: { message: "Internal server error" },
});
});
});
17 changes: 3 additions & 14 deletions lib/lambda/getUploadUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ const s3 = new S3Client({
});

export const handler = async (event: APIGatewayEvent) => {
validateEnvVariable("attachmentsBucketName");
validateEnvVariable("attachmentsBucketRegion");
try {
validateEnvVariable("attachmentsBucketName");
validateEnvVariable("attachmentsBucketRegion");

Comment on lines +15 to +17
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved these into the try so the catch block catches them

if (!event.body) {
return response({
statusCode: 400,
Expand Down Expand Up @@ -48,15 +49,3 @@ export const handler = async (event: APIGatewayEvent) => {
});
}
};

function checkEnvVariables(requiredEnvVariables: string[]) {
const missingVariables = requiredEnvVariables.filter(
(envVar) => !process.env[envVar],
);

if (missingVariables.length > 0) {
throw new Error(
`Missing required environment variables: ${missingVariables.join(", ")}`,
);
}
}
1 change: 0 additions & 1 deletion lib/lambda/mapRole.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { Handler } from "aws-lambda";
import { send, SUCCESS, FAILED } from "cfn-response-async";
import { handler } from "./mapRole";
import * as os from "../libs/opensearch-lib";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { assert, describe, expect, it, vi } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { withdrawPackage } from "./withdraw-package";
import { generateMock } from "@anatine/zod-mock";
import { withdrawPackageSchema } from "shared-types";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
WithdrawPackage,
withdrawPackageSchema,
SEATOOL_STATUS,
Action,
} from "shared-types";
import { withdrawPackageSchema, SEATOOL_STATUS, Action } from "shared-types";
import { seaToolFriendlyTimestamp } from "shared-utils";
import { response } from "../../../libs/handler-lib";
import { TOPIC_NAME } from "../consts";
Expand Down
20 changes: 10 additions & 10 deletions lib/lambda/postAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { getSecret } from "shared-utils";
// Initialize Cognito client
const client = new CognitoIdentityProviderClient({});

export const handler: Handler = async (event, context) => {
export const handler: Handler = async (event) => {
console.log(JSON.stringify(event, null, 2));

// Check if idmInfoSecretArn is provided
Expand All @@ -30,7 +30,7 @@ export const handler: Handler = async (event, context) => {
throw error;
}

const { request, response } = event;
const { request } = event;
const { userAttributes } = request;

if (!userAttributes.identities) {
Expand All @@ -56,12 +56,12 @@ export const handler: Handler = async (event, context) => {
`Network response was not ok. Response was ${response.status}: ${response.statusText}`,
);
}
let data = await response.json();
const data = await response.json();
console.log(JSON.stringify(data, null, 2));
let roleArray: string[] = [];
let stateArray: string[] = [];
const roleArray: string[] = [];
const stateArray: string[] = [];
data.userProfileAppRoles.userRolesInfoList.forEach((element: any) => {
let role = element.roleName;
const role = element.roleName;
if (Object.values(UserRoles).includes(role)) {
roleArray.push(role);
if (STATE_ROLES.includes(role)) {
Expand All @@ -74,7 +74,7 @@ export const handler: Handler = async (event, context) => {
}
});

let attributeData: any = {
const attributeData: any = {
Username: event.userName,
UserPoolId: event.userPoolId,
UserAttributes: [
Expand Down Expand Up @@ -126,7 +126,7 @@ async function updateUserAttributes(params: any): Promise<void> {
: [];

// Prepare for updating user attributes
let attributeData: any = {
const attributeData: any = {
UserPoolId: params.UserPoolId,
Username: params.Username,
UserAttributes: params.UserAttributes,
Expand All @@ -139,7 +139,7 @@ async function updateUserAttributes(params: any): Promise<void> {
);
if (rolesIndex !== -1) {
// Only merge if new roles are not empty
let newRoles = attributeData.UserAttributes[rolesIndex].Value
const newRoles = attributeData.UserAttributes[rolesIndex].Value
? new Set(
attributeData.UserAttributes[rolesIndex].Value.split(",").concat(
"onemac-micro-super",
Expand All @@ -164,7 +164,7 @@ async function updateUserAttributes(params: any): Promise<void> {
);
if (stateIndex !== -1) {
// Only merge if new states are not empty
let newStates = attributeData.UserAttributes[stateIndex].Value
const newStates = attributeData.UserAttributes[stateIndex].Value
? new Set(
attributeData.UserAttributes[stateIndex].Value.split(",").concat(
"ZZ",
Expand Down
Loading
Loading