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: various fixes suggested from eslint #174

Merged
merged 7 commits into from
Jul 3, 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
11 changes: 9 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ module.exports = {
plugins: ['@typescript-eslint'],
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'],
rules: {
'@typescript-eslint/no-unused-vars': 'error',
'@typescript-eslint/consistent-type-definitions': ['error', 'type']
'@typescript-eslint/no-unused-vars': [
'error',
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_"
}
],
'@typescript-eslint/consistent-type-definitions': ['error', 'type'],
"no-control-regex": 0
}
};
8 changes: 4 additions & 4 deletions pkg/core/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ export type ResultOk = { ok: true; value: Jsonable };
/**
* Result of a plugin execution, indicating failure.
*/
export type ResultErr = { ok: false; error: any };
export type ResultErr = { ok: false; error: Error };

/**
* The Plugin Context. It has every info a plugin needs, plus some utilities.
Expand Down Expand Up @@ -453,7 +453,7 @@ export type PluginContext = {
* The utility function that makes a {@link Plugin} fail. Must be used with a
* `return` statement.
*/
fail(reason: any): PluginResult;
fail(reason: Error): PluginResult;

/**
* The utility function that makes a {@link Plugin} pass/succeed. Must be used with
Expand Down Expand Up @@ -489,7 +489,7 @@ export class PluginContextImpl implements PluginContext {
/**
* {@inheritDoc PluginContext.fail}
*/
fail(reason: any): PluginResult {
fail(reason: Error): PluginResult {
return { ok: false, error: reason };
}

Expand Down Expand Up @@ -592,7 +592,7 @@ export class PluginContextTest implements PluginContext {
/**
* {@inheritDoc PluginContext.fail}
*/
fail(reason: any): PluginResult {
fail(reason: Error): PluginResult {
return { ok: false, error: reason };
}

Expand Down
4 changes: 2 additions & 2 deletions pkg/core/src/slangroom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ const thorwErrors = (errorArray: GenericError[], contract: string) => {
for (let i = lineStart; i < lineEnd; i++) {
const linePrefix = `${i} | `;
if (i === lineNumber -1) {
let boldError = textHighlight(contractLines[i]!.slice(colStart, colEnd));
const boldError = textHighlight(contractLines[i]!.slice(colStart, colEnd));
const redBackground = sentenceHighlight(contractLines[i]!.slice(0, colStart) + boldError + contractLines[i]!.slice(colEnd));
e = e.concat(`${lineNoColor(linePrefix)}${redBackground}\n`);
e = e.concat(' '.repeat(colStart + linePrefix.length) + errorColor('^'.repeat(colEnd - colStart)) + '\n');
Expand All @@ -168,7 +168,7 @@ const thorwErrors = (errorArray: GenericError[], contract: string) => {
e = e.concat(` - ${missingColor('missing words')}\n`);
e = e.concat(` - ${extraColor('extra words')}\n`);

for (let err of errorArray) {
for (const err of errorArray) {
e = e.concat('\n' + err.message + '\n');
}
throw new Error(e);
Expand Down
4 changes: 2 additions & 2 deletions pkg/core/test/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,9 @@ test('PluginContext', async (t) => {
const objCtx = new PluginContextTest('', {obj: 'obj'});
// pass and fail
const pass = p.new('test pass', (ctx) => ctx.pass('done'));
const fail = p.new('test fail', (ctx) => ctx.fail('failed'));
const fail = p.new('test fail', (ctx) => ctx.fail(new Error ('failed')));
t.deepEqual(await pass(emptyCtx), { ok: true, value: 'done' });
t.deepEqual(await fail(emptyCtx), { ok: false, error: 'failed' });
t.deepEqual(await fail(emptyCtx), { ok: false, error: new Error('failed') });
// connect
const getConnect = p.new('connect', 'test get connect', (ctx) => ctx.pass(ctx.getConnect()));
const fetchConnect = p.new('connect', 'test fetch connect', (ctx) => ctx.pass(ctx.fetchConnect()));
Expand Down
2 changes: 1 addition & 1 deletion pkg/git/test/e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,6 @@ test.serial('Should create a new git commit', async (t) => {
t.truthy(typeof res.result['commit_hash'] === 'string');
})

test.after.always('guaranteed cleanup', async (_t) => {
test.after.always('guaranteed cleanup', async () => {
await fs.rm('./test/dumb', { recursive: true })
});
15 changes: 8 additions & 7 deletions pkg/helpers/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later

import { Plugin } from '@slangroom/core';
import type { JsonableObject, JsonableArray } from '@slangroom/shared';
import _ from 'lodash';
// read the version from the package.json
import packageJson from '@slangroom/helpers/package.json' with { type: 'json' };
Expand All @@ -20,7 +21,7 @@ export const get = p.new(['object', 'path'], 'manipulate and get', async (ctx) =
const object = ctx.fetch('object');
const path = ctx.fetch('path');
try {
return ctx.pass(_.get(object as any, path as string));
return ctx.pass(_.get(object as JsonableObject, path as string));
} catch (e) {
return ctx.fail(new HelperError(e));
}
Expand All @@ -31,7 +32,7 @@ export const set = p.new(['object', 'path', 'value'], 'manipulate and set', asyn
const path = ctx.fetch('path');
const value = ctx.fetch('value');
try {
return ctx.pass(_.set(object as any, path as string, value));
return ctx.pass(_.set(object as JsonableObject, path as string, value));
} catch (e) {
return ctx.fail(new HelperError(e));
}
Expand All @@ -41,7 +42,7 @@ export const merge = p.new(['object', 'sources'], 'manipulate and merge', async
const object = ctx.fetch('object');
const sources = ctx.fetch('sources');
try {
return ctx.pass(_.merge(object as any, ...sources as any[]));
return ctx.pass(_.merge(object as JsonableObject, ...sources as JsonableArray));
} catch (e) {
return ctx.fail(new HelperError(e));
}
Expand All @@ -51,7 +52,7 @@ export const omit = p.new(['object', 'paths'], 'manipulate and omit', async (ctx
const object = ctx.fetch('object');
const paths = ctx.fetch('paths');
try {
return ctx.pass(_.omit(object as any, paths as any[]));
return ctx.pass(_.omit(object as JsonableObject, paths as string[]));
} catch (e) {
return ctx.fail(new HelperError(e));
}
Expand All @@ -61,7 +62,7 @@ export const concat = p.new(['array', 'values'], 'manipulate and concat', async
const array = ctx.fetch('array');
const values = ctx.fetch('values');
try {
return ctx.pass(_.concat(array as any[], ...values as any[]));
return ctx.pass(_.concat(array as JsonableArray, ...values as JsonableArray));
} catch (e) {
return ctx.fail(new HelperError(e));
}
Expand All @@ -70,15 +71,15 @@ export const concat = p.new(['array', 'values'], 'manipulate and concat', async
export const compact = p.new(['array'], 'manipulate and compact', async (ctx) => {
const array = ctx.fetch('array');
try {
return ctx.pass(_.compact(array as any[]));
return ctx.pass(_.compact(array as JsonableArray));
} catch (e) {
return ctx.fail(new HelperError(e));
}
});

export const pick = p.new(['object', 'properties'], 'manipulate and pick', async (ctx) => {
const properties = ctx.fetch('properties') as string[] | string;
const obj = ctx.fetch('object') as {};
const obj = ctx.fetch('object') as JsonableObject;
try {
const manipulated = _.pick(obj, properties);
if (Object.keys(manipulated).length === 0) {
Expand Down
38 changes: 24 additions & 14 deletions pkg/http/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
//
// SPDX-License-Identifier: AGPL-3.0-or-later

import type { JsonableArray, JsonableObject } from '@slangroom/shared';
import type { Jsonable, JsonableArray, JsonableObject } from '@slangroom/shared';
import { Plugin, type PluginExecutor } from '@slangroom/core';
import axios, { type AxiosRequestConfig } from 'axios';
import axios, { type AxiosRequestConfig, type AxiosHeaders } from 'axios';
// read the version from the package.json
import packageJson from '@slangroom/http/package.json' with { type: 'json' };

Expand Down Expand Up @@ -34,7 +34,7 @@ const defaultRequest = (m: HttpMethod): PluginExecutor => {
return async (ctx) => {
const url = ctx.fetchConnect()[0];
// TODO: typecheck headers
const headers = ctx.get('headers') as any;
const headers = ctx.get('headers') as AxiosHeaders;
const object = ctx.get('object');
const conf: AxiosRequestConfig = { url: url, method: m };
if (object) conf.data = object;
Expand All @@ -51,10 +51,10 @@ const defaultRequest = (m: HttpMethod): PluginExecutor => {

const sameParallelRequest = (m: HttpMethod, isSame: boolean): PluginExecutor => {
return async (ctx) => {
const reqs: ReturnType<typeof request<any>>[] = [];
const reqs: ReturnType<typeof request<AxiosRequestConfig>>[] = [];
const urls = ctx.fetchConnect();
// TODO: typecheck headers
const headers = ctx.get('headers') as any;
const headers = ctx.get('headers') as AxiosHeaders;

if (isSame) {
// TODO: typecheck object JsonableObject
Expand All @@ -78,15 +78,25 @@ const sameParallelRequest = (m: HttpMethod, isSame: boolean): PluginExecutor =>
}
}

const results = (await Promise.allSettled(reqs)).map((x) => {
if (x.status === 'fulfilled')
return { status: x.value.status.toString(), result: x.value.data };

const err = x.reason;
if (axios.isAxiosError(err)) return { status: err.code ?? '', result: '' };

return ctx.fail(new HttpError(err.message));
});
const results: { status: string, result: Jsonable }[] = [];
try {
(await Promise.allSettled(reqs)).map((x) => {
if (x.status === 'fulfilled') {
results.push({ status: x.value.status.toString(), result: x.value.data as Jsonable });
return;
}

const err = x.reason;
if (axios.isAxiosError(err)) {
results.push({ status: err.code ?? '', result: '' });
return;
}

throw new HttpError(err.message);
})
} catch (e) {
ctx.fail(new HttpError(e.message));
}

return ctx.pass(results);
};
Expand Down
1 change: 1 addition & 0 deletions pkg/http/test/e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ nock('http://localhost')
.get('/greeting-en')
.reply(200, { req: 'Hi!' })
.post('/sendresult')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.reply((_, body: any) => {
const req = body['req'];
if (req?.includes('Hola') || req?.includes('Hi')) return [200, 'received result'];
Expand Down
2 changes: 2 additions & 0 deletions pkg/http/test/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,13 @@ nock('http://localhost')
},
})
.post('/sendresult')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.reply((_, body: any) => {
if (body['myData']) return [200, 'received result'];
return [500, 'Did not receive the result'];
})
.put('/sendresultwithput')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.reply((_, body: any) => {
if (body['myData']) return [200, 'received result'];
return [500, 'Did not receive the result'];
Expand Down
14 changes: 8 additions & 6 deletions pkg/ignored/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ export class InvalidStatementError extends Error {
}
}

type ParseResult = {
result: {
ignored: [string, number][],
invalid: [string, number, string][]
},
logs: string
}

/**
* Check if the statement could be an ignored statement and thus adding Rule unknown ignore can solve the problem
Expand Down Expand Up @@ -57,12 +64,7 @@ const couldBeIgnored = (lineNo: number, contract: string, invalidLinesNos: numbe
export const getIgnoredStatements = async (
contract: string,
): Promise<{ignoredLines: [string, number][], invalidLines: {message: Error, lineNo: number}[]}> => {
let zout: {result: {ignored: [string, number][], invalid: [string, number, string][]}; logs: string};
try {
zout = await zencodeParse(contract);
} catch (e) {
throw e;
}
const zout: ParseResult = await zencodeParse(contract);
const invalidLinesNos: number[] = zout.result.invalid.map((x) => x[1]);
const ruleUnknownIgnore = JSON.parse(zout.logs).some((x: string) => x.toLowerCase().includes('rule unknown ignore'));;
return {
Expand Down
2 changes: 1 addition & 1 deletion pkg/pocketbase/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ export const authWithPassword = p.new(['my_credentials'], 'login', async (ctx) =
*/
export const requestPasswordReset = p.new(['email'], 'ask password reset', async (ctx) => {
const email = ctx.fetch('email') as string;
if (!(await isPbRunning())) return ctx.fail('Client is not running');
if (!(await isPbRunning())) return ctx.fail(new PocketBaseError('Client is not running'));

try {
const res = await pb.collection('users').requestPasswordReset(email);
Expand Down
Loading