Skip to content

Commit

Permalink
More eslint clean-up
Browse files Browse the repository at this point in the history
  • Loading branch information
thoukydides committed Sep 2, 2024
1 parent 45f9ef5 commit ab66fe5
Show file tree
Hide file tree
Showing 17 changed files with 55 additions and 36 deletions.
17 changes: 12 additions & 5 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,17 @@
"image": "mcr.microsoft.com/devcontainers/javascript-node:18",

// VS Code extensions to install automatically
"extensions": [
"dbaeumer.vscode-eslint",
"streetsidesoftware.code-spell-checker"
],
"customizations": {
"vscode": {
"extensions": [
"dbaeumer.vscode-eslint",
"streetsidesoftware.code-spell-checker",
"bierner.markdown-preview-github-styles",
"amazonwebservices.aws-toolkit-vscode",
"Tyriar.sort-lines"
]
}
},

// Finish setup after creating the container
"postCreateCommand": {
Expand All @@ -29,4 +36,4 @@
"onAutoForward": "ignore"
}
}
}
}
10 changes: 7 additions & 3 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
{
"recommendations": [
"dbaeumer.vscode-eslint"
]
"recommendations": [
"dbaeumer.vscode-eslint",
"amazonwebservices.aws-toolkit-vscode",
"streetsidesoftware.code-spell-checker",
"tyriar.sort-lines",
"bierner.markdown-preview-github-styles"
]
}
7 changes: 7 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,17 @@
"AEGAPI",
"AEGO",
"aeiou",
"amazonwebservices",
"Bbyy",
"bierner",
"buymeacoffee",
"Centi",
"Childrens",
"Cleanings",
"Codespaces",
"dbaeumer",
"devcontainer",
"devcontainers",
"DTOs",
"Electrolux",
"eluxiot",
Expand All @@ -33,6 +39,7 @@
"SHALEGREY",
"Thoukydides",
"tseslint",
"Tyriar",
"Unconfigured",
"undici",
"vars",
Expand Down
7 changes: 3 additions & 4 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ export default tseslint.config(
}
},
rules: {
'@typescript-eslint/no-floating-promises': ['error', {}],
'@typescript-eslint/no-misused-promises': ['error', {}],
'@typescript-eslint/no-unused-vars': ['error', { args: 'all', argsIgnorePattern: '^_', ignoreRestSiblings: true }],
'@typescript-eslint/restrict-template-expressions': ['error', { allowBoolean: true, allowNullish: true, allowNumber: true}],
'brace-style': ['warn', '1tbs', { allowSingleLine: true }],
Expand All @@ -46,8 +44,9 @@ export default tseslint.config(
'prefer-arrow-callback': ['warn'],
'quotes': ['warn', 'single', { avoidEscape: true }],
'semi': ['warn'],

'@typescript-eslint/unified-signatures': ['error', { ignoreDifferentlyNamedParameters: true }]
// Special rules for this project
'@typescript-eslint/unified-signatures': ['error', { ignoreDifferentlyNamedParameters: true }],
'@typescript-eslint/explicit-function-return-type': ['error']
}
}, {
files: ['**/*-types.ts'],
Expand Down
2 changes: 1 addition & 1 deletion src/accessory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export class AEGAccessory {
}

// Add a read-only Configured Name characteristic
addServiceName(service: Service, suffix: string, defaultName: string) {
addServiceName(service: Service, suffix: string, defaultName: string): void {
// Add the configured name characteristic
if (!service.testCharacteristic(this.Characteristic.ConfiguredName)) {
service.addOptionalCharacteristic(this.Characteristic.ConfiguredName);
Expand Down
8 changes: 4 additions & 4 deletions src/aeg-account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ export class AEGAccount {
// Start polling for interesting changes
const intervals = this.config.pollIntervals;
const poll: [string, number, () => Promise<void>][] = [
['Appliances', intervals.statusSeconds, () => this.pollAppliances()],
['Server health', intervals.serverHealthSeconds, () => this.pollServerHealth()],
['Feed', intervals.feedSeconds, () => this.pollFeed()]
['Appliances', intervals.statusSeconds, this.pollAppliances.bind(this)],
['Server health', intervals.serverHealthSeconds, this.pollServerHealth.bind(this)],
['Feed', intervals.feedSeconds, this.pollFeed.bind(this)]
];
this.heartbeats = poll.map(action =>
new Heartbeat(this.log, action[0], action[1] * MS, action[2],
Expand Down Expand Up @@ -117,7 +117,7 @@ export class AEGAccount {
// Check the server health
async pollServerHealth(): Promise<void> {
// Check the server health
const isHealthy = (server: HealthCheck) => server.statusCode === 200 && server.message === 'I am alive!';
const isHealthy = (server: HealthCheck): boolean => server.statusCode === 200 && server.message === 'I am alive!';
const servers = await this.api.getHealthChecks();
const failed = servers.filter(server => !isHealthy(server)).length;

Expand Down
4 changes: 2 additions & 2 deletions src/aeg-robot-ctrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ abstract class AEGRobotCtrl<Type extends number | string> {

// Return a set method bound to this instance
makeSetter(): (target: Type) => void {
return (target) => void (async () => { await this.set(target); })();
return (target) => void (async (): Promise<void> => { await this.set(target); })();
}

// Request a change to the robot
Expand Down Expand Up @@ -86,7 +86,7 @@ abstract class AEGRobotCtrl<Type extends number | string> {
do {
// Create mechanism to abort waiting for a status update
const abort = new Promise<'abort'>(resolve =>
this.abort = () => { resolve('abort'); });
this.abort = (): void => { resolve('abort'); });

// Attempt to apply the requested change
target = this.target;
Expand Down
4 changes: 2 additions & 2 deletions src/aeg-robot-log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ export class AEGRobotLog {
this.log.info(` Recharged ${item.data.pitstopCount} times while cleaning`);
break;
case 'OsirisBusierWeekJobDone': {
const formatHours = (hours: number) => formatSeconds(hours * 60 * 60);
const formatHours = (hours: number): string => formatSeconds(hours * 60 * 60);
this.log.info(`Worked more this week (${age}):`);
this.log.info(` Worked ${formatHours(item.data.current)} this week`);
this.log.info(` Worked ${formatHours(item.data.previous)} previous week`);
Expand Down Expand Up @@ -203,7 +203,7 @@ export class AEGRobotLog {
this.log.info(`Cleaned area ${date.toLocaleDateString()}:`);
this.log.info(` Cleaned ${cleanedArea.cleanedArea} m²`);
if (cleaningSession) {
const formatTime = (time: string) => new Date(time).toLocaleTimeString();
const formatTime = (time: string): string => new Date(time).toLocaleTimeString();
this.log.info(` ${formatTime(cleaningSession.startTime)} - ${formatTime(cleaningSession.eventTime)}`);
this.log.info(` Cleaned for ${formatMilliseconds(cleaningSession.cleaningDuration * TICK_MS)}`);
if (cleaningSession.pitstopCount) {
Expand Down
10 changes: 5 additions & 5 deletions src/aeg-robot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ export class AEGRobot extends EventEmitter {
// Start polling for interesting changes
const intervals = this.config.pollIntervals;
const poll: [string, number, () => Promise<void>][] = [
['Cleaned areas', intervals.cleanedAreasSeconds, () => this.pollCleanedAreas()]
['Cleaned areas', intervals.cleanedAreasSeconds, this.pollCleanedAreas.bind(this)]
];
this.heartbeats = poll.map(action =>
new Heartbeat(this.log, action[0], action[1] * MS, action[2],
Expand Down Expand Up @@ -224,7 +224,7 @@ export class AEGRobot extends EventEmitter {
}

// Update the name and timezone
updateFromDomains(appliance: DomainAppliance | ApplianceNamePatch) {
updateFromDomains(appliance: DomainAppliance | ApplianceNamePatch): void {
this.updateStatus({
rawName: appliance.applianceName,
timezone: appliance.timeZoneStandardName
Expand Down Expand Up @@ -333,7 +333,7 @@ export class AEGRobot extends EventEmitter {
if (!changed.length) return;

// Log a summary of the changes
const toText = (value: unknown) => {
const toText = (value: unknown): string => {
if (value === undefined) return '?';
if (typeof(value) === 'string' && /[- <>:,]/.test(value)) return `"${value}"`;
return String(value);
Expand All @@ -350,7 +350,7 @@ export class AEGRobot extends EventEmitter {
}

// Emit events for any new messages
emitMessages(messages: Message[] = []) {
emitMessages(messages: Message[] = []): void {
// If there are no current messages then just flush the cache
if (!messages.length) { this.emittedMessages.clear(); return; }

Expand All @@ -365,7 +365,7 @@ export class AEGRobot extends EventEmitter {
}

// Update feed items
updateFromFeed(feed: FeedItem[]) {
updateFromFeed(feed: FeedItem[]): void {
// If there are no current feed items then just flush the cache
if (!feed.length) { this.emittedFeed.clear(); return; }

Expand Down
4 changes: 2 additions & 2 deletions src/aegapi-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export class AEGAPIStatusCodeError extends AEGAPIError {
}

// Construct an error message from a response
static getMessage(response: Response, text: string) {
static getMessage(response: Response, text: string): string {
const statusCode = response.statusCode;
const statusCodeName = STATUS_CODES[statusCode];
const description = AEGAPIStatusCodeError.getBodyDescription(text)
Expand Down Expand Up @@ -126,7 +126,7 @@ export class AEGAPIValidationError extends AEGAPIError {
}

// Construct an error message from a checker validation error
static getMessage(errors: IErrorDetail[]) {
static getMessage(errors: IErrorDetail[]): string {
const description = `${errors[0].path} ${errors[0].message}`;
return `Structure validation failed (${description})`;
}
Expand Down
2 changes: 1 addition & 1 deletion src/aegapi-ua-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export class AEGAuthoriseUserAgent extends AEGUserAgent {
// Construct a Promise used to abort token refreshing
makeAbortRefreshPromise(reason: unknown): Promise<never> {
return new Promise((_, reject) => {
this.reauthorise = () => {
this.reauthorise = (): void => {
this.log.warn('Reauthorisation required...');
this.reauthorise = undefined;
this.authorised = this.makeAuthPromise();
Expand Down
2 changes: 1 addition & 1 deletion src/aegapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export class AEGAPI {
return this.ua.postJSON(checkers.WebShop, path, body);
}

applianceAPI(applianceId: string) {
applianceAPI(applianceId: string): AEGApplianceAPI {
return new AEGApplianceAPI(this.ua, applianceId);
}
}
2 changes: 1 addition & 1 deletion src/heartbeat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export class Heartbeat {
// Start a new watchdog
const abort = new Promise<never>((_, reject) => {
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
this.killWatchdog = () => { reject('kill'); };
this.killWatchdog = (): void => { reject('kill'); };
});
await sleep(this.interval * TIMEOUT_MULTIPLE + TIMEOUT_OFFSET, abort);

Expand Down
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ import { PLATFORM_NAME } from './settings.js';
import { AEGPlatform } from './platform.js';

// Register the platform with Homebridge
export default (api: API) => { api.registerPlatform(PLATFORM_NAME, AEGPlatform); };
export default (api: API): void => {
api.registerPlatform(PLATFORM_NAME, AEGPlatform);
};
4 changes: 2 additions & 2 deletions src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ export class PrefixLogger {
}

// Attempt to filter sensitive data within the log message
static filterSensitive(message: string) {
const replaceJWT = (match: string) => isJWT(match) ? '<JSON_WEB_TOKEN>' : match;
static filterSensitive(message: string): string {
const replaceJWT = (match: string): string => isJWT(match) ? '<JSON_WEB_TOKEN>' : match;
return message
// User ID and access tokens
.replace(/\b[\w-]+\.[\w-]+\.[\w-]+\b/g, replaceJWT)
Expand Down
2 changes: 1 addition & 1 deletion src/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ export class AEGPlatform implements DynamicPlatformPlugin {
// Remove any accessories that are no longer required
removeUnconfiguredAccessories(): void {
// Identify accessories that do not have an implementation
const isObsolete = (linkage: AccessoryLinkage) => !linkage.implementation;
const isObsolete = (linkage: AccessoryLinkage): boolean => !linkage.implementation;
const rmAccessories = [...this.accessories.values()]
.filter(isObsolete).map(linkage => linkage.accessory);
if (!rmAccessories.length) return;
Expand Down
2 changes: 1 addition & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export function plural(count: number, noun: string | [string, string], showCount
];
const rule = rules.find(([ending]) => new RegExp(ending, 'i').test(singular));
assertIsDefined(rule);
const matchCase = (s: string) => singular === singular.toUpperCase() ? s.toUpperCase() : s;
const matchCase = (s: string): string => singular === singular.toUpperCase() ? s.toUpperCase() : s;
noun = singular.substring(0, singular.length - rule[2]).concat(matchCase(rule[1]));
}
return showCount ? `${count} ${noun}` : noun;
Expand Down

0 comments on commit ab66fe5

Please sign in to comment.