diff --git a/.eslintrc.js b/.eslintrc.js
index fc5af07..8f63f11 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -89,6 +89,8 @@ module.exports = {
]
}
],
+ 'curly': ['warn', 'all'],
+ 'brace-style': ['warn', 'stroustrup'],
'eol-last': 'error',
'eqeqeq': [
'error',
diff --git a/gulpfile.mjs b/gulpfile.mjs
index 1c57466..d98c201 100644
--- a/gulpfile.mjs
+++ b/gulpfile.mjs
@@ -1,3 +1,5 @@
+/* eslint-disable */
+
import 'source-map-support/register.js';
import fs from 'fs';
import path from 'path';
@@ -125,7 +127,7 @@ const changelog = cb => {
.map(x => x.replace(/^\[test\]/, 'test')),
}));
const type = `{ version: string; changes: string[]; }[]`;
- const code = `/* tslint:disable */\n\nexport const CHANGELOG: ${type} = ${JSON.stringify(object, null, 2)};\n`;
+ const code = `/* eslint:disable */\n\nexport const CHANGELOG: ${type} = ${JSON.stringify(object, null, 2)};\n`;
fs.writeFile('src/ts/generated/changelog.ts', code, 'utf8', cb);
};
@@ -178,7 +180,7 @@ const shaders = cb => {
}
const dir = path.join('src', 'ts', 'graphics', 'shaders');
- const code = '/* tslint:disable */\n\n' + fs.readdirSync(dir)
+ const code = '/* eslint:disable */\n\n' + fs.readdirSync(dir)
.map(file => [_.camelCase(file.replace(/\.glsl$/, '')), path.join(dir, file)])
.map(([name, filePath]) => `export const ${name}Shader = \`${getShaderCode(filePath)}\`;`)
.join('\n\n');
@@ -200,7 +202,7 @@ const rollbar = cb => {
const assetsRev = cb => {
const json = fs.readFileSync('dist/browser/rev-manifest.json', 'utf8');
const data = _.mapValues(JSON.parse(json), value => value.replace(/^\S+-([a-f0-9]{10})\.\S+$/, '$1'));
- const code = `export const REV: { [key: string]: string; } = ${JSON.stringify(data, null, 4)};`;
+ const code = `export const REV: { [key: string]: string; } = ${JSON.stringify(data, null, 2)};`;
fs.writeFile('src/ts/generated/rev.ts', lintCode(code), 'utf8', cb);
};
diff --git a/src/ts/client/adminHtmlUtils.ts b/src/ts/client/adminHtmlUtils.ts
index 03fac5f..76e62df 100644
--- a/src/ts/client/adminHtmlUtils.ts
+++ b/src/ts/client/adminHtmlUtils.ts
@@ -26,7 +26,8 @@ export function createSupporterChanges(entries: LogEntry[]): SupporterChange[] {
if (current.level > prev.level) {
current.icon = faCaretSquareUp;
current.class = 'text-info';
- } else if (current.level < prev.level) {
+ }
+ else if (current.level < prev.level) {
current.icon = faCaretSquareDown;
current.class = 'text-info';
}
@@ -49,7 +50,6 @@ function formatChatLine(l: string): HTMLElement {
// 00:00:01 [merged][dev][Autumn Leafs][ignored] hello world
// 00:00:01 [merged][dev][main][Autumn Leafs][ignored] hello world
- /* tslint:disable:max-line-length */
const regex = /^([0-9:]+) (\[(?:merged|\d+|\d+:merged|[a-z0-9]{24})\])?\[([a-z0-9_-]+)\](?:\[([a-z0-9_-]+)\])?((?:\[.*?\])?)(?:\[(muted|ignored|ignorepub)\])?\t(.*)$/;
const m = regex.exec(l);
@@ -69,7 +69,8 @@ function formatChatLine(l: string): HTMLElement {
textNode(' '),
element('a', 'chat-translate', [], undefined, { click: translateChat }),
]);
- } else {
+ }
+ else {
return element('div', '', [textNode(highlightWords(l))]);
}
}
@@ -104,13 +105,17 @@ export function formatChat(chat: string): HTMLElement[] {
function getMessageTag(message: string) {
if (/^\/p /.test(message)) {
return 'party';
- } else if (/^\/w /.test(message)) {
+ }
+ else if (/^\/w /.test(message)) {
return 'whisper';
- } else if (/^\/s[s123] /.test(message)) {
+ }
+ else if (/^\/s[s123] /.test(message)) {
return 'supporter';
- } else if (/^\//.test(message)) {
+ }
+ else if (/^\//.test(message)) {
return 'command';
- } else {
+ }
+ else {
return 'none';
}
}
diff --git a/src/ts/client/buttonActions.ts b/src/ts/client/buttonActions.ts
index fe526e7..ab94bd4 100644
--- a/src/ts/client/buttonActions.ts
+++ b/src/ts/client/buttonActions.ts
@@ -225,8 +225,11 @@ export function deserializeActions(data: string): ButtonActionSlot[] {
try {
const json = JSON.parse(data);
return json.slice(0, ACTIONS_LIMIT).map(deserializeAction);
- } catch (e) {
- DEVELOPMENT && console.error(e);
+ }
+ catch (e) {
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
return [];
}
}
@@ -243,10 +246,13 @@ function serializeAction({ action }: ButtonActionSlot): any {
case 'entity':
return { ent: action.entity };
default:
- DEVELOPMENT && console.warn(`Missing serialization for ${JSON.stringify(action)}`);
+ if (DEVELOPMENT) {
+ console.warn(`Missing serialization for ${JSON.stringify(action)}`);
+ }
return null;
}
- } else {
+ }
+ else {
return null;
}
}
@@ -255,15 +261,21 @@ function deserializeAction(data: any): ButtonActionSlot {
if (data) {
if ('act' in data || 'action' in data) {
return { action: getActionAction(data.act || data.action) };
- } else if ('cmd' in data || 'command' in data) {
+ }
+ else if ('cmd' in data || 'command' in data) {
return { action: getCommandAction(data.cmd || data.command) };
- } else if ('exp' in data || 'expression' in data) {
+ }
+ else if ('exp' in data || 'expression' in data) {
const expression = decodeExpression(data.exp || data.expression | 0);
return { action: expressionButtonAction(expression) };
- } else if ('ent' in data || 'entity' in data) {
+ }
+ else if ('ent' in data || 'entity' in data) {
return { action: entityButtonAction(data.ent || data.entity) };
- } else {
- DEVELOPMENT && console.warn(`Missing deserialization for ${JSON.stringify(data)}`);
+ }
+ else {
+ if (DEVELOPMENT) {
+ console.warn(`Missing deserialization for ${JSON.stringify(data)}`);
+ }
}
}
@@ -281,7 +293,8 @@ export function useAction(game: PonyTownGame, action: ButtonAction | undefined)
case 'action':
if (action.sendAction) {
game.send(server => server.action(action.sendAction));
- } else {
+ }
+ else {
switch (action.action) {
case 'boop':
boopAction(game);
@@ -336,7 +349,8 @@ export function useAction(game: PonyTownGame, action: ButtonAction | undefined)
function shouldRedrawAction(action: ButtonAction | undefined, state: any, game: PonyTownGame) {
if (action !== state.action) {
return true;
- } else if (action) {
+ }
+ else if (action) {
switch (action.type) {
case 'action': {
switch (action.action) {
@@ -353,7 +367,8 @@ function shouldRedrawAction(action: ButtonAction | undefined, state: any, game:
default:
return false;
}
- } else {
+ }
+ else {
return false;
}
}
@@ -373,13 +388,15 @@ export function drawAction(canvas: HTMLCanvasElement, action: ButtonAction | und
state.action = 0;
}
- if (!spriteSheetsLoaded || !shouldRedrawAction(action, state, game))
+ if (!spriteSheetsLoaded || !shouldRedrawAction(action, state, game)) {
return;
+ }
const context = canvas.getContext('2d');
- if (!context)
+ if (!context) {
return;
+ }
state.action = action;
@@ -412,10 +429,12 @@ export function drawAction(canvas: HTMLCanvasElement, action: ButtonAction | und
if (hasFlag(extra, ExpressionExtra.Cry)) {
batch.drawSprite(sprites.emote_cry2.frames[4], WHITE, defaultPalette, headX, headY);
- } else if (hasFlag(extra, ExpressionExtra.Tears)) {
+ }
+ else if (hasFlag(extra, ExpressionExtra.Tears)) {
batch.drawSprite(sprites.emote_tears.frames[0], WHITE, defaultPalette, headX, headY);
}
- } else {
+ }
+ else {
const color = parseColor(ACTION_EXPRESSION_BG);
batch.drawRect(color, 0, 3, 15, 5);
batch.drawRect(color, 0, 8, 3, 1);
@@ -449,9 +468,12 @@ export function drawAction(canvas: HTMLCanvasElement, action: ButtonAction | und
state.draw = action.action === 'up' ? getUpDrawFunc(game) : getDownDrawFunc(game);
buffer = drawCanvasCached(`action:${action.action}:${state.draw}`, batch => {
- state.draw && getDrawFuncByName(state.draw)(batch);
+ if (state.draw) {
+ getDrawFuncByName(state.draw)(batch);
+ }
});
- } else {
+ }
+ else {
buffer = drawCanvasCached(`action:${action.action}`, batch => {
switch (action.action) {
case 'boop': {
@@ -662,9 +684,11 @@ function getUpDrawFunc(game: PonyTownGame) {
if (player) {
if (isPonyLying(player)) {
return 'sit';
- } else if (isPonySitting(player)) {
+ }
+ else if (isPonySitting(player)) {
return 'stand';
- } else if (isPonyStanding(player) && canPonyFly(player)) {
+ }
+ else if (isPonyStanding(player) && canPonyFly(player)) {
return 'fly';
}
}
@@ -678,9 +702,11 @@ function getDownDrawFunc(game: PonyTownGame) {
if (player) {
if (isPonySitting(player)) {
return 'lie';
- } else if (isPonyStanding(player)) {
+ }
+ else if (isPonyStanding(player)) {
return 'sit';
- } else if (isPonyFlying(player)) {
+ }
+ else if (isPonyFlying(player)) {
return 'stand';
}
}
diff --git a/src/ts/client/clientActions.ts b/src/ts/client/clientActions.ts
index 51874cf..c629d41 100644
--- a/src/ts/client/clientActions.ts
+++ b/src/ts/client/clientActions.ts
@@ -51,7 +51,9 @@ export class ClientActions extends ClientActionsTemplate {
this.apply(() => this.gameService.disconnected());
}
invalidVersion() {
- DEVELOPMENT && !TESTS && console.error('Invalid version');
+ if (DEVELOPMENT && !TESTS) {
+ console.error('Invalid version');
+ }
}
// @Method({ binary: [Bin.U32] })
queue(place: number) {
@@ -182,7 +184,9 @@ export class ClientActions extends ClientActionsTemplate {
this.game.nextFriendsCRC = 0;
break;
default:
- DEVELOPMENT && !TESTS && console.error(`actionParam: Invalid action: ${action}`);
+ if (DEVELOPMENT && !TESTS) {
+ console.error(`actionParam: Invalid action: ${action}`);
+ }
}
}
// @Method({ binary: [Bin.U8] }>)
diff --git a/src/ts/client/clientAdminActions.ts b/src/ts/client/clientAdminActions.ts
index 56cde28..5e37ef7 100644
--- a/src/ts/client/clientAdminActions.ts
+++ b/src/ts/client/clientAdminActions.ts
@@ -20,7 +20,8 @@ export class ClientAdminActions extends ClientAdminActionsTemplate {
if (model) {
model.update(id, update);
- } else {
+ }
+ else {
console.error(`Invalid model type "${type}"`);
}
}
diff --git a/src/ts/client/clientUtils.ts b/src/ts/client/clientUtils.ts
index 29dbe2e..4ffad1a 100644
--- a/src/ts/client/clientUtils.ts
+++ b/src/ts/client/clientUtils.ts
@@ -39,7 +39,8 @@ function isMultipleMatch(message: string, last: string): boolean {
}
return message === current.substr(0, SAY_MAX_LENGTH);
- } else {
+ }
+ else {
return false;
}
}
@@ -53,9 +54,11 @@ function isTrailingMatch(message: string, last: string) {
if (message.length > last.length && last.length > minMessageLength) {
return checkTrailing(message, last);
- } else if (message.length < last.length && message.length > minMessageLength) {
+ }
+ else if (message.length < last.length && message.length > minMessageLength) {
return checkTrailing(last, message);
- } else {
+ }
+ else {
return false;
}
}
@@ -63,7 +66,8 @@ function isTrailingMatch(message: string, last: string) {
export function isSpamMessage(message: string, lastMessages: string[]): boolean {
if (!/^\//.test(message) && lastMessages.length) {
return lastMessages.some(last => message === last || isMultipleMatch(message, last) || isTrailingMatch(message, last));
- } else {
+ }
+ else {
return false;
}
}
@@ -154,7 +158,8 @@ export function readFileAsText(file: File) {
export function isFileSaverSupported() {
try {
return !!new Blob;
- } catch {
+ }
+ catch {
return false;
}
}
@@ -167,13 +172,15 @@ export function setIsIncognitoMode(value: boolean) {
/* istanbul ignore next */
function checkIncognitoMode(wnd: any) {
- if (!wnd || !wnd.chrome)
+ if (!wnd || !wnd.chrome) {
return;
+ }
const fs = wnd.RequestFileSystem || wnd.webkitRequestFileSystem;
- if (!fs)
+ if (!fs){
return;
+ }
fs(wnd.TEMPORARY, 100, () => { }, () => isInIncognitoMode = true);
}
@@ -202,7 +209,8 @@ export function isStandalone() {
export function supportsLetAndConst() {
try {
return (new Function('let x = true; return x;'))();
- } catch {
+ }
+ catch {
return false;
}
}
@@ -230,7 +238,8 @@ export function registerServiceWorker(url: string, onUpdate: () => void) {
}
});
}
- } catch (e) {
+ }
+ catch (e) {
console.error(e);
}
}
@@ -244,7 +253,8 @@ export function unregisterServiceWorker() {
registration.unregister();
}
});
- } else {
+ }
+ else {
return Promise.resolve();
}
}
@@ -271,7 +281,8 @@ export function updateRangeIndicator(range: number | undefined, { player, scale,
e.style.top = `${-h / 2}px`;
e.style.transform = `translate3d(${x}px, ${y}px, 0)`;
e.style.display = 'block';
- } else {
+ }
+ else {
e.style.display = 'none';
}
}
@@ -283,7 +294,8 @@ export function checkIframeKey(iframeId: string, expectedKey: string) {
const doc = iframe && iframe.contentWindow && iframe.contentWindow.document;
const key = doc && doc.body && doc.body.getAttribute('data-key');
return key === expectedKey;
- } catch (e) {
+ }
+ catch (e) {
if (DEVELOPMENT) {
console.error(e);
}
@@ -333,9 +345,11 @@ export function isSupporterOrPastSupporter(account: AccountData | undefined) {
export function supporterTitle(account: AccountData | undefined) {
if (account && account.supporter) {
return `Supporter Tier ${account.supporter}`;
- } else if (account && hasFlag(account.flags, AccountDataFlags.PastSupporter)) {
+ }
+ else if (account && hasFlag(account.flags, AccountDataFlags.PastSupporter)) {
return 'Past supporter';
- } else {
+ }
+ else {
return '';
}
}
@@ -343,9 +357,11 @@ export function supporterTitle(account: AccountData | undefined) {
export function supporterClass(account: AccountData | undefined) {
if (account && account.supporter) {
return `supporter-${account.supporter}`;
- } else if (account && hasFlag(account.flags, AccountDataFlags.PastSupporter)) {
+ }
+ else if (account && hasFlag(account.flags, AccountDataFlags.PastSupporter)) {
return 'supporter-past';
- } else {
+ }
+ else {
return 'd-none';
}
}
@@ -353,9 +369,11 @@ export function supporterClass(account: AccountData | undefined) {
export function supporterRewards(account: AccountData | undefined) {
if (account && account.supporter) {
return SUPPORTER_REWARDS[account.supporter];
- } else if (account && hasFlag(account.flags, AccountDataFlags.PastSupporter)) {
+ }
+ else if (account && hasFlag(account.flags, AccountDataFlags.PastSupporter)) {
return PAST_SUPPORTER_REWARDS;
- } else {
+ }
+ else {
return SUPPORTER_REWARDS[0];
}
}
diff --git a/src/ts/client/data.ts b/src/ts/client/data.ts
index 36b8e0c..c7f4ae3 100644
--- a/src/ts/client/data.ts
+++ b/src/ts/client/data.ts
@@ -46,7 +46,8 @@ export function socketOptions(): ClientOptions {
const buffer = toByteArray(options);
const reader = createBinaryReader(buffer);
return readObject(reader);
- } else {
+ }
+ else {
throw new Error('Missing socket options');
}
}
diff --git a/src/ts/client/draw.ts b/src/ts/client/draw.ts
index ebb8748..84624d2 100644
--- a/src/ts/client/draw.ts
+++ b/src/ts/client/draw.ts
@@ -31,11 +31,13 @@ function drawEntities(batch: PaletteSpriteBatch, entities: Entity[], camera: Cam
batch.depth = -batch.depth;
drawPonyEntity(batch, entity as Pony, options);
entitiesDrawn++;
- } else if (entity.draw !== undefined) {
+ }
+ else if (entity.draw !== undefined) {
entity.draw(batch, options);
entitiesDrawn++;
}
- } else {
+ }
+ else {
if (entity.type === PONY_TYPE) {
const pony = entity as Pony;
@@ -62,7 +64,8 @@ export function drawEntityLights(batch: SpriteBatch, entities: Entity[], camera:
if (isBoundsVisible(camera, entity.lightBounds, entity.x, entity.y) && (!isHidden(entity) || drawHidden)) {
if (entity.type === PONY_TYPE) {
drawPonyEntityLight(batch, entity as Pony, options);
- } else {
+ }
+ else {
entity.drawLight!(batch, options);
}
++drawn;
@@ -85,7 +88,8 @@ export function drawEntityLightSprites(batch: SpriteBatch, entities: Entity[], c
batch.depth = entity.depth;
if (entity.type === PONY_TYPE) {
drawPonyEntityLightSprite(batch, entity as Pony, options);
- } else {
+ }
+ else {
entity.drawLightSprite!(batch, options);
}
++drawn;
@@ -100,7 +104,8 @@ export function hasDrawLight(entity: Entity) {
const pony = entity as Pony;
return (pony.ponyState.holding !== undefined && pony.ponyState.holding.drawLight !== undefined) ||
((pony.state & EntityState.Magic) !== 0);
- } else {
+ }
+ else {
return entity.drawLight !== undefined;
}
}
@@ -109,7 +114,8 @@ export function hasLightSprite(entity: Entity) {
if (entity.type === PONY_TYPE) {
const pony = entity as Pony;
return (pony.ponyState.holding !== undefined && pony.ponyState.holding.drawLightSprite !== undefined);
- } else {
+ }
+ else {
return entity.drawLightSprite !== undefined;
}
}
@@ -118,25 +124,39 @@ export function drawMap(
batch: PaletteSpriteBatch, map: WorldMap, camera: Camera, player: Pony,
options: DrawOptions, tileSets: TileSets, selectedEntities: Entity[],
) {
- TIMING && timeStart('forEachRegion');
+ if (TIMING) {
+ timeStart('forEachRegion');
+ }
batch.depth = 1.0;
if (BETA && options.engine === Engine.Whiteness) {
batch.drawRect(WHITE, 0, 0, toScreenX(map.width), toScreenY(map.height));
- } else if (BETA && options.engine === Engine.LayeredTiles) {
+ }
+ else if (BETA && options.engine === Engine.LayeredTiles) {
forEachRegion(map, region => drawTilesNew(batch, region, camera, map, tileSets, options));
- } else {
+ }
+ else {
forEachRegion(map, region => drawTiles(batch, region, camera, map, tileSets, options));
}
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
- TIMING && timeStart('sortEntities');
+ if (TIMING) {
+ timeStart('sortEntities');
+ }
sortEntities(map.entitiesDrawable);
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
- TIMING && timeStart('drawEntities');
+ if (TIMING) {
+ timeStart('drawEntities');
+ }
const entitiesDrawn = drawEntities(batch, map.entitiesDrawable, camera, options);
batch.depth = 1.0;
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
if (BETA || TOOLS) {
forEachRegion(map, region => drawTilesDebugInfo(batch, region, camera, options));
@@ -179,10 +199,18 @@ function drawDebugHelpers(batch: PaletteSpriteBatch, entities: Entity[], options
for (const e of entities) {
batch.globalAlpha = 0.3;
- show.bounds && drawBounds(batch, e, e.bounds, ORANGE);
- show.cover && drawBounds(batch, e, e.coverBounds, BLUE);
- show.interact && drawBounds(batch, e, e.interactBounds, PURPLE);
- show.trigger && drawWorldBounds(batch, e, e.triggerBounds, CYAN);
+ if (show.bounds) {
+ drawBounds(batch, e, e.bounds, ORANGE);
+ }
+ if (show.cover) {
+ drawBounds(batch, e, e.coverBounds, BLUE);
+ }
+ if (show.interact) {
+ drawBounds(batch, e, e.interactBounds, PURPLE);
+ }
+ if (show.trigger) {
+ drawWorldBounds(batch, e, e.triggerBounds, CYAN);
+ }
if (show.collider) {
batch.globalAlpha = 0.5;
@@ -224,16 +252,19 @@ function drawDebugInWater(batch: PaletteSpriteBatch, map: WorldMap, camera: Came
const cameraTop = camera.actualY;
const cameraBottom = camera.actualY + camera.h;
- if (sx > cameraRight || sy > cameraBottom || (sx + w) < cameraLeft || (sy + h) < cameraTop)
+ if (sx > cameraRight || sy > cameraBottom || (sx + w) < cameraLeft || (sy + h) < cameraTop) {
return;
+ }
for (let y = 0; y < h; y++) {
- if ((sy + y + 1) < cameraTop || (sy + y) > cameraBottom)
+ if ((sy + y + 1) < cameraTop || (sy + y) > cameraBottom) {
continue;
+ }
for (let x = 0; x < w; x++) {
- if ((sx + x + 1) < cameraLeft || (sx + x) > cameraRight)
+ if ((sx + x + 1) < cameraLeft || (sx + x) > cameraRight) {
continue;
+ }
const tx = x;
@@ -263,16 +294,19 @@ function drawDebugCollider(batch: PaletteSpriteBatch, map: WorldMap, camera: Cam
const cameraTop = camera.actualY;
const cameraBottom = camera.actualY + camera.h;
- if (sx > cameraRight || sy > cameraBottom || (sx + w) < cameraLeft || (sy + h) < cameraTop)
+ if (sx > cameraRight || sy > cameraBottom || (sx + w) < cameraLeft || (sy + h) < cameraTop) {
return;
+ }
for (let y = 0; y < h; y++) {
- if ((sy + y + 1) < cameraTop || (sy + y) > cameraBottom)
+ if ((sy + y + 1) < cameraTop || (sy + y) > cameraBottom) {
continue;
+ }
for (let x = 0; x < w; x++) {
- if ((sx + x + 1) < cameraLeft || (sx + x) > cameraRight)
+ if ((sx + x + 1) < cameraLeft || (sx + x) > cameraRight) {
continue;
+ }
const tx = x;
diff --git a/src/ts/client/game.ts b/src/ts/client/game.ts
index 7353193..34aae3a 100644
--- a/src/ts/client/game.ts
+++ b/src/ts/client/game.ts
@@ -1,3 +1,4 @@
+/* eslint-disable camelcase */
import { Injectable, NgZone } from '@angular/core';
import { Subject, BehaviorSubject } from 'rxjs';
import { debounce } from 'lodash';
@@ -370,7 +371,8 @@ export class PonyTownGame implements Game {
send(action: (server: IServerActions) => T) {
if (this.socket && this.socket.isConnected) {
return action(this.socket.server);
- } else {
+ }
+ else {
return undefined;
}
}
@@ -385,11 +387,13 @@ export class PonyTownGame implements Game {
this.setScale(Math.max(1, this.scale - 1));
}
select(pony: Pony | undefined) {
- if (this.selected === pony)
+ if (this.selected === pony) {
return;
+ }
- if (pony && isHidden(pony) && !this.mod)
+ if (pony && isHidden(pony) && !this.mod) {
return;
+ }
this.zone.run(() => {
if (this.selected) {
@@ -400,7 +404,8 @@ export class PonyTownGame implements Game {
if (pony && !pony.info && !pony.palettePonyInfo) {
this.send(server => server.select(pony.id, SelectFlags.FetchEx | SelectFlags.FetchInfo));
- } else {
+ }
+ else {
this.sendSelected();
}
@@ -427,12 +432,16 @@ export class PonyTownGame implements Game {
if (!this.initialized) {
this.canvas.addEventListener('webglcontextlost', e => {
e.preventDefault();
- DEVELOPMENT && console.warn('Context lost');
+ if (DEVELOPMENT) {
+ console.warn('Context lost');
+ }
this.errorReporter.captureEvent({ name: 'Context lost' });
});
this.canvas.addEventListener('webglcontextrestored', () => {
- DEVELOPMENT && console.warn('Context restored');
+ if (DEVELOPMENT) {
+ console.warn('Context restored');
+ }
this.errorReporter.captureEvent({ name: 'Context restored' });
if (this.webgl) {
@@ -573,7 +582,8 @@ export class PonyTownGame implements Game {
dir = -1;
}
}, 1000 / 24);
- } else {
+ }
+ else {
let faceDir = 0;
const state = this.player!.ponyState;
@@ -643,7 +653,8 @@ export class PonyTownGame implements Game {
if (loseContext) {
loseContext.restoreContext();
loseContext = null;
- } else {
+ }
+ else {
loseContext = this.webgl!.gl.getExtension('WEBGL_lose_context')!;
loseContext.loseContext();
}
@@ -661,7 +672,8 @@ export class PonyTownGame implements Game {
const entity = entities[0];
const typeName = getEntityTypeName(entity.type);
this.announce(`${typeName}${entities.length > 1 ? ` (1 of ${entities.length})` : ''}`);
- } else {
+ }
+ else {
this.announce('nothing');
}
}
@@ -705,7 +717,9 @@ export class PonyTownGame implements Game {
window.addEventListener('resize', () => {
this.resized = true;
- DEVELOPMENT && log(`resized ${window.innerHeight} (${window.scrollY})`);
+ if (DEVELOPMENT) {
+ log(`resized ${window.innerHeight} (${window.scrollY})`);
+ }
});
this.canvas.addEventListener('touchstart', () => this.audio.touch());
@@ -721,7 +735,8 @@ export class PonyTownGame implements Game {
if (this.socket) {
if (this.socket.isConnected) {
this.socket.server.leave();
- } else {
+ }
+ else {
this.socket.disconnect();
}
}
@@ -767,10 +782,13 @@ export class PonyTownGame implements Game {
this.supporterPony = createPony(0, 0, SUPPORTER_PONY, palettes.defaultPalette, this.paletteManager);
this.discordPony = createPony(0, 0, DISCORD_PONY, palettes.defaultPalette, this.paletteManager);
initializeToys(this.paletteManager);
- } catch (e) {
+ }
+ catch (e) {
this.errorReporter.captureEvent({ name: 'failed game.initWebGL', error: isErrorAlike(e) ? e.message : '', stack: isErrorAlike(e) ? e.stack : '' });
this.releaseWebGL();
- DEVELOPMENT && console.error(e);
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
throw new Error(`Failed to initialize graphics device (${isErrorAlike(e) ? e.message : 'Unknown error'})`);
}
}
@@ -781,8 +799,11 @@ export class PonyTownGame implements Game {
try {
this.paletteManager.dispose(this.webgl.gl);
disposeWebGL(this.webgl);
- } catch (e) {
- DEVELOPMENT && console.error(e);
+ }
+ catch (e) {
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
}
this.webgl = undefined;
@@ -827,7 +848,8 @@ export class PonyTownGame implements Game {
startup(socket: ClientSocketService, mod: boolean) {
if (this.settings.account.actions) {
this.actions = deserializeActions(this.settings.account.actions);
- } else {
+ }
+ else {
this.actions = createDefaultButtonActions();
}
@@ -860,21 +882,25 @@ export class PonyTownGame implements Game {
return this.scale * (integerPixelRatio() / pixelRatio());
}
update(delta: number, now: number, last: number) {
- TIMING && timeStart('update');
+ if (TIMING) {
+ timeStart('update');
+ }
delta *= this.deltaMultiplier;
const shiftSpeed = delta * 10;
if (this.cameraShiftOn && this.camera.shiftRatio !== 1) {
this.camera.shiftRatio = Math.min(1, this.camera.shiftRatio + shiftSpeed);
- } else if (!this.cameraShiftOn && this.camera.shiftRatio !== 0) {
+ }
+ else if (!this.cameraShiftOn && this.camera.shiftRatio !== 0) {
this.camera.shiftRatio = Math.max(0, this.camera.shiftRatio - shiftSpeed);
}
updateMap(this.map, delta);
- if (!this.socket || !this.socket.isConnected || !this.element)
+ if (!this.socket || !this.socket.isConnected || !this.element) {
return;
+ }
this.updateGameTime(delta);
@@ -986,7 +1012,8 @@ export class PonyTownGame implements Game {
if (hasFlag(this.map.flags, MapFlags.EditableEntities)) {
if (player.hold === removeEntitiesTool.type) {
this.highlightEntity = pickEntities(this.map, hover, true, false, true)[0];
- } else if (player.hold === placeEntitiesTool.type) {
+ }
+ else if (player.hold === placeEntitiesTool.type) {
if (!isOutsideMap(hover.x, hover.y, this.map)) {
const { type } = placeableEntities[this.placeEntity];
let { x, y } = hover;
@@ -1011,38 +1038,48 @@ export class PonyTownGame implements Game {
if (BETA && this.editor.selectingEntities) {
editorSelectEntities(this, hover, shift);
- } else if (pickedEntity && (!holdingTool || !editableMap || hasFlag(pickedEntity.flags, EntityFlags.IgnoreTool))) {
+ }
+ else if (pickedEntity && (!holdingTool || !editableMap || hasFlag(pickedEntity.flags, EntityFlags.IgnoreTool))) {
if (pickedEntity.type === PONY_TYPE) {
this.select(pickedEntity as Pony);
- } else if (entityInRange(pickedEntity, player)) {
+ }
+ else if (entityInRange(pickedEntity, player)) {
server.interact(pickedEntity.id);
}
- } else if (BETA && this.editor.tile !== -1) {
+ }
+ else if (BETA && this.editor.tile !== -1) {
if (this.editor.brushSize > 1) {
const x = Math.floor((hover.x - (this.editor.brushSize / 2)));
const y = Math.floor((hover.y - (this.editor.brushSize / 2)));
server.editorAction({ type: 'tile', x, y, tile: this.editor.tile, size: this.editor.brushSize });
- } else {
+ }
+ else {
const x = hover.x | 0;
const y = hover.y | 0;
const type = this.editor.tile === getTile(this.map, hover.x, hover.y) ? TileType.Dirt : this.editor.tile;
server.changeTile(x, y, type);
}
- } else if (player.hold === changeTileTool.type && hasFlag(this.map.flags, MapFlags.EditableTiles)) {
+ }
+ else if (player.hold === changeTileTool.type && hasFlag(this.map.flags, MapFlags.EditableTiles)) {
const x = hover.x | 0;
const y = hover.y | 0;
server.changeTile(x, y, houseTiles[this.placeTile].type);
- } else if (player.hold === toggleWallsTool.type && hasFlag(this.map.flags, MapFlags.EditableWalls)) {
+ }
+ else if (player.hold === toggleWallsTool.type && hasFlag(this.map.flags, MapFlags.EditableWalls)) {
toggleWall(this, hover);
- } else if (holdingRemoveTool && this.highlightEntity && editableMap) {
+ }
+ else if (holdingRemoveTool && this.highlightEntity && editableMap) {
const id = this.highlightEntity.id;
this.send(server => server.actionParam(Action.RemoveEntity, id));
- } else if (holdingPlaceTool && this.highlightEntity && editableMap) {
+ }
+ else if (holdingPlaceTool && this.highlightEntity && editableMap) {
const { x, y, type } = this.highlightEntity;
this.send(server => server.actionParam(Action.PlaceEntity, { x, y, type }));
- } else if (this.selected) {
+ }
+ else if (this.selected) {
this.select(undefined);
- } else if (hasFlag(this.map.flags, MapFlags.EdibleGrass)) {
+ }
+ else if (hasFlag(this.map.flags, MapFlags.EdibleGrass)) {
const tile = getTile(this.map, hover.x, hover.y);
if (isValidTile(tile) && distanceXY(player.x, player.y, hover.x, hover.y) < TILE_CHANGE_RANGE) {
@@ -1051,7 +1088,8 @@ export class PonyTownGame implements Game {
let type = tile === TileType.Grass ? TileType.Dirt : TileType.Grass;
server.changeTile(x, y, type);
}
- } else if (DEVELOPMENT && this.engine === Engine.LayeredTiles && this.editor.elevation) {
+ }
+ else if (DEVELOPMENT && this.engine === Engine.LayeredTiles && this.editor.elevation) {
const value = getElevation(this.map, hover.x, hover.y);
setElevation(this.map, hover.x, hover.y, clamp(this.editor.elevation === 'up' ? value + 1 : value - 1, 0, 10));
}
@@ -1060,7 +1098,8 @@ export class PonyTownGame implements Game {
if (BETA && input.wasPressed(Key.MOUSE_BUTTON2)) {
if (this.editor.selectingEntities) {
editorMoveEntities(this, hover);
- } else if (this.mod) {
+ }
+ else if (this.mod) {
toggleWall(this, hover);
}
}
@@ -1078,10 +1117,12 @@ export class PonyTownGame implements Game {
const action = input.wheelY < 0 ? Action.SwitchTool : Action.SwitchToolRev;
this.send(server => server.action(action));
}
- } else {
+ }
+ else {
if (this.player.hold === placeEntitiesTool.type) {
this.changePlaceEntity(input.wheelY < 0);
- } else if (this.player.hold === changeTileTool.type) {
+ }
+ else if (this.player.hold === changeTileTool.type) {
this.changePlaceTile(input.wheelY < 0);
}
}
@@ -1144,7 +1185,9 @@ export class PonyTownGame implements Game {
}
this.updateSocketStats(delta);
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
if (DEVELOPMENT && LOG_POSITION) {
if (this.player) {
@@ -1159,7 +1202,8 @@ export class PonyTownGame implements Game {
if (Math.abs(this.targetBaseTime - baseTime) < timeDelta) {
this.baseTime = this.targetBaseTime;
- } else {
+ }
+ else {
this.baseTime = baseTime;
}
}
@@ -1188,7 +1232,8 @@ export class PonyTownGame implements Game {
if (initial) {
this.baseTime = this.targetBaseTime = baseTime;
- } else {
+ }
+ else {
this.targetBaseTime = baseTime;
}
@@ -1218,11 +1263,14 @@ export class PonyTownGame implements Game {
redrawActionButtons(this.actionsChanged);
this.actionsChanged = false;
- if (!this.webgl)
+ if (!this.webgl) {
return;
+ }
if (this.webgl.gl.isContextLost()) {
- DEVELOPMENT && console.warn('Context is lost');
+ if (DEVELOPMENT) {
+ console.warn('Context is lost');
+ }
return;
}
@@ -1247,16 +1295,21 @@ export class PonyTownGame implements Game {
const { gl, frameBuffer, frameBuffer2, spriteBatch, paletteBatch, palettes, failedFBO,
mergeShader, paletteShader, spriteShader, spriteShaderWithColor, lightShader } = this.webgl;
- TIMING && timeStart('draw');
+ if (TIMING) {
+ timeStart('draw');
+ }
- TIMING && timeStart('draw init');
+ if (TIMING) {
+ timeStart('draw init');
+ }
let lightColor = WHITE;
let shadowColor = 0;
if (this.map.type === MapType.Cave) {
lightColor = CAVE_LIGHT;
shadowColor = CAVE_SHADOW;
- } else {
+ }
+ else {
lightColor = getLightColor(this.lightData, this.time);
shadowColor = getShadowColor(this.lightData, this.time);
}
@@ -1291,17 +1344,27 @@ export class PonyTownGame implements Game {
}
ortho(this.fboMatrix, 0, gl.drawingBufferWidth / actualScale, gl.drawingBufferHeight / actualScale, 0, 0, 1000, false);
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
- TIMING && timeStart('ensureAllVisiblePon...');
+ if (TIMING) {
+ timeStart('ensureAllVisiblePon...');
+ }
ensureAllVisiblePoniesAreDecoded(this.map, camera, this.paletteManager);
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
- TIMING && timeStart('commit+invalidatePalettes');
+ if (TIMING) {
+ timeStart('commit+invalidatePalettes');
+ }
if (this.paletteManager.commit(gl)) {
invalidatePalettes(this.map.entitiesDrawable);
}
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
if (this.settings.browser.brightNight) {
lerpColor(light, white, 0.3);
@@ -1310,9 +1373,13 @@ export class PonyTownGame implements Game {
// you'd draw directly onto the screen only when there's no framebuffer
// or the graphics is low and framebuffer size matches screen size
- TIMING && timeStart('initializeFrameBuffers');
+ if (TIMING) {
+ timeStart('initializeFrameBuffers');
+ }
this.initializeFrameBuffers(this.webgl, width, height, this.settings.browser.graphicsQuality === GraphicsQuality.High);
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
const useDepthBuffer =
!failedFBO && (this.settings.browser.graphicsQuality === GraphicsQuality.High) && !!frameBuffer!.depthStencilRenderbuffer;
@@ -1342,12 +1409,16 @@ export class PonyTownGame implements Game {
gl.depthFunc(gl.ALWAYS);
if (drawSceneDirectlyOntoScreen) {
- TIMING && timeStart('color -> screen');
+ if (TIMING) {
+ timeStart('color -> screen');
+ }
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
this.drawMap(this.webgl, this.map, this.viewMatrix, mapDrawingColor, drawOptions);
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
}
else {
// if (!isWebGL2(gl)) {
@@ -1361,17 +1432,23 @@ export class PonyTownGame implements Game {
clearMask |= gl.DEPTH_BUFFER_BIT;
}
- TIMING && timeStart('color -> framebuffer');
+ if (TIMING) {
+ timeStart('color -> framebuffer');
+ }
bindFrameBuffer(gl, frameBuffer!);
gl.viewport(0, 0, frameBuffer!.width, frameBuffer!.height); // clearing the whole surface is preferable for most GPUs
gl.clear(clearMask);
gl.viewport(0, 0, width, height);
this.drawMap(this.webgl, this.map, this.viewMatrix, mapDrawingColor, drawOptions);
gl.depthMask(false);
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
if (useLighting) {
- TIMING && timeStart('light -> fbo');
+ if (TIMING) {
+ timeStart('light -> fbo');
+ }
bindFrameBuffer(gl, frameBuffer2!);
gl.viewport(0, 0, frameBuffer2!.width, frameBuffer2!.height); // clearing the whole surface is preferable for most GPUs
gl.clearColor(light[0], light[1], light[2], light[3]);
@@ -1402,9 +1479,13 @@ export class PonyTownGame implements Game {
if (isWebGL2(gl)) {
(gl as WebGL2RenderingContext).invalidateFramebuffer(gl.FRAMEBUFFER, [gl.DEPTH_ATTACHMENT]);
}
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
- TIMING && timeStart('color + lights -> screen');
+ if (TIMING) {
+ timeStart('color + lights -> screen');
+ }
unbindFrameBuffer(gl);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.disable(gl.BLEND);
@@ -1417,10 +1498,14 @@ export class PonyTownGame implements Game {
spriteBatch.begin();
spriteBatch.drawImage(WHITE, 0, 0, width, height, 0, 0, width, height);
spriteBatch.end();
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
}
else {
- TIMING && timeStart('color framebuffer -> screen');
+ if (TIMING) {
+ timeStart('color framebuffer -> screen');
+ }
unbindFrameBuffer(gl);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.disable(gl.BLEND);
@@ -1433,7 +1518,9 @@ export class PonyTownGame implements Game {
spriteBatch.begin();
spriteBatch.drawImage(WHITE, 0, 0, width, height, 0, 0, width, height);
spriteBatch.end();
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
}
}
@@ -1442,7 +1529,9 @@ export class PonyTownGame implements Game {
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
- TIMING && timeStart('drawNames+drawChat');
+ if (TIMING) {
+ timeStart('drawNames+drawChat');
+ }
gl.useProgram(paletteShader.program);
gl.uniformMatrix4fv(paletteShader.uniforms.transform, false, this.fboMatrix);
gl.uniform4fv(paletteShader.uniforms.lighting, white);
@@ -1461,13 +1550,16 @@ export class PonyTownGame implements Game {
if (!this.socket || !this.socket.isConnected) {
this.drawMessage(this.webgl, 'Connecting...');
- } else if (!this.loaded) {
+ }
+ else if (!this.loaded) {
if (this.placeInQueue) {
this.drawMessage(this.webgl, `Waiting in queue (${this.placeInQueue})`);
- } else {
+ }
+ else {
this.drawMessage(this.webgl, 'Loading...');
}
- } else if ((performance.now() - this.socket.lastPacket) > CONNECTION_ISSUE_TIMEOUT) {
+ }
+ else if ((performance.now() - this.socket.lastPacket) > CONNECTION_ISSUE_TIMEOUT) {
// this.drawMessage('Connection issues...');
}
@@ -1478,7 +1570,8 @@ export class PonyTownGame implements Game {
const y = this.input.pointerY / scale;
const height = getMapHeightAt(this.map, this.hover.x, this.hover.y, this.time);
drawText(paletteBatch, `${height.toFixed(2)}`, fontSmallPal, BLACK, x, y);
- } catch (e) {
+ }
+ catch (e) {
console.warn(e);
}
}
@@ -1497,13 +1590,16 @@ export class PonyTownGame implements Game {
if (dx > dy) {
if ((dx + dy) < 1) {
paletteBatch.drawSprite(wall_h_placeholder.color, color, palette, screenX, screenY - 15);
- } else {
+ }
+ else {
paletteBatch.drawSprite(wall_v_placeholder.color, color, palette, screenX + tileWidth - 4, screenY - 12);
}
- } else {
+ }
+ else {
if ((dx + dy) < 1) {
paletteBatch.drawSprite(wall_v_placeholder.color, color, palette, screenX - 4, screenY - 12);
- } else {
+ }
+ else {
paletteBatch.drawSprite(wall_h_placeholder.color, color, palette, screenX, screenY + tileHeight - 15);
}
}
@@ -1511,7 +1607,9 @@ export class PonyTownGame implements Game {
}
paletteBatch.end();
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
gl.useProgram(spriteShaderWithColor.program);
gl.uniformMatrix4fv(spriteShaderWithColor.uniforms.transform, false, this.fboMatrix);
@@ -1562,7 +1660,9 @@ export class PonyTownGame implements Game {
if (showFPS || showHelp || showPalette || showAdditionalStats) {
// 1 to 1 pixel scale drawing
- TIMING && timeStart('showFps');
+ if (TIMING) {
+ timeStart('showFps');
+ }
const scale = 2;
ortho(this.fboMatrix, 0, gl.drawingBufferWidth / ratio, gl.drawingBufferHeight / ratio, 0, 0, 1000, false);
gl.uniformMatrix4fv(spriteShaderWithColor.uniforms.transform, false, this.fboMatrix);
@@ -1626,25 +1726,37 @@ export class PonyTownGame implements Game {
spriteBatch.end();
}
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
}
bindTexture(gl, 0, undefined);
bindTexture(gl, 1, undefined);
gl.useProgram(null);
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
this.updateStatsText();
- TIMING && timeStart('messageQueue');
+ if (TIMING) {
+ timeStart('messageQueue');
+ }
while (this.messageQueue.length) {
this.onMessage.next(this.messageQueue.shift()!);
}
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
- TIMING && timeStart('onFrame');
+ if (TIMING) {
+ timeStart('onFrame');
+ }
this.onFrame.next();
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
}
private drawMessage({ paletteBatch, palettes }: WebGL, message: string) {
drawFullScreenMessage(paletteBatch, this.camera, message, palettes.mainFont.white);
@@ -1654,7 +1766,9 @@ export class PonyTownGame implements Game {
const mapPaletteShader = options.useDepthBuffer ? paletteShaderWithDepth : paletteShader;
- TIMING && timeStart('drawMap');
+ if (TIMING) {
+ timeStart('drawMap');
+ }
if (this.tileSets && this.player) {
gl.useProgram(mapPaletteShader.program);
gl.uniformMatrix4fv(mapPaletteShader.uniforms.transform, false, viewMatrix);
@@ -1675,14 +1789,18 @@ export class PonyTownGame implements Game {
paletteBatch.end();
}
}
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
}
private updateCameraShift() {
if (isMobile) {
const isKeyboardOpen = !!document.activeElement && /input/i.test(document.activeElement.tagName);
if (this.lastIsKeyboardOpen !== isKeyboardOpen) {
- DEVELOPMENT && log(`keyboard open ${isKeyboardOpen}`);
+ if (DEVELOPMENT) {
+ log(`keyboard open ${isKeyboardOpen}`);
+ }
this.lastIsKeyboardOpen = isKeyboardOpen;
}
@@ -1695,10 +1813,13 @@ export class PonyTownGame implements Game {
log(`shift camera ${this.cameraShiftTarget} (${this.windowHeight} - ${window.innerHeight}, ${window.scrollY})`);
}
}
- } else {
+ }
+ else {
if (this.cameraShiftOn && window.scrollY < 100) {
this.cameraShiftOn = false;
- DEVELOPMENT && log(`unshift camera`);
+ if (DEVELOPMENT) {
+ log(`unshift camera`);
+ }
}
}
}
@@ -1728,7 +1849,9 @@ export class PonyTownGame implements Game {
canvas.style.height = `${h / ratio}px`;
this.lastCanvasRatio = ratio;
this.resized = false;
- DEVELOPMENT && log(`scrollY: ${window.scrollY}`);
+ if (DEVELOPMENT) {
+ log(`scrollY: ${window.scrollY}`);
+ }
}
}
private initializeFrameBuffers(
@@ -1748,8 +1871,11 @@ export class PonyTownGame implements Game {
if (isSizeTooBig) {
this.setScale(this.scale + 1); // should not happen, useDepthBuffer is also ignored if it does
- DEVELOPMENT && console.warn('Cannot resize framebuffer');
- } else {
+ if (DEVELOPMENT) {
+ console.warn('Cannot resize framebuffer');
+ }
+ }
+ else {
disposeFrameBuffer(gl, frameBuffer);
disposeFrameBuffer(gl, frameBuffer2);
createFrameBuffer(gl, frameBuffer, width, height, useDepthBuffer, null);
@@ -1763,7 +1889,8 @@ export class PonyTownGame implements Game {
changePlaceEntity(reverse: boolean) {
if (reverse) {
this.placeEntity = this.placeEntity === 0 ? (placeableEntities.length - 1) : (this.placeEntity - 1);
- } else {
+ }
+ else {
this.placeEntity = (this.placeEntity + 1) % placeableEntities.length;
}
@@ -1774,7 +1901,8 @@ export class PonyTownGame implements Game {
changePlaceTile(reverse: boolean) {
if (reverse) {
this.placeTile = this.placeTile === 0 ? (houseTiles.length - 1) : (this.placeTile - 1);
- } else {
+ }
+ else {
this.placeTile = (this.placeTile + 1) % houseTiles.length;
}
@@ -1789,7 +1917,9 @@ export class PonyTownGame implements Game {
const { gl, spriteBatch, paletteBatch } = this.webgl!;
if ((performance.now() - this.lastStats) > SECOND) {
- TIMING && timingCollate();
+ if (TIMING) {
+ timingCollate();
+ }
if (TIMING) {
const timings = timingCollate();
@@ -1834,7 +1964,9 @@ export class PonyTownGame implements Game {
this.onClock.next(formatHourMinutes(this.time));
}
- TIMING && timeReset();
+ if (TIMING) {
+ timeReset();
+ }
spriteBatch!.drawnTrisStats = 0;
spriteBatch!.flushes = 0;
diff --git a/src/ts/client/gameLoop.ts b/src/ts/client/gameLoop.ts
index 97836f7..fe797a8 100644
--- a/src/ts/client/gameLoop.ts
+++ b/src/ts/client/gameLoop.ts
@@ -45,7 +45,8 @@ export function startGameLoop(game: Game, onError = (e: Error) => console.error(
if (draw) {
game.draw();
}
- } catch (e) {
+ }
+ catch (e) {
if (isError(e)) {
onError(e);
}
@@ -80,7 +81,8 @@ export function startGameLoop(game: Game, onError = (e: Error) => console.error(
.then(() => {
if (cancelled) {
throw new Error('Cancelled (loop)');
- } else {
+ }
+ else {
game.init();
handle = requestAnimationFrame(onFrame);
backup = setTimeout(onTimer, 1000 / 10);
diff --git a/src/ts/client/handlers.ts b/src/ts/client/handlers.ts
index a3f1c9d..aa68265 100644
--- a/src/ts/client/handlers.ts
+++ b/src/ts/client/handlers.ts
@@ -130,7 +130,8 @@ export function handleUpdateEntity(game: PonyTownGame, update: DecodedUpdate) {
}
}
}
- } else if (distanceXY(entity.x, entity.y, x, y) > 8) {
+ }
+ else if (distanceXY(entity.x, entity.y, x, y) > 8) {
log(`Fixing player position (${entity.x}, ${entity.y}) => (${x}, ${y})`);
entity.x = x;
entity.y = y;
@@ -163,7 +164,8 @@ export function handleUpdateEntity(game: PonyTownGame, update: DecodedUpdate) {
if (entity.fake) {
(entity as Pony).palettePonyInfo = decodePonyInfo(ponyInfo, mockPaletteManager);
- } else {
+ }
+ else {
updatePonyInfoWithPoof(game, entity, ponyInfo, crc);
}
}
@@ -173,7 +175,8 @@ export function handleUpdateEntity(game: PonyTownGame, update: DecodedUpdate) {
}
applyIfSelected(game, id);
- } else {
+ }
+ else {
log(`handleUpdateEntity: missing entity: ${id}`);
}
}
@@ -315,7 +318,8 @@ export function handleUpdates(game: PonyTownGame, updates: Uint8Array) {
if (region) {
handleAddEntity(game, region, update, false);
- } else {
+ }
+ else {
log(`handleUpdates (add): missing region at ${x} ${y}`);
}
break;
@@ -353,7 +357,8 @@ export function updatePonyInfoWithPoof(game: PonyTownGame, entity: Entity, info:
if (entity && isPony(entity)) {
if (isHidden(entity)) {
update(entity);
- } else {
+ }
+ else {
playEffect(game, entity, poof2.type);
setTimeout(() => update(entity), 100);
}
@@ -365,7 +370,8 @@ export function handleRemoveEntity(game: PonyTownGame, id: number) {
if (entity) {
removeEntity(game.map, entity);
- } else {
+ }
+ else {
log(`handleRemoveEntity: Missing entity: ${id}`);
}
@@ -441,21 +447,26 @@ export function handleAction(game: PonyTownGame, id: number, action: Action) {
default:
log(`handleAction: Invalid action: ${action}`);
}
- } else {
+ }
+ else {
log(`handleAction: Missing entity: ${id}`);
}
}
export function playEffect(game: PonyTownGame, target: Entity, type: number) {
- if (isHidden(target))
+ if (isHidden(target)) {
return;
+ }
try {
const entity = createAnEntity(type, 0, target.x, target.y, {}, game.paletteManager, game);
addEntity(game.map, entity);
setTimeout(() => removeEntityDirectly(game.map, entity), 1000);
- } catch (e) {
- DEVELOPMENT && console.error(e);
+ }
+ catch (e) {
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
}
}
@@ -554,7 +565,8 @@ export function containsFilteredWords(message: string, filter: string | undefine
if (filter) {
const words = compact(filter.replace(/[,]/g, ' ').split(/[\r\n\t ]+/g).map(x => x.trim()));
cachedRegex = new RegExp(`(^| )(${words.map(escapeRegExp).join('|')})($| )`, 'i');
- } else {
+ }
+ else {
cachedRegex = undefined;
}
@@ -569,8 +581,11 @@ export function handleSays(game: PonyTownGame, id: number, message: string, type
if (entity) {
handleSay(game, entity, message, type);
- } else {
- DEVELOPMENT && console.warn('incomplete say');
+ }
+ else {
+ if (DEVELOPMENT) {
+ console.warn('incomplete say');
+ }
game.incompleteSays.push({ id, message, type, time: Date.now() });
game.send(server => server.actionParam2(Action.RequestEntityInfo, id));
}
@@ -589,32 +604,41 @@ function isFriendEntityId(game: PonyTownGame, id: number) {
}
function shouldShowChatMessage(game: PonyTownGame, entity: Entity | FakeEntity, message: string, type: MessageType): boolean {
- if (entity === game.player)
+ if (entity === game.player) {
return true;
+ }
- if (isWhisperTo(type))
+ if (isWhisperTo(type)) {
return true;
+ }
- if (isWhisper(type) && isFriendEntityId(game, entity.id))
+ if (isWhisper(type) && isFriendEntityId(game, entity.id)) {
return true;
+ }
- if (isPublicMessage(type) && !entity.fake && !isChatVisible(game.camera, entity))
+ if (isPublicMessage(type) && !entity.fake && !isChatVisible(game.camera, entity)) {
return false;
+ }
- if (isNonIgnorableMessage(type))
+ if (isNonIgnorableMessage(type)) {
return true;
+ }
- if (game.settings.account.filterCyrillic && containsCyrillic(message))
+ if (game.settings.account.filterCyrillic && containsCyrillic(message)) {
return false;
+ }
- if (game.settings.account.ignorePublicChat && isPublicMessage(type))
+ if (game.settings.account.ignorePublicChat && isPublicMessage(type)) {
return false;
+ }
- if (isWhisper(type) && game.settings.account.ignoreNonFriendWhispers)
+ if (isWhisper(type) && game.settings.account.ignoreNonFriendWhispers) {
return false;
+ }
- if (containsFilteredWords(message, game.settings.account.filterWords))
+ if (containsFilteredWords(message, game.settings.account.filterWords)) {
return false;
+ }
return true;
}
@@ -624,30 +648,36 @@ function isChatInRange(entity: Entity, player: Entity | undefined, range: number
}
function shouldShowChatMessageInChatlog(game: PonyTownGame, entity: Entity | FakeEntity, type: MessageType) {
- if (entity.type !== PONY_TYPE)
+ if (entity.type !== PONY_TYPE) {
return false;
+ }
- if (entity.fake)
+ if (entity.fake) {
return true;
+ }
- if (!isPublicMessage(type))
+ if (!isPublicMessage(type)) {
return true;
+ }
- if (!isChatInRange(entity, game.player, game.settings.account.chatlogRange))
+ if (!isChatInRange(entity, game.player, game.settings.account.chatlogRange)) {
return false;
+ }
return true;
}
export function handleSay(game: PonyTownGame, entity: Entity | FakeEntity, message: string, type: MessageType) {
- if (!shouldShowChatMessage(game, entity, message, type))
+ if (!shouldShowChatMessage(game, entity, message, type)) {
return;
+ }
if (type === MessageType.Dismiss || message === '.') {
if (!entity.fake && entity.says) {
dismissSays(entity.says);
}
- } else {
+ }
+ else {
const bubbleEntity = isWhisperTo(type) ? game.player : entity;
if (bubbleEntity && !bubbleEntity.fake && game.map.entitiesById.has(bubbleEntity.id)) {
@@ -677,7 +707,8 @@ export function handleEntityInfo(game: PonyTownGame, id: number, name: string, c
game.incompleteSays.splice(i, 1);
const entity: FakeEntity = { fake: true, type: PONY_TYPE, id, name, crc };
handleSay(game, entity, say.message, say.type);
- } else {
+ }
+ else {
i++;
}
}
@@ -697,9 +728,11 @@ export function subscribeRegion(game: PonyTownGame, data: Uint8Array) {
export function filterEntityName({ settings, worldFlags }: PonyTownGame, name: string | undefined, nameBad: boolean) {
if (name && nameBad && (settings.account.filterSwearWords || hasFlag(worldFlags, WorldStateFlags.Safe))) {
return repeat('*', name.length);
- } else if (name && containsFilteredWords(name, settings.account.filterWords)) {
+ }
+ else if (name && containsFilteredWords(name, settings.account.filterWords)) {
return repeat('?', name.length);
- } else {
+ }
+ else {
return name;
}
}
@@ -722,7 +755,8 @@ function createEntityOrPony(
}
return entity;
- } else {
+ }
+ else {
const entity = createAnEntity(type, id, x, y, options, game.paletteManager, game);
entity.state = state;
@@ -744,8 +778,9 @@ function updateEntityOptionsInternal(entity: Entity, options: Partial f.accountId === accountId);
@@ -754,7 +789,8 @@ export function handleUpdateFriends(game: PonyTownGame, friends: FriendStatusDat
if (friend) {
removeItem(game.model.friends, friend);
}
- } else {
+ }
+ else {
if (!friend) {
friend = {
accountId,
@@ -817,7 +853,9 @@ export function handleUpdateFriends(game: PonyTownGame, friends: FriendStatusDat
}
}
- DEVELOPMENT && console.log('Refreshing friend list');
+ if (DEVELOPMENT) {
+ console.log('Refreshing friend list');
+ }
}
game.model.friends.sort(compareFriends);
diff --git a/src/ts/client/htmlUtils.ts b/src/ts/client/htmlUtils.ts
index 96845aa..adcdc2c 100644
--- a/src/ts/client/htmlUtils.ts
+++ b/src/ts/client/htmlUtils.ts
@@ -27,7 +27,8 @@ export function createHtmlNodes(value: string | undefined, scale: number): Node[
});
return img;
- } else {
+ }
+ else {
return document.createTextNode(x);
}
}) : [];
@@ -88,7 +89,9 @@ export function removeFirstChild(element: HTMLElement) {
}
export function removeElement(element: HTMLElement) {
- element.parentElement && element.parentElement.removeChild(element);
+ if (element.parentElement) {
+ element.parentElement.removeChild(element);
+ }
}
export function replaceNodes(element: HTMLElement, text: string) {
@@ -105,7 +108,8 @@ export function replaceNodes(element: HTMLElement, text: string) {
if (hasEmojis(text)) {
firstChild.nodeValue = '';
appendAllNodes(element, createHtmlNodes(text, 2));
- } else {
+ }
+ else {
firstChild.nodeValue = text;
}
}
diff --git a/src/ts/client/input/gamepad.ts b/src/ts/client/input/gamepad.ts
index 85b60ac..e2b334d 100644
--- a/src/ts/client/input/gamepad.ts
+++ b/src/ts/client/input/gamepad.ts
@@ -55,7 +55,8 @@ function button({ mapping, gamepad }: GamepadInstance, name: GamepadButtons) {
if (button.axis !== undefined) {
if (button.direction < 0) {
return gamepad.axes[button.axis] < -0.75;
- } else {
+ }
+ else {
return gamepad.axes[button.axis] > 0.75;
}
}
@@ -84,8 +85,9 @@ export class GamePadController implements InputController {
window.removeEventListener('gamepaddisconnected', this.gamepaddisconnected);
}
update() {
- if (this.manager.disabledGamepad || !isFocused() || this.gamepadIndex === -1)
+ if (this.manager.disabledGamepad || !isFocused() || this.gamepadIndex === -1) {
return;
+ }
const gamepads = navigator.getGamepads();
const gamepad = gamepads[this.gamepadIndex];
@@ -150,7 +152,8 @@ function readAxis(manager: InputManager, keyX: Key, keyY: Key, axisX: number, ax
manager.setValue(keyX, Math.cos(theta) * scaledDist);
manager.setValue(keyY, Math.sin(theta) * scaledDist);
return false;
- } else if (!zeroed) {
+ }
+ else if (!zeroed) {
manager.setValue(keyX, 0);
manager.setValue(keyY, 0);
return true;
diff --git a/src/ts/client/input/inputManager.ts b/src/ts/client/input/inputManager.ts
index a359a1c..18d04ce 100644
--- a/src/ts/client/input/inputManager.ts
+++ b/src/ts/client/input/inputManager.ts
@@ -146,7 +146,8 @@ export class InputManager {
setValue(input: Key, value: number): boolean {
if (input < 0 || input >= KEYS) {
console.warn(`Input out of range: ${input}`);
- } else if (this.state[input] !== value) {
+ }
+ else if (this.state[input] !== value) {
this.state[input] = value;
if (this.actions[input] && this.actions[input].length) {
@@ -163,7 +164,8 @@ export class InputManager {
addValue(input: Key, value: number) {
if (input < 0 || input >= KEYS) {
console.warn(`Input out of range: ${input}`);
- } else {
+ }
+ else {
this.state[input] += value;
}
}
diff --git a/src/ts/client/input/keyboard.ts b/src/ts/client/input/keyboard.ts
index 175742c..b045a96 100644
--- a/src/ts/client/input/keyboard.ts
+++ b/src/ts/client/input/keyboard.ts
@@ -14,8 +14,12 @@ function allowKey(key: number) {
function fixKeyCode(key: number) {
if (firefox) {
- if (key === 173) return Key.DASH;
- if (key === 61) return Key.EQUALS;
+ if (key === 173) {
+ return Key.DASH;
+ }
+ if (key === 61) {
+ return Key.EQUALS;
+ }
}
return key;
diff --git a/src/ts/client/input/touch.ts b/src/ts/client/input/touch.ts
index 328975e..3fdc7b3 100644
--- a/src/ts/client/input/touch.ts
+++ b/src/ts/client/input/touch.ts
@@ -122,13 +122,16 @@ export class TouchController implements InputController {
this.touchIsDrag = true;
this.manager.setValue(Key.GAMEPAD_AXIS1_X, -Math.cos(theta) * scaledDist);
this.manager.setValue(Key.GAMEPAD_AXIS1_Y, -Math.sin(theta) * scaledDist);
- } else {
+ }
+ else {
this.manager.setValue(Key.GAMEPAD_AXIS1_X, 0);
this.manager.setValue(Key.GAMEPAD_AXIS1_Y, 0);
}
}
private touchstart = (e: any) => {
- e.cancellable && e.preventDefault();
+ if (e.cancellable) {
+ e.preventDefault();
+ }
e.stopPropagation();
this.manager.usingTouch = true;
@@ -144,7 +147,8 @@ export class TouchController implements InputController {
this.manager.setValue(Key.MOUSE_Y, this.touchStart.y);
this.manager.setValue(Key.TOUCH, 1);
}
- } else if (this.touch2Id === -1) {
+ }
+ else if (this.touch2Id === -1) {
const touch = e.changedTouches.item(0);
if (touch) {
diff --git a/src/ts/client/partyUtils.ts b/src/ts/client/partyUtils.ts
index af81fa5..c196a3e 100644
--- a/src/ts/client/partyUtils.ts
+++ b/src/ts/client/partyUtils.ts
@@ -5,7 +5,8 @@ import { PonyTownGame } from './game';
export function updateParty(current: PartyInfo | undefined, info: PartyMember[] | undefined): PartyInfo | undefined {
if (!info || !info.length) {
return undefined;
- } else {
+ }
+ else {
const party = current || {
leaderId: 0,
members: [],
@@ -18,7 +19,8 @@ export function updateParty(current: PartyInfo | undefined, info: PartyMember[]
if (existing) {
Object.assign(existing, m);
- } else {
+ }
+ else {
party.members.push(m);
}
diff --git a/src/ts/client/playerActions.ts b/src/ts/client/playerActions.ts
index f29bbc7..dc55258 100644
--- a/src/ts/client/playerActions.ts
+++ b/src/ts/client/playerActions.ts
@@ -37,7 +37,8 @@ export function handleActionCommand(message: string, game: PonyTownGame): boolea
if (player) {
if (isPonyLying(player)) {
sitAction(player, game);
- } else {
+ }
+ else {
lieAction(player, game);
}
}
@@ -46,7 +47,8 @@ export function handleActionCommand(message: string, game: PonyTownGame): boolea
if (player) {
if (isPonyFlying(player)) {
standAction(player, game);
- } else {
+ }
+ else {
sitAction(player, game);
}
}
@@ -60,7 +62,8 @@ export function handleActionCommand(message: string, game: PonyTownGame): boolea
if (player) {
if (isPonyFlying(player)) {
standAction(player, game);
- } else {
+ }
+ else {
flyAction(player, game);
}
}
@@ -77,9 +80,11 @@ export function upAction(game: PonyTownGame) {
if (player) {
if (isPonyLying(player)) {
sitAction(player, game);
- } else if (isPonySitting(player)) {
+ }
+ else if (isPonySitting(player)) {
standAction(player, game);
- } else if (isPonyStanding(player)) {
+ }
+ else if (isPonyStanding(player)) {
flyAction(player, game);
}
}
@@ -91,9 +96,11 @@ export function downAction(game: PonyTownGame) {
if (player) {
if (isPonySitting(player)) {
lieAction(player, game);
- } else if (isPonyStanding(player)) {
+ }
+ else if (isPonyStanding(player)) {
sitAction(player, game);
- } else if (isPonyFlying(player)) {
+ }
+ else if (isPonyFlying(player)) {
standAction(player, game);
}
}
@@ -172,11 +179,14 @@ export function interact(game: PonyTownGame, shift: boolean) {
if (entity && entityInRange(entity, player)) {
game.send(server => server.interact(entity.id));
- } else if (player.hold === hammer.type) {
+ }
+ else if (player.hold === hammer.type) {
game.changePlaceEntity(shift);
- } else if (player.hold === shovel.type) {
+ }
+ else if (player.hold === shovel.type) {
game.changePlaceTile(shift);
- } else if (player.ponyState.holding && hasFlag(player.ponyState.holding.flags, EntityFlags.Usable)) {
+ }
+ else if (player.ponyState.holding && hasFlag(player.ponyState.holding.flags, EntityFlags.Usable)) {
game.send(server => server.use());
}
}
@@ -191,13 +201,16 @@ export function toggleWall(game: PonyTownGame, hover: Point) {
if (dx > dy) {
if ((dx + dy) < 1) {
game.send(server => server.changeTile(x, y, TileType.WallH));
- } else {
+ }
+ else {
game.send(server => server.changeTile(x + 1, y, TileType.WallV));
}
- } else {
+ }
+ else {
if ((dx + dy) < 1) {
game.send(server => server.changeTile(x, y, TileType.WallV));
- } else {
+ }
+ else {
game.send(server => server.changeTile(x, y + 1, TileType.WallH));
}
}
@@ -209,8 +222,11 @@ export function editorSelectEntities(game: PonyTownGame, hover: Point, shift: bo
if (shift) {
const entity = entities.filter(e => !includes(game.editor.selectedEntities, e))[0];
- entity && game.editor.selectedEntities.push(entity);
- } else {
+ if (entity) {
+ game.editor.selectedEntities.push(entity);
+ }
+ }
+ else {
const index = entities.findIndex(e => includes(game.editor.selectedEntities, e));
const entity = entities[(index + 1) % entities.length];
game.editor.selectedEntities = entity ? [entity] : [];
@@ -227,7 +243,8 @@ export function editorDragEntities(game: PonyTownGame, hover: Point, buttonPress
e.x = roundPositionX(e.draggingStart!.x + dx);
e.y = roundPositionY(e.draggingStart!.y + dy);
});
- } else {
+ }
+ else {
game.apply(() => game.editor.draggingEntities = false);
game.send(server => server.editorAction({
type: 'move',
diff --git a/src/ts/client/polyfils.ts b/src/ts/client/polyfils.ts
index 3981639..6eaddcd 100644
--- a/src/ts/client/polyfils.ts
+++ b/src/ts/client/polyfils.ts
@@ -5,29 +5,34 @@ try {
if (!('performance' in window && 'now' in performance)) {
(window as any).performance = Date;
}
-} catch { }
+}
+catch { }
try {
if (!('getGamepads' in navigator)) {
(window.navigator as any).getGamepads = () => [];
}
-} catch { }
+}
+catch { }
try {
if (!('requestAnimationFrame' in window)) {
(window as any).requestAnimationFrame = (callback: any) => setTimeout(() => callback(performance.now()), 1000 / 60) as any;
}
-} catch { }
+}
+catch { }
try {
if (!('cancelAnimationFrame' in window)) {
(window as any).cancelAnimationFrame = clearTimeout;
}
-} catch { }
+}
+catch { }
// IE <= 10
try {
if (!('devicePixelRatio' in window)) {
(window as any).devicePixelRatio = 1;
}
-} catch { }
+}
+catch { }
diff --git a/src/ts/client/pony.ts b/src/ts/client/pony.ts
index b83111e..52e032e 100644
--- a/src/ts/client/pony.ts
+++ b/src/ts/client/pony.ts
@@ -162,7 +162,9 @@ export function updatePonyInfo(pony: Pony, info: string | Uint8Array, apply: ()
pony.discardBatch = true;
if (isPonyFlying(pony) && !canPonyFly(pony)) {
- DEVELOPMENT && console.warn('Force land');
+ if (DEVELOPMENT) {
+ console.warn('Force land');
+ }
pony.state = setFlag(pony.state, EntityState.PonyFlying, false);
resetAnimatorState(pony.animator);
}
@@ -201,7 +203,8 @@ export function doBoopPonyAction(game: PonyTownGame, pony: Pony) {
if (pony.swimming && pony.lastBoopSplash < performance.now()) {
if (isFacingRight(pony)) {
playEffect(game, pony, boopSplashRight.type);
- } else {
+ }
+ else {
playEffect(game, pony, boopSplashLeft.type);
}
@@ -242,13 +245,15 @@ export function drawPonyEntity(batch: PaletteSpriteBatch, pony: Pony, drawOption
if (pony.batch !== undefined) {
batch.patchBatchDepth(pony.batch);
batch.drawBatch(pony.batch);
- } else if (pony.palettePonyInfo !== undefined) {
+ }
+ else if (pony.palettePonyInfo !== undefined) {
let swimming = false;
if (isSwimmingState(pony.animator.state)) {
if (pony.animator.state === swimmingToFlying) {
swimming = pony.animator.time < 0.4;
- } else {
+ }
+ else {
swimming = true;
}
}
@@ -294,7 +299,9 @@ export function drawPonyEntity(batch: PaletteSpriteBatch, pony: Pony, drawOption
if (pony.magicEffect.currentAnimation !== undefined) {
drawAnimation(batch, pony.magicEffect, 0, 0, pony.magicColor, flip);
const sprite = sprites.magic3.frames[pony.magicEffect.frame];
- sprite && batch.drawSprite(sprite, WHITE, pony.heartsEffect.palette, 0, 0);
+ if (sprite) {
+ batch.drawSprite(sprite, WHITE, pony.heartsEffect.palette, 0, 0);
+ }
}
}
@@ -384,13 +391,16 @@ export function flagsToState(state: EntityState, moving: boolean, isSwimming: bo
if (isSwimming) {
return swimming;
- } else if (moving) {
+ }
+ else if (moving) {
if (ponyState === EntityState.PonyFlying) {
return flying;
- } else {
+ }
+ else {
return trotting;
}
- } else {
+ }
+ else {
switch (ponyState) {
case EntityState.PonyStanding: return standing;
case EntityState.PonyWalking: return trotting;
@@ -435,7 +445,8 @@ export function updatePonyEntity(pony: Pony, delta: number, gameTime: number, sa
}
pony.doAction = DoAction.None;
- } else {
+ }
+ else {
setAnimatorState(pony.animator, animationState);
}
@@ -448,7 +459,8 @@ export function updatePonyEntity(pony: Pony, delta: number, gameTime: number, sa
if (frame >= pony.headAnimation.frames.length && !pony.headAnimation.loop) {
pony.headAnimation = undefined;
state.headAnimationFrame = 0;
- } else {
+ }
+ else {
state.headAnimationFrame = frame % pony.headAnimation.frames.length;
}
}
@@ -468,7 +480,8 @@ export function updatePonyEntity(pony: Pony, delta: number, gameTime: number, sa
if ((pony.state & EntityState.Magic) !== 0) {
playAnimation(pony.magicEffect, magicAnimation);
- } else {
+ }
+ else {
playAnimation(pony.magicEffect, undefined);
}
@@ -546,11 +559,13 @@ export function updatePonyHold(pony: Pony, game: PonyTownGame) {
if (pony.hold !== 0) {
if (ponyState.holding === undefined) {
ponyState.holding = createAnEntity(pony.hold, 0, 0, 0, {}, pony.paletteManager, game);
- } else if (ponyState.holding.type !== pony.hold) {
+ }
+ else if (ponyState.holding.type !== pony.hold) {
releaseEntity(ponyState.holding);
ponyState.holding = createAnEntity(pony.hold, 0, 0, 0, {}, pony.paletteManager, game);
}
- } else if (ponyState.holding !== undefined) {
+ }
+ else if (ponyState.holding !== undefined) {
releaseEntity(ponyState.holding);
ponyState.holding = undefined;
}
@@ -590,7 +605,8 @@ function filterExpression(expression: Expression) {
if (expression.muzzle === Muzzle.SmilePant) {
expression.muzzle = Muzzle.SmileOpen;
- } else if (expression.muzzle === Muzzle.NeutralPant) {
+ }
+ else if (expression.muzzle === Muzzle.NeutralPant) {
expression.muzzle = Muzzle.NeutralOpen2;
}
}
@@ -598,9 +614,11 @@ function filterExpression(expression: Expression) {
if (blush) {
if (expression.muzzle === Muzzle.SmileOpen2) {
expression.muzzle = Muzzle.SmileOpen;
- } else if (expression.muzzle === Muzzle.FrownOpen) {
+ }
+ else if (expression.muzzle === Muzzle.FrownOpen) {
expression.muzzle = Muzzle.ConcernedOpen;
- } else if (expression.muzzle === Muzzle.NeutralOpen2) {
+ }
+ else if (expression.muzzle === Muzzle.NeutralOpen2) {
expression.muzzle = Muzzle.Oh;
}
}
@@ -619,21 +637,25 @@ function updatePonyExpression(pony: Pony, expr: number, safe: boolean) {
if (hasFlag(extra, ExpressionExtra.Cry)) {
playAnimation(pony.cryEffect, cryAnimation);
- } else if (hasFlag(extra, ExpressionExtra.Tears)) {
+ }
+ else if (hasFlag(extra, ExpressionExtra.Tears)) {
playAnimation(pony.cryEffect, tearsAnimation);
- } else {
+ }
+ else {
playAnimation(pony.cryEffect, undefined);
}
if (hasFlag(extra, ExpressionExtra.Zzz)) {
playOneOfAnimations(pony.zzzEffect, zzzAnimations);
- } else {
+ }
+ else {
playAnimation(pony.zzzEffect, undefined);
}
if (hasFlag(extra, ExpressionExtra.Hearts)) {
playAnimation(pony.heartsEffect, heartsAnimation);
- } else {
+ }
+ else {
playAnimation(pony.heartsEffect, undefined);
}
}
diff --git a/src/ts/client/ponyDraw.ts b/src/ts/client/ponyDraw.ts
index ffe65d0..06c1791 100644
--- a/src/ts/client/ponyDraw.ts
+++ b/src/ts/client/ponyDraw.ts
@@ -112,7 +112,8 @@ export function createHeadTransform(
) {
if (originalTransform !== undefined) {
copyMat2D(headTransform, originalTransform);
- } else {
+ }
+ else {
identityMat2D(headTransform);
}
@@ -140,7 +141,8 @@ const hairOffsets = [
function draw(options: Options, flag: NoDraw) {
if (TOOLS) {
return !hasFlag(options.no, flag);
- } else {
+ }
+ else {
return true;
}
}
@@ -274,13 +276,17 @@ export function drawPony(batch: Batch, info: Info, state: State, ponyX: number,
// selection
if (options.selected) {
const sprite = at(sprites.ponySelections, shadow.frame);
- sprite && batch.drawSprite(sprite, WHITE, info.defaultPalette, shadowX, shadowY);
+ if (sprite) {
+ batch.drawSprite(sprite, WHITE, info.defaultPalette, shadowX, shadowY);
+ }
}
// shadow
if (options.shadow) {
const sprite = at(sprites.ponyShadows, shadow.frame);
- sprite && batch.drawSprite(sprite, options.shadowColor, info.defaultPalette, shadowX, shadowY);
+ if (sprite) {
+ batch.drawSprite(sprite, options.shadowColor, info.defaultPalette, shadowX, shadowY);
+ }
}
// head accessory
@@ -522,7 +528,8 @@ export function drawHead(
if (toy !== undefined) {
drawSet(batch, sprites.extraAccessoriesBehind, toy, extraX, extraY, WHITE);
- } else if (options.extra && draw(options, NoDraw.Behind)) {
+ }
+ else if (options.extra && draw(options, NoDraw.Behind)) {
drawSet(batch, sprites.extraAccessoriesBehind, info.extraAccessory, extraX, extraY, WHITE);
}
@@ -615,7 +622,9 @@ export function drawHead(
const noses = at(sprites.noses, muzzle);
const nose = att(noses, info.nose && info.nose.type)![0];
- nose.mouth && batch.drawSprite(nose.mouth, WHITE, info.defaultPalette, x, y);
+ if (nose.mouth) {
+ batch.drawSprite(nose.mouth, WHITE, info.defaultPalette, x, y);
+ }
if (holding !== undefined && holding.draw !== undefined) {
holding.x = toWorldX(x + toInt(holding.pickableX));
@@ -647,7 +656,8 @@ export function drawHead(
if (toy !== undefined) {
drawSet(batch, sprites.extraAccessories, toy, extraX, extraY, WHITE);
- } else if (options.extra && draw(options, NoDraw.Front)) {
+ }
+ else if (options.extra && draw(options, NoDraw.Front)) {
drawSet(batch, sprites.extraAccessories, info.extraAccessory, extraX, extraY, WHITE);
}
@@ -770,13 +780,21 @@ function drawEye(
) {
if (eye !== undefined) {
if (info.eyeshadow === true) {
- eye.shadow && batch.drawSprite(eye.shadow, WHITE, info.eyeshadowColor, x, y);
- eye.shine && batch.drawSprite(eye.shine, SHINES_COLOR, info.defaultPalette, x, y);
+ if (eye.shadow) {
+ batch.drawSprite(eye.shadow, WHITE, info.eyeshadowColor, x, y);
+ }
+ if (eye.shine) {
+ batch.drawSprite(eye.shine, SHINES_COLOR, info.defaultPalette, x, y);
+ }
}
- eye.base && batch.drawSprite(eye.base, WHITE, eyePalette, x, y);
+ if (eye.base) {
+ batch.drawSprite(eye.base, WHITE, eyePalette, x, y);
+ }
const sprite = at(eye.irises, iris);
- sprite && batch.drawSprite(sprite, WHITE, palette, x, y);
+ if (sprite) {
+ batch.drawSprite(sprite, WHITE, palette, x, y);
+ }
}
}
diff --git a/src/ts/client/rev.ts b/src/ts/client/rev.ts
index 2ecee8f..227e262 100644
--- a/src/ts/client/rev.ts
+++ b/src/ts/client/rev.ts
@@ -2,11 +2,13 @@ import { REV } from '../generated/rev';
/* istanbul ignore next */
export function getUrl(name: string): string {
- if (DEVELOPMENT)
+ if (DEVELOPMENT) {
return `/assets/${name}`;
+ }
- if (!REV[name])
+ if (!REV[name]) {
throw new Error(`Cannot find file url (${name})`);
+ }
return `/assets/${name.replace(/(\.\S+)$/, `-${REV[name]}$1`)}`;
}
diff --git a/src/ts/client/sec.ts b/src/ts/client/sec.ts
index 22adcc6..e26f052 100644
--- a/src/ts/client/sec.ts
+++ b/src/ts/client/sec.ts
@@ -33,7 +33,9 @@ export function restorePlayerPosition() {
if (currentPlayer.x !== setX || currentPlayer.y !== setY) {
currentPlayer.x = setX;
currentPlayer.y = setY;
- DEVELOPMENT && console.warn('Restoring player position');
+ if (DEVELOPMENT) {
+ console.warn('Restoring player position');
+ }
}
}
}
diff --git a/src/ts/client/webgl.ts b/src/ts/client/webgl.ts
index 85202c0..3d0c123 100644
--- a/src/ts/client/webgl.ts
+++ b/src/ts/client/webgl.ts
@@ -68,8 +68,11 @@ export function initWebGLResources(gl: WebGLRenderingContext, paletteManager: Pa
try {
createFrameBuffer(gl, frameBuffer, camera.w, camera.h, true, null);
createFrameBuffer(gl, frameBuffer2, camera.w, camera.h, false, frameBuffer.depthStencilRenderbuffer);
- } catch (e) {
- DEVELOPMENT && console.warn(e);
+ }
+ catch (e) {
+ if (DEVELOPMENT) {
+ console.warn(e);
+ }
failedFBO = true;
failedDepthBuffer = true;
}
diff --git a/src/ts/client/worldMap.ts b/src/ts/client/worldMap.ts
index ad5a9e1..8947fd7 100644
--- a/src/ts/client/worldMap.ts
+++ b/src/ts/client/worldMap.ts
@@ -105,7 +105,8 @@ function pickEntity(
function pickByBounds(entity: Entity, rect: Rect, pickHidden: boolean): boolean {
if ((entity.flags & EntityFlags.Interactive) === 0 || (isHidden(entity) && !pickHidden)) {
return false;
- } else {
+ }
+ else {
const bounds = entity.interactBounds || entity.bounds;
return !!bounds && boundsIntersect(entity.x, entity.y, bounds, 0, 0, rect);
}
@@ -128,8 +129,9 @@ export function pickEntitiesByRect(map: WorldMap, rect: Rect, ignorePonies: bool
}
export function removeRegions(map: WorldMap, coords: number[]) {
- if (coords.length === 0)
+ if (coords.length === 0) {
return;
+ }
const entitiesToRemove = new Set();
@@ -161,7 +163,9 @@ export function setRegion(map: WorldMap, x: number, y: number, region: Region) {
const oldRegion = map.regions[index];
if (oldRegion) {
- DEVELOPMENT && !TESTS && console.error(`Region already set (${x}, ${y})`);
+ if (DEVELOPMENT && !TESTS) {
+ console.error(`Region already set (${x}, ${y})`);
+ }
for (const e of oldRegion.entities.slice()) {
releaseAndRemoveEntityFromMap(map, e);
@@ -172,8 +176,11 @@ export function setRegion(map: WorldMap, x: number, y: number, region: Region) {
setTilesDirty(map, x * REGION_SIZE - 1, y * REGION_SIZE - 1, REGION_SIZE + 2, REGION_SIZE + 2);
map.regions[index] = region;
updateMinMaxRegion(map);
- } else {
- DEVELOPMENT && !TESTS && console.error(`Invalid region coords (${x}, ${y})`);
+ }
+ else {
+ if (DEVELOPMENT && !TESTS) {
+ console.error(`Invalid region coords (${x}, ${y})`);
+ }
}
}
@@ -186,7 +193,8 @@ export function addEntity(map: WorldMap, entity: Entity) {
if (!region) {
throw new Error(`Missing region at ${entity.x} ${entity.y}`);
- } else {
+ }
+ else {
addEntityToMapRegion(map, region, entity);
}
}
@@ -209,7 +217,8 @@ export function removeEntityDirectly(map: WorldMap, entity: Entity) {
releaseEntity(entity);
removeEntityFromEntities(map, entity);
return false;
- } else {
+ }
+ else {
return true;
}
});
@@ -286,9 +295,11 @@ export function addEntityToMapRegion(map: WorldMap, region: Region, entity: Enti
const existing = map.entitiesById.get(entity.id);
if (existing) {
- DEVELOPMENT && !TESTS && console.error(`Adding duplicate entity ${entity.id} (` +
+ if (DEVELOPMENT && !TESTS) {
+ console.error(`Adding duplicate entity ${entity.id} (` +
`${worldToRegionX(existing.x, map)}, ${worldToRegionY(existing.y, map)} => ` +
`${worldToRegionX(entity.x, map)}, ${worldToRegionY(entity.y, map)})`);
+ }
removeEntity(map, existing);
}
@@ -419,7 +430,8 @@ export function updateEntitiesCoverLifted(map: WorldMap, player: Entity, hideObj
if (e.coverLifted && lifting < 1) {
e.coverLifting = Math.min(lifting + delta * 2, 1);
- } else if (!e.coverLifted && lifting > 0) {
+ }
+ else if (!e.coverLifted && lifting > 0) {
e.coverLifting = Math.max(lifting - delta * 2, 0);
}
}
@@ -460,7 +472,9 @@ export function getMapHeightAt(map: WorldMap, x: number, y: number, gameTime: nu
}
export function updateEntities(game: PonyTownGame, gameTime: number, delta: number, safe: boolean) {
- TIMING && timeStart('updateEntities');
+ if (TIMING) {
+ timeStart('updateEntities');
+ }
const map = game.map;
@@ -475,7 +489,8 @@ export function updateEntities(game: PonyTownGame, gameTime: number, delta: numb
const bobs = entity.bobs!;
const frame = (((gameTime / 1000) * entity.bobsFps!) | 0) % bobs.length;
entity.z = toWorldZ(bobs[frame]);
- } else if ((flags & EntityFlags.StaticY) === 0) {
+ }
+ else if ((flags & EntityFlags.StaticY) === 0) {
entity.z = getMapHeightAt(map, entity.x, entity.y, gameTime);
}
@@ -489,11 +504,13 @@ export function updateEntities(game: PonyTownGame, gameTime: number, delta: numb
if (wasSwimming !== pony.swimming) {
if (isFlyingDown(pony.animator.state)) {
setTimeout(() => playEffect(game, pony, splash.type), 400);
- } else {
+ }
+ else {
playEffect(game, pony, splash.type);
}
}
- } else if (entity.update !== undefined) {
+ }
+ else if (entity.update !== undefined) {
entity.update(delta, gameTime);
}
@@ -516,7 +533,8 @@ export function updateEntities(game: PonyTownGame, gameTime: number, delta: numb
if (Math.abs(entity.lightScale! - entity.lightTarget!) < move) {
entity.lightScale = entity.lightTarget;
entity.lightTarget = 1 - Math.random() * 0.15;
- } else {
+ }
+ else {
entity.lightScale! += entity.lightScale! < entity.lightTarget! ? move : -move;
}
}
@@ -538,7 +556,9 @@ export function updateEntities(game: PonyTownGame, gameTime: number, delta: numb
}
}
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
}
export function invalidatePalettes(entities: Entity[]) {
@@ -552,8 +572,9 @@ export function invalidatePalettes(entities: Entity[]) {
export function ensureAllVisiblePoniesAreDecoded(map: WorldMap, camera: Camera, paletteManager: PaletteManager) {
const poniesToDecode = map.poniesToDecode;
- if (!poniesToDecode.length)
+ if (!poniesToDecode.length) {
return;
+ }
const decode = new Set();
@@ -565,8 +586,9 @@ export function ensureAllVisiblePoniesAreDecoded(map: WorldMap, camera: Camera,
}
}
- if (!decode.size)
+ if (!decode.size) {
return;
+ }
if (decode.size > 100) {
paletteManager.deduplicate = false;
@@ -575,10 +597,12 @@ export function ensureAllVisiblePoniesAreDecoded(map: WorldMap, camera: Camera,
map.poniesToDecode = poniesToDecode.filter((pony, i) => {
if (pony.palettePonyInfo !== undefined) {
return false;
- } else if (decode.has(i)) {
+ }
+ else if (decode.has(i)) {
ensurePonyInfoDecoded(pony);
return false;
- } else {
+ }
+ else {
return true;
}
});
@@ -595,7 +619,8 @@ export function switchEntityRegion(map: WorldMap, entity: Entity, x: number, y:
if (region) {
addEntityToRegion(region, entity, map);
- } else {
+ }
+ else {
releaseAndRemoveEntityFromMap(map, entity);
}
}
diff --git a/src/ts/common/accountUtils.ts b/src/ts/common/accountUtils.ts
index da318da..85c85f5 100644
--- a/src/ts/common/accountUtils.ts
+++ b/src/ts/common/accountUtils.ts
@@ -41,13 +41,17 @@ function meetsSupporterRequirement(account: AccountSupporter, require: string):
if (require === 'inv') {
return modOrDev || level >= 1 || !!account.supporterInvited;
- } else if (require === 'sup1') {
+ }
+ else if (require === 'sup1') {
return modOrDev || level >= 1;
- } else if (require === 'sup2') {
+ }
+ else if (require === 'sup2') {
return modOrDev || level >= 2;
- } else if (require === 'sup3') {
+ }
+ else if (require === 'sup3') {
return modOrDev || level >= 3;
- } else {
+ }
+ else {
return false;
}
}
@@ -60,7 +64,8 @@ export function getCharacterLimit(account: AccountSupporter) {
default:
if (hasFlag(account.flags, AccountDataFlags.PastSupporter)) {
return BASE_CHARACTER_LIMIT + ADDITIONAL_CHARACTERS_PAST_SUPPORTER;
- } else {
+ }
+ else {
return BASE_CHARACTER_LIMIT;
}
}
@@ -69,7 +74,8 @@ export function getCharacterLimit(account: AccountSupporter) {
export function getSupporterInviteLimit(account: AccountSupporter) {
if (isMod(account) || isDev(account)) {
return 100;
- } else {
+ }
+ else {
switch (account.supporter) {
case 1: return 1;
case 2: return 5;
diff --git a/src/ts/common/adminInterfaces.ts b/src/ts/common/adminInterfaces.ts
index af9983c..6f30cf8 100644
--- a/src/ts/common/adminInterfaces.ts
+++ b/src/ts/common/adminInterfaces.ts
@@ -352,6 +352,7 @@ export const enum SupporterFlags {
Supporter1 = 1,
Supporter2 = 2,
Supporter3 = 3,
+ // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values
SupporterMask = 0x0003,
IgnorePatreon = 0x0080,
PastSupporter = 0x0100,
@@ -489,11 +490,9 @@ export const eventFields: (keyof Event)[] = [
// models
-export interface OriginInfo extends OriginInfoBase {
-}
+export type OriginInfo = OriginInfoBase;
-export interface Timestamps extends TimestampsBase {
-}
+export type Timestamps = TimestampsBase;
export interface AccountStatus {
online: boolean;
diff --git a/src/ts/common/adminUtils.ts b/src/ts/common/adminUtils.ts
index 795ee85..9204c17 100644
--- a/src/ts/common/adminUtils.ts
+++ b/src/ts/common/adminUtils.ts
@@ -31,9 +31,11 @@ export function compareAuths(a: Auth, b: Auth) {
if (aDeleted && !bDeleted) {
return 1;
- } else if (!aDeleted && bDeleted) {
+ }
+ else if (!aDeleted && bDeleted) {
return -1;
- } else {
+ }
+ else {
return compareByName(a, b);
}
}
@@ -82,7 +84,8 @@ export function filterAccounts(items: Account[], search: string, showOnly: strin
if (filter) {
if (not) {
items = items.filter(i => !filter(i));
- } else {
+ }
+ else {
items = items.filter(filter);
}
}
@@ -106,20 +109,27 @@ export function createFilter(search: string): (account: Account) => boolean {
}
function filter(account: Account): boolean {
- if (account._id === search)
+ if (account._id === search) {
return true;
- if (test(account.name))
+ }
+ if (test(account.name)) {
return true;
- if (test(account.note))
+ }
+ if (test(account.note)) {
return true;
- if (account.roles && account.roles.some(test))
+ }
+ if (account.roles && account.roles.some(test)) {
return true;
- if (account.emails && account.emails.some(test))
+ }
+ if (account.emails && account.emails.some(test)) {
return true;
- if (account.auths && account.auths.some(testAuth))
+ }
+ if (account.auths && account.auths.some(testAuth)) {
return true;
- if (account.merges && account.merges.some(testMerge))
+ }
+ if (account.merges && account.merges.some(testMerge)) {
return true;
+ }
return false;
}
@@ -165,8 +175,9 @@ export function createPotentialDuplicatesFilter(getAccountsByBrowserId: (id: str
return i => {
const name = i.nameLower;
- if (name === 'anonymous' || !i.lastBrowserId)
+ if (name === 'anonymous' || !i.lastBrowserId) {
return false;
+ }
const accounts = getAccountsByBrowserId(i.lastBrowserId);
@@ -187,15 +198,20 @@ export function createFilter2(showOnly: string): ((account: Account) => boolean)
if (showOnly === 'banned') {
return hasAnyBan;
- } else if (showOnly === 'timed out') {
+ }
+ else if (showOnly === 'timed out') {
return i => !!((i.mute && i.mute > now) || (i.shadow && i.shadow > now) || (i.ban && i.ban > now));
- } else if (showOnly === 'with flags') {
+ }
+ else if (showOnly === 'with flags') {
return i => !!i.flags;
- } else if (showOnly === 'notes') {
+ }
+ else if (showOnly === 'notes') {
return i => !!i.note;
- } else if (showOnly === 'supporters') {
+ }
+ else if (showOnly === 'supporters') {
return i => !!(i.patreon || i.supporter || i.supporterDeclinedSince);
- } else {
+ }
+ else {
return undefined;
}
}
@@ -206,7 +222,8 @@ export function getPotentialDuplicates(account: Account, getAccountsByBrowserId:
if (accounts !== undefined && accounts.length > 1 && name !== 'anonymous') {
return accounts.filter(a => a !== account && a.nameLower === name);
- } else {
+ }
+ else {
return [];
}
}
@@ -214,18 +231,24 @@ export function getPotentialDuplicates(account: Account, getAccountsByBrowserId:
// duplicates
export function compareDuplicates(a: DuplicateBase, b: DuplicateBase): number {
- if (a.note !== b.note)
+ if (a.note !== b.note) {
return b.note - a.note;
- if (a.emails !== b.emails)
+ }
+ if (a.emails !== b.emails) {
return b.emails - a.emails;
- if (a.name !== b.name)
+ }
+ if (a.name !== b.name) {
return b.name - a.name;
- if (a.browserId !== b.browserId)
+ }
+ if (a.browserId !== b.browserId) {
return a.browserId ? -1 : 1;
- if (a.origins !== b.origins)
+ }
+ if (a.origins !== b.origins) {
return b.origins - a.origins;
- if (a.ponies !== b.ponies)
+ }
+ if (a.ponies !== b.ponies) {
return (b.ponies ? b.ponies.length : 0) - (a.ponies ? a.ponies.length : 0);
+ }
return b.lastVisit.getTime() - a.lastVisit.getTime();
}
@@ -236,7 +259,8 @@ export function emailName(email: string): string {
export function createEmailMatcher(emails: string[]): ((email: string) => boolean) | undefined {
if (!emails || !emails.length) {
return undefined;
- } else {
+ }
+ else {
const match = emails.map(emailName).map(escapeRegExp).join('|');
const regex = new RegExp(`^(?:${match})@`, 'i');
return email => regex.test(email);
@@ -296,7 +320,8 @@ export function duplicatesCollector(duplicates: string[]) {
return (item: string) => {
if (set.has(item)) {
duplicates.push(item);
- } else {
+ }
+ else {
set.add(item);
}
};
@@ -393,7 +418,8 @@ export function addToMap(map: Map, key: string, item: T) {
if (items) {
items.push(item);
- } else {
+ }
+ else {
map.set(key, [item]);
}
}
@@ -426,7 +452,8 @@ export function createIdStore() {
if (result) {
return result;
- } else {
+ }
+ else {
idsMap.set(id, id);
return id;
}
diff --git a/src/ts/common/animationPlayer.ts b/src/ts/common/animationPlayer.ts
index d627137..2038cd9 100644
--- a/src/ts/common/animationPlayer.ts
+++ b/src/ts/common/animationPlayer.ts
@@ -34,13 +34,15 @@ export function playAnimation(player: AnimationPlayer, animation: SpriteAnimatio
player.time = (player.frame + 1) / player.currentAnimation.fps;
player.phase = AnimationPhase.Ending;
}
- } else {
+ }
+ else {
player.currentAnimation = animation;
player.time = 0;
player.phase = AnimationPhase.Starting;
}
player.dirty = true;
- } else if (player.phase === AnimationPhase.Ending) {
+ }
+ else if (player.phase === AnimationPhase.Ending) {
player.nextAnimation = animation;
player.dirty = true;
}
@@ -95,12 +97,14 @@ export function drawAnimation(
throw new Error('Undefined frame in sprite animation');
}
- if (!frame) // TEMP
+ if (!frame) { // TEMP
return;
+ }
if (maxY === 0) {
batch.drawSprite(frame, color, player.palette, x, y);
- } else {
+ }
+ else {
drawSpriteCropped(batch, frame, color, player.palette, x, y, maxY);
}
}
diff --git a/src/ts/common/animator.ts b/src/ts/common/animator.ts
index c5580f7..0016beb 100644
--- a/src/ts/common/animator.ts
+++ b/src/ts/common/animator.ts
@@ -71,10 +71,12 @@ export function setAnimatorState(animator: Animator, sta
if (animator.state !== state) {
if (animator.state === undefined) {
animator.state = state;
- } else {
+ }
+ else {
animator.target = state;
}
- } else {
+ }
+ else {
animator.target = undefined;
}
@@ -106,7 +108,8 @@ export function updateAnimator(animator: Animator, delta
if (frameTimeAfter >= exitAfter || animationEnded) {
if (!transition.keepTime) {
animator.time = transition.enterTime || 0;
- } else {
+ }
+ else {
animator.time = animator.time % animationLength;
}
diff --git a/src/ts/common/binaryUtils.ts b/src/ts/common/binaryUtils.ts
index 11fcf12..c86840e 100644
--- a/src/ts/common/binaryUtils.ts
+++ b/src/ts/common/binaryUtils.ts
@@ -10,10 +10,12 @@ export function writeBinary(write: (writer: BinaryWriter) => void): Uint8Array {
try {
write(writer);
break;
- } catch (e) {
+ }
+ catch (e) {
if (e instanceof RangeError || isDataViewError(e)) {
resizeWriter(writer);
- } else {
+ }
+ else {
throw e;
}
}
@@ -23,7 +25,9 @@ export function writeBinary(write: (writer: BinaryWriter) => void): Uint8Array {
}
export function decodeString(value: DataView | null, offset: number, length: number): string | null {
- if (value == null) return null;
+ if (value == null) {
+ return null;
+ }
let result = '';
const end = offset + length;
@@ -34,14 +38,16 @@ export function decodeString(value: DataView | null, offset: number, length: num
if ((byte1 & 0x80) === 0) {
code = byte1;
- } else if ((byte1 & 0xe0) === 0xc0) {
+ }
+ else if ((byte1 & 0xe0) === 0xc0) {
const byte2 = continuationByte(value, i++, end);
code = ((byte1 & 0x1f) << 6) | byte2;
if (code < 0x80) {
throw Error('Invalid continuation byte');
}
- } else if ((byte1 & 0xf0) === 0xe0) {
+ }
+ else if ((byte1 & 0xf0) === 0xe0) {
const byte2 = continuationByte(value, i++, end);
const byte3 = continuationByte(value, i++, end);
code = ((byte1 & 0x0f) << 12) | (byte2 << 6) | byte3;
@@ -53,7 +59,8 @@ export function decodeString(value: DataView | null, offset: number, length: num
if (code >= 0xd800 && code <= 0xdfff) {
throw Error(`Lone surrogate U+${code.toString(16).toUpperCase()} is not a scalar value`);
}
- } else if ((byte1 & 0xf8) === 0xf0) {
+ }
+ else if ((byte1 & 0xf8) === 0xf0) {
const byte2 = continuationByte(value, i++, end);
const byte3 = continuationByte(value, i++, end);
const byte4 = continuationByte(value, i++, end);
@@ -62,7 +69,8 @@ export function decodeString(value: DataView | null, offset: number, length: num
if (code < 0x010000 || code > 0x10ffff) {
throw Error('Invalid continuation byte');
}
- } else {
+ }
+ else {
throw Error('Invalid UTF-8 detected');
}
@@ -79,13 +87,16 @@ export function decodeString(value: DataView | null, offset: number, length: num
}
function continuationByte(buffer: DataView, index: number, end: number): number {
- if (index >= end) throw Error('Invalid byte index');
+ if (index >= end) {
+ throw Error('Invalid byte index');
+ }
const continuationByte = buffer.getUint8(index);
if ((continuationByte & 0xC0) === 0x80) {
return continuationByte & 0x3F;
- } else {
+ }
+ else {
throw Error('Invalid continuation byte');
}
}
@@ -99,8 +110,9 @@ export function encodeString(string?: string | null) {
}
export function getStringLengthWithLength(value?: string | null) {
- if (value == null)
+ if (value == null) {
return 1;
+ }
const len = stringLengthInBytes(value);
return getLength(len) + len;
}
@@ -134,7 +146,8 @@ function forEachCharacter(value: string, callback: (code: number) => void) {
callback(((code & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
}
}
- } else {
+ }
+ else {
callback(code);
}
}
@@ -143,11 +156,14 @@ function forEachCharacter(value: string, callback: (code: number) => void) {
function charLengthInBytes(code: number): number {
if ((code & 0xffffff80) === 0) {
return 1;
- } else if ((code & 0xfffff800) === 0) {
+ }
+ else if ((code & 0xfffff800) === 0) {
return 2;
- } else if ((code & 0xffff0000) === 0) {
+ }
+ else if ((code & 0xffff0000) === 0) {
return 3;
- } else {
+ }
+ else {
return 4;
}
}
diff --git a/src/ts/common/canvasUtils.ts b/src/ts/common/canvasUtils.ts
index d2ec4a0..fc5394f 100644
--- a/src/ts/common/canvasUtils.ts
+++ b/src/ts/common/canvasUtils.ts
@@ -77,7 +77,8 @@ export function canvasToSource(canvas: HTMLCanvasElement) {
canvas.toBlob(blob => {
if (blob) {
resolve(URL.createObjectURL(blob));
- } else {
+ }
+ else {
reject(new Error('Failed to convert canvas'));
}
});
@@ -93,7 +94,8 @@ export function saveCanvas(canvas: HTMLCanvasElement, name: string) {
export function disableImageSmoothing(context: CanvasRenderingContext2D) {
if ('imageSmoothingEnabled' in context) {
context.imageSmoothingEnabled = false;
- } else {
+ }
+ else {
(context as any).webkitImageSmoothingEnabled = false;
(context as any).mozImageSmoothingEnabled = false;
(context as any).msImageSmoothingEnabled = false;
diff --git a/src/ts/common/collision.ts b/src/ts/common/collision.ts
index cadccb0..662291c 100644
--- a/src/ts/common/collision.ts
+++ b/src/ts/common/collision.ts
@@ -68,14 +68,16 @@ function isPonyColliding(x: number, y: number, map
function isColliding(x: number, y: number, mask: number, map: IMap) {
if (x < 0 || x >= (map.width * tileWidth) || y < 0 || y >= (map.height * tileHeight)) {
return true;
- } else {
+ }
+ else {
const regionX = (x / REGION_WIDTH) | 0;
const regionY = (y / REGION_HEIGHT) | 0;
const region = map.regions[regionX + regionY * map.regionsX];
if (region === undefined) {
return true;
- } else {
+ }
+ else {
const insideX = (x % REGION_WIDTH) | 0;
const insideY = (y % REGION_HEIGHT) | 0;
return (region.collider[insideX + insideY * REGION_WIDTH] & mask) !== 0;
@@ -153,24 +155,29 @@ export function updatePosition(entity: Entity, delta: number, map: IMap dstX) {
+ }
+ else if (srcX > dstX) {
if (srcY < dstY) {
oy = 1;
stepYT = 1 | 0;
stepXF = -1 | 0;
- } else {
+ }
+ else {
stepYT = -1 | 0;
stepXF = -1 | 0;
}
- } else {
+ }
+ else {
if (srcY < dstY) {
stepYF = stepYT = 1 | 0;
- } else {
+ }
+ else {
stepYF = stepYT = -1 | 0;
}
}
@@ -187,7 +194,8 @@ export function updatePosition(entity: Entity, delta: number, map: IMap fy) : (fx < fy)) {
tx = (tx + stepXT) | 0;
ty = (ty + stepYT) | 0;
- } else {
+ }
+ else {
tx = (tx + stepXF) | 0;
ty = (ty + stepYF) | 0;
}
@@ -217,7 +225,8 @@ export function updatePosition(entity: Entity, delta: number, map: IMap, region: Region,
if (x === 0) {
const r = getRegionUnsafe(map, region.x - 1, region.y);
- r && (r.colliderDirty = true);
- } else if (x === (REGION_SIZE - 1)) {
+ if (r) {
+ (r.colliderDirty = true);
+ }
+ }
+ else if (x === (REGION_SIZE - 1)) {
const r = getRegionUnsafe(map, region.x + 1, region.y);
- r && (r.colliderDirty = true);
+ if (r) {
+ (r.colliderDirty = true);
+ }
}
if (y === 0) {
const r = getRegionUnsafe(map, region.x, region.y - 1);
- r && (r.colliderDirty = true);
- } else if (y === (REGION_SIZE - 1)) {
+ if (r) {
+ (r.colliderDirty = true);
+ }
+ }
+ else if (y === (REGION_SIZE - 1)) {
const r = getRegionUnsafe(map, region.x, region.y + 1);
- r && (r.colliderDirty = true);
+ if (r) {
+ (r.colliderDirty = true);
+ }
}
}
diff --git a/src/ts/common/color.ts b/src/ts/common/color.ts
index 3377b00..fc94af8 100644
--- a/src/ts/common/color.ts
+++ b/src/ts/common/color.ts
@@ -217,7 +217,8 @@ export function colorToCSS(color: number): string {
if (alpha === 0xff) {
return `#${colorToHexRGB(color)}`;
- } else {
+ }
+ else {
return `rgba(${getR(color)},${getG(color)},${getB(color)},${alpha / 255})`;
}
}
@@ -277,26 +278,30 @@ export function colorFromHSVAObject({ h, s, v, a }: HSVA) {
// parse
export function parseColorFast(str: string): number {
- if (!isString(str))
+ if (!isString(str)) {
return TRANSPARENT;
+ }
const int = parseInt(str, 16);
if (str.length !== 6 || isNaN(int) || int < 0) {
return parseColorWithAlpha(str, 1);
- } else {
+ }
+ else {
return (((int << 8) | 0xff) >>> 0);
}
}
export function parseColor(str: string): number {
- if (!isString(str))
+ if (!isString(str)) {
return TRANSPARENT;
+ }
str = str.trim().toLowerCase();
- if (str === '' || str === 'none' || str === 'transparent')
+ if (str === '' || str === 'none' || str === 'transparent') {
return TRANSPARENT;
+ }
str = colorNames[str] || str;
@@ -320,7 +325,8 @@ export function parseColor(str: string): number {
parseInt(s.charAt(0), 16) * 0x11,
parseInt(s.charAt(1), 16) * 0x11,
parseInt(s.charAt(2), 16) * 0x11, 255);
- } else {
+ }
+ else {
return colorFromRGBA(
parseInt(s.substr(0, 2), 16),
parseInt(s.substr(2, 2), 16),
@@ -511,18 +517,34 @@ export function rgb2hsl(rgb: RGB): HSL {
let s;
let l;
- if (max === min) h = 0;
- else if (r === max) h = (g - b) / delta;
- else if (g === max) h = 2 + (b - r) / delta;
- else if (b === max) h = 4 + (r - g) / delta;
+ if (max === min) {
+ h = 0;
+ }
+ else if (r === max) {
+ h = (g - b) / delta;
+ }
+ else if (g === max) {
+ h = 2 + (b - r) / delta;
+ }
+ else if (b === max) {
+ h = 4 + (r - g) / delta;
+ }
h = Math.min(h * 60, 360);
- if (h < 0) h += 360;
+ if (h < 0) {
+ h += 360;
+ }
l = (min + max) / 2;
- if (max === min) s = 0;
- else if (l <= 0.5) s = delta / (max + min);
- else s = delta / (2 - max - min);
+ if (max === min) {
+ s = 0;
+ }
+ else if (l <= 0.5) {
+ s = delta / (max + min);
+ }
+ else {
+ s = delta / (2 - max - min);
+ }
h = Math.floor(h);
s = Math.floor(s * 100);
l = Math.floor(l * 100);
diff --git a/src/ts/common/colors.ts b/src/ts/common/colors.ts
index d3236b9..df65a1d 100644
--- a/src/ts/common/colors.ts
+++ b/src/ts/common/colors.ts
@@ -123,7 +123,8 @@ export function blushColor(coat: number): number {
(h > 280 && s > 0.2 && s < 0.7 && v > 0.85)
) {
return DARK_BLUSH;
- } else {
+ }
+ else {
return LIGHT_BLUSH;
}
}
@@ -134,9 +135,11 @@ export function getTileColor(tile: TileType, season: Season) {
case TileType.ElevatedDirt:
if (season === Season.Autumn) {
return 0xedd29eff;
- } else if (season === Season.Winter) {
+ }
+ else if (season === Season.Winter) {
return 0xd9c2a1ff;
- } else {
+ }
+ else {
return 0xf5d99bff;
}
case TileType.Water:
@@ -146,9 +149,11 @@ export function getTileColor(tile: TileType, season: Season) {
case TileType.Grass:
if (season === Season.Autumn) {
return 0xddcf71ff;
- } else if (season === Season.Winter) {
+ }
+ else if (season === Season.Winter) {
return 0xe1ebf8ff;
- } else {
+ }
+ else {
return 0x7cc991ff;
}
case TileType.Ice:
diff --git a/src/ts/common/compress.ts b/src/ts/common/compress.ts
index df344fe..3e3cbb1 100644
--- a/src/ts/common/compress.ts
+++ b/src/ts/common/compress.ts
@@ -43,7 +43,8 @@ export function compressTiles(tiles: Uint8Array): Uint8Array {
if (i === (tiles.length - 1)) {
write(count | 0b1000, bitsPerRun);
write(types.indexOf(value), bitsPerTile);
- } else {
+ }
+ else {
i++;
if (value === tiles[i]) {
@@ -56,7 +57,8 @@ export function compressTiles(tiles: Uint8Array): Uint8Array {
write(count, bitsPerRun);
write(types.indexOf(value), bitsPerTile);
- } else {
+ }
+ else {
let last = tiles[i];
let last2 = last;
let pushLast = true;
@@ -71,10 +73,12 @@ export function compressTiles(tiles: Uint8Array): Uint8Array {
count--;
pushLast = false;
break;
- } else if (count === 0b111) {
+ }
+ else if (count === 0b111) {
i -= 1;
break;
- } else {
+ }
+ else {
values.push(last);
count++;
last = last2;
@@ -110,7 +114,8 @@ export function decompressTiles(data: Uint8Array): Uint8Array {
if (types.length === 1) {
result.fill(types[0]);
- } else {
+ }
+ else {
const bitsPerTile = getBitsForNumber(typesCount);
const bitsPerRun = 4;
@@ -125,7 +130,8 @@ export function decompressTiles(data: Uint8Array): Uint8Array {
result[i] = types[entry];
i++;
}
- } else {
+ }
+ else {
const count = value & 0b0111;
for (let j = 0; j < count; j++) {
diff --git a/src/ts/common/compressPony.ts b/src/ts/common/compressPony.ts
index 1ca4985..689018f 100644
--- a/src/ts/common/compressPony.ts
+++ b/src/ts/common/compressPony.ts
@@ -307,13 +307,15 @@ const ALL_LOCKED = array(MAX_COLORS, true);
export function precompressSet(
set: SpriteSet | undefined, def: SetDefinition, customOutlines: boolean, defaultColor: T, addColor: (color: T) => number
): PrecompressedSet | undefined {
- if (!set)
+ if (!set) {
return undefined;
+ }
const type = clamp(toInt(set.type), 0, def.sets.length - 1);
- if (type === 0 && !def.preserveOnZero)
+ if (type === 0 && !def.preserveOnZero) {
return undefined;
+ }
const patterns = at(def.sets, type);
const pattern = clamp(toInt(set.pattern), 0, patterns ? patterns.length - 1 : 0);
@@ -321,8 +323,9 @@ export function precompressSet(
const colors = Math.max(getColorCount(sprite), def.minColors || 0);
/* istanbul ignore next */
- if (type === 0 && pattern === 0 && colors === 0)
+ if (type === 0 && pattern === 0 && colors === 0) {
return undefined;
+ }
const fillLocks = compressLockSet(set.lockFills, colors);
const fills = precompressColorSet(set.fills, colors, fillLocks, defaultColor, addColor);
@@ -355,7 +358,8 @@ function precompressFields, TValue, TResul
return trimRight(defs.map(def => {
if (def.dontSave || (def.omit && def.omit(data))) {
return defaultValue;
- } else {
+ }
+ else {
return encode(data[def.name], def);
}
}));
@@ -512,7 +516,8 @@ export function readSet(
const outlineLocks = customOutlines ? read(colors) : 0;
const outlines = customOutlines ? readTimes(read, colors - countBits(outlineLocks), colorBits) : [];
return { type, pattern, colors, fillLocks, fills, outlineLocks, outlines };
- } else {
+ }
+ else {
return undefined;
}
}
diff --git a/src/ts/common/encoders/expressionEncoder.ts b/src/ts/common/encoders/expressionEncoder.ts
index 7084ac5..5acee00 100644
--- a/src/ts/common/encoders/expressionEncoder.ts
+++ b/src/ts/common/encoders/expressionEncoder.ts
@@ -4,8 +4,9 @@ import { hasFlag } from '../utils';
export const EMPTY_EXPRESSION = 0x1fffffff;
export function encodeExpression(expression: Expression | undefined): number {
- if (!expression)
+ if (!expression) {
return EMPTY_EXPRESSION;
+ }
const { extra, rightIris, leftIris, right, left, muzzle } = expression;
@@ -16,8 +17,9 @@ export function encodeExpression(expression: Expression | undefined): number {
export function decodeExpression(value: number): Expression | undefined {
value = value >>> 0;
- if (value === EMPTY_EXPRESSION)
+ if (value === EMPTY_EXPRESSION) {
return undefined;
+ }
const muzzle = value & 0x1f;
const left = (value >> 5) & 0x1f;
diff --git a/src/ts/common/encoders/updateDecoder.ts b/src/ts/common/encoders/updateDecoder.ts
index 99f82e0..ddf2cbe 100644
--- a/src/ts/common/encoders/updateDecoder.ts
+++ b/src/ts/common/encoders/updateDecoder.ts
@@ -90,8 +90,9 @@ export function decodeUpdate(data: Uint8Array): DecodedRegionUpdate {
}
export function readOneUpdate(reader: BinaryReader): DecodedUpdate | undefined {
- if (reader.offset >= reader.view.byteLength)
+ if (reader.offset >= reader.view.byteLength) {
return undefined;
+ }
const flags = readUint16(reader);
diff --git a/src/ts/common/entities.ts b/src/ts/common/entities.ts
index 88a3706..35a4592 100644
--- a/src/ts/common/entities.ts
+++ b/src/ts/common/entities.ts
@@ -42,8 +42,9 @@ if (DEVELOPMENT) {
}
for (const { type } of entities) {
- if (type === 0)
+ if (type === 0) {
continue;
+ }
const entity = createAnEntity(type, 0, 0, 0, {}, mockPaletteManager, defaultWorldState);
const name = getEntityTypeName(type);
diff --git a/src/ts/common/entities/entitiesCore.ts b/src/ts/common/entities/entitiesCore.ts
index e869615..ded54e1 100644
--- a/src/ts/common/entities/entitiesCore.ts
+++ b/src/ts/common/entities/entitiesCore.ts
@@ -134,7 +134,8 @@ export function mixBounds(x: number, y: number, w: number, h: number): MixinEnti
export function mixServerFlags(flags: ServerFlags): MixinEntity {
if (SERVER) {
return base => base.serverFlags! |= flags;
- } else {
+ }
+ else {
return () => { };
}
}
@@ -180,7 +181,9 @@ export function doodadSet(name: string, sprite: PaletteRenderable, ox: number, o
// placeholder entity
-registerMix(n('null'), () => { throw new Error('Invalid type (0)'); });
+registerMix(n('null'), () => {
+ throw new Error('Invalid type (0)');
+});
// entities
diff --git a/src/ts/common/entityUtils.ts b/src/ts/common/entityUtils.ts
index 786820d..b94601e 100644
--- a/src/ts/common/entityUtils.ts
+++ b/src/ts/common/entityUtils.ts
@@ -53,9 +53,11 @@ export function getPonyChatHeight(pony: Pony) {
if (pony.animator.state === trotting) {
return baseHeight;
- } else if (pony.animator.state === flying || pony.animator.state === hovering) {
+ }
+ else if (pony.animator.state === flying || pony.animator.state === hovering) {
return baseHeight - 16;
- } else {
+ }
+ else {
const frame = getPonyAnimationFrame(state.animation, state.animationFrame, defaultBodyFrame);
const animation = state.headAnimation || defaultHeadAnimation;
const headFrame = getPonyAnimationFrame(animation, state.headAnimationFrame, defaultHeadFrame);
@@ -284,7 +286,8 @@ export function addOrRemoveFromEntityList(list: Entity[], entity: Entity, had: b
if (had !== has) {
if (has) {
pushUniq(list, entity);
- } else {
+ }
+ else {
removeItemFast(list, entity);
}
}
diff --git a/src/ts/common/expressionUtils.ts b/src/ts/common/expressionUtils.ts
index ec40035..7713cb4 100644
--- a/src/ts/common/expressionUtils.ts
+++ b/src/ts/common/expressionUtils.ts
@@ -180,13 +180,15 @@ const horizontalRegex = new RegExp(`^${any(horizontalEyesRight)}(//)?${any(horiz
function matchVertical(
text: string, regex: RegExp, flip: boolean, muzzleMap: Dict, eyesMap: Dict, command: boolean = false
): Expression | undefined {
- if (!command && /^([|]{2,}|BS|8x|x8|x-?x|\d+)$/i.test(text))
+ if (!command && /^([|]{2,}|BS|8x|x8|x-?x|\d+)$/i.test(text)) {
return undefined;
+ }
const match = regex.exec(text);
- if (!match)
+ if (!match) {
return undefined;
+ }
const eyesStr = flip ? match[3] : match[1];
const muzzleStr = flip ? match[1] : match[3];
@@ -288,11 +290,14 @@ const constants = createPlainMap<() => Expression | undefined>({
function matchOther(text: string): Expression | undefined {
if (/^A{5,}\.*$/.test(text)) {
return expression(Eye.Neutral, Eye.Neutral, Muzzle.ConcernedOpen3, Iris.Shocked, Iris.Shocked);
- } else if (/^a{5,}\.*$/.test(text)) {
+ }
+ else if (/^a{5,}\.*$/.test(text)) {
return expression(Eye.Neutral, Eye.Neutral, Muzzle.ConcernedOpen3);
- } else if (/^z{3,}\.*$/i.test(text)) {
+ }
+ else if (/^z{3,}\.*$/i.test(text)) {
return expression(Eye.Closed, Eye.Closed, Muzzle.Neutral);
- } else {
+ }
+ else {
return constants[text] && constants[text]();
}
}
diff --git a/src/ts/common/filterUtils.ts b/src/ts/common/filterUtils.ts
index 1f2d67a..50162fc 100644
--- a/src/ts/common/filterUtils.ts
+++ b/src/ts/common/filterUtils.ts
@@ -14,7 +14,8 @@ export const urlRegexTexts = [
export function trimRepeatedLetters(test: string): string {
if (test.length > MAX_REPEATS && (/^.?(.)\1+$/u.test(test) || /^.?(..)\1+$/u.test(test))) {
return test.substr(0, MAX_REPEATS) + '…';
- } else {
+ }
+ else {
return test;
}
}
diff --git a/src/ts/common/interfaces.ts b/src/ts/common/interfaces.ts
index f4b1286..7d82928 100644
--- a/src/ts/common/interfaces.ts
+++ b/src/ts/common/interfaces.ts
@@ -144,7 +144,9 @@ export const enum EntityState {
Editable = 8,
// pony
+ // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values
HeadTurned = 4,
+ // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values
Magic = 8,
// CanFly ?, // Or in flags ?
@@ -203,7 +205,8 @@ export const enum MessageType {
export function toMessageType(type: MessageType) {
if (type === MessageType.WhisperAnnouncement) {
return MessageType.WhisperToAnnouncement;
- } else {
+ }
+ else {
return MessageType.WhisperTo;
}
}
@@ -1274,11 +1277,9 @@ export interface PalettePonyInfo extends PonyInfoBase
magicColorValue: number;
}
-export interface PonyInfo extends PonyInfoBase> {
-}
+export type PonyInfo = PonyInfoBase>;
-export interface PonyInfoNumber extends PonyInfoBase> {
-}
+export type PonyInfoNumber = PonyInfoBase>;
export interface ColorExtra {
color: Sprite;
@@ -1742,7 +1743,7 @@ export interface EntityDescriptor {
create: CreateEntity;
}
-export type EntityOptions = PonyEntityOptions | SpiderEntityOptions | SignEntityOptions | {};
+export type EntityOptions = PonyEntityOptions | SpiderEntityOptions | SignEntityOptions | object;
export type EntityOrPonyOptions = Partial & EntityOptions;
export interface EntityWorldState {
@@ -1826,7 +1827,8 @@ export let counterNow: () => number;
if (typeof window !== 'undefined') {
counterNow = performance.now;
-} else {
+}
+else {
const hrtime = process.hrtime;
const getNanoSeconds = () => {
const hr = hrtime();
diff --git a/src/ts/common/mat2d.ts b/src/ts/common/mat2d.ts
index 4f46fd1..e517118 100644
--- a/src/ts/common/mat2d.ts
+++ b/src/ts/common/mat2d.ts
@@ -102,7 +102,8 @@ export function skewTransform(base: Matrix2D | undefined, skew: number, ox: numb
translateMat2D(tempMatrix, tempMatrix, ox + x, oy + y);
skewY(tempMatrix, tempMatrix, skew);
translateMat2D(tempMatrix, tempMatrix, -ox, -oy);
- } else {
+ }
+ else {
translateMat2D(tempMatrix, tempMatrix, x, y);
}
diff --git a/src/ts/common/mixins.ts b/src/ts/common/mixins.ts
index 437a40a..bbc132f 100644
--- a/src/ts/common/mixins.ts
+++ b/src/ts/common/mixins.ts
@@ -50,11 +50,14 @@ function getBounds(sprite: Sprite | undefined, ox: number, oy: number): Rect {
export function getRenderableBounds({ color, shadow }: Renderable, dx: number, dy: number): Rect {
if (color && shadow) {
return addRects(getBounds(color, -dx, -dy), getBounds(shadow, -dx, -dy));
- } else if (color) {
+ }
+ else if (color) {
return getBounds(color, -dx, -dy);
- } else if (shadow) {
+ }
+ else if (shadow) {
return getBounds(shadow, -dx, -dy);
- } else {
+ }
+ else {
return rect(0, 0, 0, 0);
}
}
@@ -288,15 +291,20 @@ export function mixAnimation(
}
return at(animations[animation], frameNumber) || 0;
- } else {
+ }
+ else {
return repeat ? (frameNumber % anim.frames.length) : Math.min(frameNumber, anim.frames.length - 1);
}
};
base.bounds = bounds;
base.palettes = [];
- defaultPalette && base.palettes.push(defaultPalette);
- palette && base.palettes.push(palette);
+ if (defaultPalette) {
+ base.palettes.push(defaultPalette);
+ }
+ if (palette) {
+ base.palettes.push(palette);
+ }
base.update = function (delta: number) {
time += delta;
@@ -313,7 +321,8 @@ export function mixAnimation(
if (lastFrame !== frameNumber) {
lastFrame = frameNumber;
return true;
- } else {
+ }
+ else {
return false;
}
};
@@ -332,8 +341,12 @@ export function mixAnimation(
}
batch.translate(-dx, -dy);
- anim.shadow && batch.drawSprite(anim.shadow, options.shadowColor, defaultPalette, 0, 0);
- frameSprite && batch.drawSprite(frameSprite, color, palette, 0, 0);
+ if (anim.shadow) {
+ batch.drawSprite(anim.shadow, options.shadowColor, defaultPalette, 0, 0);
+ }
+ if (frameSprite) {
+ batch.drawSprite(frameSprite, color, palette, 0, 0);
+ }
batch.restore();
};
@@ -374,8 +387,12 @@ export function mixDrawWindow(
const defaultPalette = sprite.shadow && createPalette(sprites.defaultPalette);
const palette = createPalette(att(sprite.palettes, paletteIndex));
base.palettes = [];
- defaultPalette && base.palettes.push(defaultPalette);
- palette && base.palettes.push(palette);
+ if (defaultPalette) {
+ base.palettes.push(defaultPalette);
+ }
+ if (palette) {
+ base.palettes.push(palette);
+ }
base.draw = function (batch, options) {
const baseX = toScreenX(this.x + (this.ox || 0));
@@ -407,8 +424,12 @@ export function mixDraw(sprite: PaletteRenderable, dx: number, dy: number, palet
const defaultPalette = sprite.shadow && createPalette(sprites.defaultPalette);
const palette = createPalette(att(sprite.palettes, paletteIndex));
base.palettes = [];
- defaultPalette && base.palettes.push(defaultPalette);
- palette && base.palettes.push(palette);
+ if (defaultPalette) {
+ base.palettes.push(defaultPalette);
+ }
+ if (palette) {
+ base.palettes.push(palette);
+ }
base.draw = function (batch: PaletteSpriteBatch, options: DrawOptions) {
const x = toScreenX(this.x + (this.ox || 0)) - dx;
@@ -506,8 +527,12 @@ export function mixDrawSeasonal(setup: MixDrawSeasonal): MixinEntity {
defaultPalette = sprite.shadow && createPalette(sprites.defaultPalette);
palette = createPalette(att(sprite.palettes, paletteIndex));
base.palettes = [];
- defaultPalette && base.palettes.push(defaultPalette);
- palette && base.palettes.push(palette);
+ if (defaultPalette) {
+ base.palettes.push(defaultPalette);
+ }
+ if (palette) {
+ base.palettes.push(palette);
+ }
};
setupSeason(worldState.season);
@@ -597,8 +622,9 @@ export function mixDrawDirectionSign(): MixinEntity {
base.bounds = rect(-20, -boundsH, 40, boundsH);
base.options = options;
- if (SERVER && !TESTS)
+ if (SERVER && !TESTS) {
return;
+ }
const {
shadowUp, shadowDown, spriteUp, spriteDown, upDX, upDY, downDX, downDY,
@@ -613,18 +639,30 @@ export function mixDrawDirectionSign(): MixinEntity {
const defaultPalette = pole.sprite.shadow && createPalette(sprites.defaultPalette);
const palette = createPalette(att(pole.sprite.palettes, 0));
base.palettes = [];
- defaultPalette && base.palettes.push(defaultPalette);
- palette && base.palettes.push(palette);
+ if (defaultPalette) {
+ base.palettes.push(defaultPalette);
+ }
+ if (palette) {
+ base.palettes.push(palette);
+ }
base.draw = function (batch, options) {
const x = toScreenX(this.x);
const y = toScreenYWithZ(this.y, this.z);
batch.drawSprite(pole.sprite.shadow, options.shadowColor, defaultPalette, x + poleDX, y + pole.dy);
- leftShadow && batch.drawSprite(shadowLeft, options.shadowColor, defaultPalette, x - 18, y - 1);
- rightShadow && batch.drawSprite(shadowRight, options.shadowColor, defaultPalette, x + 4, y - 1);
- upShadow && batch.drawSprite(shadowUp, options.shadowColor, defaultPalette, x + shadowUpDX, y + shadowUpDY);
- downShadow && batch.drawSprite(shadowDown, options.shadowColor, defaultPalette, x + shadowDownDX, y + shadowDownDY);
+ if (leftShadow) {
+ batch.drawSprite(shadowLeft, options.shadowColor, defaultPalette, x - 18, y - 1);
+ }
+ if (rightShadow) {
+ batch.drawSprite(shadowRight, options.shadowColor, defaultPalette, x + 4, y - 1);
+ }
+ if (upShadow) {
+ batch.drawSprite(shadowUp, options.shadowColor, defaultPalette, x + shadowUpDX, y + shadowUpDY);
+ }
+ if (downShadow) {
+ batch.drawSprite(shadowDown, options.shadowColor, defaultPalette, x + shadowDownDX, y + shadowDownDY);
+ }
for (let i = n.length - 1; i >= 0; i--) {
if (n[i] !== -1) {
@@ -637,14 +675,18 @@ export function mixDrawDirectionSign(): MixinEntity {
for (let i = 0; i < w.length; i++) {
if (w[i] !== -1) {
const sprite = leftSprites[w[i]];
- sprite && batch.drawSprite(sprite, WHITE, palette, x + leftDX, y + pole.dy + plateDY + i * leftRightStep);
+ if (sprite) {
+ batch.drawSprite(sprite, WHITE, palette, x + leftDX, y + pole.dy + plateDY + i * leftRightStep);
+ }
}
}
for (let i = 0; i < e.length; i++) {
if (e[i] !== -1) {
const sprite = rightSprites[e[i]];
- sprite && batch.drawSprite(rightSprites[e[i]], WHITE, palette, x + rightDX, y + pole.dy + plateDY + i * leftRightStep);
+ if (sprite) {
+ batch.drawSprite(rightSprites[e[i]], WHITE, palette, x + rightDX, y + pole.dy + plateDY + i * leftRightStep);
+ }
}
}
@@ -668,8 +710,9 @@ export function mixLight(color: number, dx: number, dy: number, w: number, h: nu
const adjustedScale = base.lightScale * base.lightScaleAdjust * LIGHT_VOLUME_SCALE;
base.lightBounds = rect(-(dx + w / 2), -(dy + h / 2), w * adjustedScale, h * adjustedScale);
base.drawLight = function (batch: SpriteBatch) {
- if (!this.lightOn)
+ if (!this.lightOn) {
return;
+ }
const x = toScreenX(this.x);
const y = toScreenYWithZ(this.y, this.z);
@@ -692,8 +735,9 @@ export function mixLightSprite(sprite: Sprite, color: number, dx: number, dy: nu
base.lightSpriteColor = color;
base.lightSpriteBounds = getBounds(sprite, -dx, -dy);
base.drawLightSprite = function (batch: SpriteBatch) {
- if (!this.lightSpriteOn)
+ if (!this.lightSpriteOn) {
return;
+ }
const x = toScreenX(this.x) - this.lightSpriteX!;
const y = toScreenYWithZ(this.y, this.z) - this.lightSpriteY!;
@@ -711,8 +755,9 @@ export function mixDrawRain(): MixinEntity {
return base => {
base.bounds = bounds;
- if (SERVER && !TESTS)
+ if (SERVER && !TESTS) {
return;
+ }
let time = 0;
const palette = createPalette(sprites.defaultPalette);
@@ -747,7 +792,9 @@ export function mixDrawShadow(sprite: PaletteRenderable, dx: number, dy: number,
const x = toScreenX(this.x + (this.ox || 0)) - dx;
const y = toScreenYWithZ(this.y + (this.oy || 0), this.z) - dy;
const color = shadowColor === undefined ? options.shadowColor : shadowColor;
- sprite.shadow && batch.drawSprite(sprite.shadow, color, defaultPalette, x, y);
+ if (sprite.shadow) {
+ batch.drawSprite(sprite.shadow, color, defaultPalette, x, y);
+ }
};
}
};
@@ -776,22 +823,29 @@ export function mixDrawWall(
return base => {
base.bounds = fullBounds; // fullWalls ? fullBounds : halfBounds
- if (SERVER && !TESTS)
+ if (SERVER && !TESTS) {
return;
+ }
const fullPalette = createPalette(att(full.palettes, 0));
const halfPalette = createPalette(att(half.palettes, 0));
base.palettes = [];
- fullPalette && base.palettes.push(fullPalette);
- halfPalette && base.palettes.push(halfPalette);
+ if (fullPalette) {
+ base.palettes.push(fullPalette);
+ }
+ if (halfPalette) {
+ base.palettes.push(halfPalette);
+ }
base.draw = function (batch: PaletteSpriteBatch) {
const sprite = fullWalls ? full : half;
const palette = fullWalls ? fullPalette : halfPalette;
const x = toScreenX(this.x) - dx;
const y = toScreenYWithZ(this.y, this.z) - (fullWalls ? dy : dy2);
- sprite.color && batch.drawSprite(sprite.color, WHITE, palette, x, y);
+ if (sprite.color) {
+ batch.drawSprite(sprite.color, WHITE, palette, x, y);
+ }
};
};
}
@@ -803,8 +857,9 @@ export function mixDrawSpider(
const spriteColor = sprite.color;
const baseBounds = getRenderableBounds(sprite, dx, dy);
- if (!spriteColor)
+ if (!spriteColor) {
throw new Error('Missing sprite');
+ }
return base => {
const { height, time } = base.options as { height: number; time: number; };
@@ -813,8 +868,9 @@ export function mixDrawSpider(
bounds.h += height;
base.bounds = bounds;
- if (SERVER && !TESTS)
+ if (SERVER && !TESTS) {
return;
+ }
const palette = createPalette(sprite.palettes && sprite.palettes[0]);
base.palettes = [palette];
diff --git a/src/ts/common/movementUtils.ts b/src/ts/common/movementUtils.ts
index e31097d..c6b2f07 100644
--- a/src/ts/common/movementUtils.ts
+++ b/src/ts/common/movementUtils.ts
@@ -36,9 +36,11 @@ export function flagsToSpeed(flags: EntityState): number {
if (state === EntityState.PonyTrotting) {
return PONY_SPEED_TROT;
- } else if (state === EntityState.PonyWalking) {
+ }
+ else if (state === EntityState.PonyWalking) {
return PONY_SPEED_WALK;
- } else {
+ }
+ else {
return 0;
}
}
diff --git a/src/ts/common/ponyAnimations.ts b/src/ts/common/ponyAnimations.ts
index a84e00f..fe4310d 100644
--- a/src/ts/common/ponyAnimations.ts
+++ b/src/ts/common/ponyAnimations.ts
@@ -1,3 +1,4 @@
+/* eslint-disable camelcase */
import { BodyAnimation, BodyAnimationFrame, HeadAnimation, HeadAnimationFrame, BodyShadow, HeadAnimationProperties } from './interfaces';
import { repeat, flatten } from './utils';
diff --git a/src/ts/common/ponyInfo.ts b/src/ts/common/ponyInfo.ts
index 996f190..fe639ed 100644
--- a/src/ts/common/ponyInfo.ts
+++ b/src/ts/common/ponyInfo.ts
@@ -37,8 +37,9 @@ export const mockPaletteManager: PaletteManager = {
};
export function spriteSet(type: number, lockFirstFill = true, fill = 'ffd700', otherFills = FILLS): SpriteSet {
- if (otherFills.length !== (MAX_COLORS - 1))
+ if (otherFills.length !== (MAX_COLORS - 1)) {
throw new Error('Invalid fills count');
+ }
const fills = [fill, ...otherFills];
const outlines = fills.map(fillToOutline);
@@ -147,13 +148,15 @@ export function syncLockedSpriteSet(
set: SpriteSet | undefined, customOutlines: boolean, fillToOutline: FillToOutline, baseFill?: T,
baseOutline?: T
) {
- if (set === undefined)
+ if (set === undefined) {
return;
+ }
const fills = set.fills;
- if (!fills)
+ if (!fills) {
return;
+ }
const lockFills = set.lockFills;
@@ -177,7 +180,8 @@ export function syncLockedSpriteSet(
if (lockOutlines[i]) {
if (i === 0 && baseOutline && lockFills && lockFills[i]) {
outlines[i] = baseOutline;
- } else {
+ }
+ else {
outlines[i] = fillToOutline(fills[i]);
}
}
@@ -202,7 +206,8 @@ function syncLockedSpritesSet2(
if (locked) {
if (baseOutlines[i] && set.lockFills && set.lockFills[i]) {
set.outlines![i] = baseOutlines[i];
- } else {
+ }
+ else {
set.outlines![i] = fillToOutline(set.fills![i]);
}
}
@@ -356,7 +361,8 @@ function getColorsGeneric(
if (darken) {
colors[i * 2 + 1] = outlines[i] ? colorToHexRGB(darkenForOutline(parseColorFast(outlines[i]!))) : defaultColor;
- } else {
+ }
+ else {
colors[i * 2 + 1] = outlines[i] || defaultColor;
}
}
@@ -398,7 +404,8 @@ export const getColorsForSetNumber: GetColorsForSet = (set, length, dark
if (darken) {
result[((i << 1) + 2) | 0] = i < outlines.length ? darkenForOutline(outlines[i] || BLACK) : BLACK;
- } else {
+ }
+ else {
result[((i << 1) + 2) | 0] = i < outlines.length ? (outlines[i] || BLACK) : BLACK;
}
}
@@ -432,8 +439,9 @@ function createCMPalette(
): Palette | undefined {
const size = CM_SIZE * CM_SIZE;
- if (cm === undefined || cm.length === 0 || cm.length > size)
+ if (cm === undefined || cm.length === 0 || cm.length > size) {
return undefined;
+ }
const result = new Uint32Array(size);
@@ -568,7 +576,8 @@ export function releasePalettes(info: PalettePonyInfo): void {
if ('refs' in value) {
const palette = value as Palette;
releasePalette(palette);
- } else if ('palette' in value) {
+ }
+ else if ('palette' in value) {
const set = value as PaletteSpriteSet;
releasePalette(set.palette);
releasePalette(set.extraPalette);
diff --git a/src/ts/common/ponyUtils.ts b/src/ts/common/ponyUtils.ts
index 5a81c90..a2d40b8 100644
--- a/src/ts/common/ponyUtils.ts
+++ b/src/ts/common/ponyUtils.ts
@@ -72,30 +72,49 @@ export function canMagic(info: PonyInfoBase) {
export function flipIris(iris: Iris): Iris {
if (iris === Iris.Left || iris === Iris.UpLeft) {
return iris + 1;
- } else if (iris === Iris.Right || iris === Iris.UpRight) {
+ }
+ else if (iris === Iris.Right || iris === Iris.UpRight) {
return iris - 1;
- } else {
+ }
+ else {
return iris;
}
}
export function flipFaceAccessoryType(type: number) {
- if (type === 6) return 7;
- if (type === 7) return 6;
+ if (type === 6) {
+ return 7;
+ }
+ if (type === 7) {
+ return 6;
+ }
- if (type === 9) return 10;
- if (type === 10) return 9;
+ if (type === 9) {
+ return 10;
+ }
+ if (type === 10) {
+ return 9;
+ }
return type;
}
export function flipFaceAccessoryPattern(type: number, pattern: number) {
if (type === 2) { // dark glasses
- if (pattern === 1) return 2;
- if (pattern === 2) return 1;
- } else if (type === 11) { // large dark glasses
- if (pattern === 1) return 2;
- if (pattern === 2) return 1;
+ if (pattern === 1) {
+ return 2;
+ }
+ if (pattern === 2) {
+ return 1;
+ }
+ }
+ else if (type === 11) { // large dark glasses
+ if (pattern === 1) {
+ return 2;
+ }
+ if (pattern === 2) {
+ return 1;
+ }
}
return pattern;
diff --git a/src/ts/common/region.ts b/src/ts/common/region.ts
index ab6cad7..4a9a2f9 100644
--- a/src/ts/common/region.ts
+++ b/src/ts/common/region.ts
@@ -131,8 +131,9 @@ export function generateRegionCollider(region: Reg
for (let rx = minX; rx <= maxX; rx++) {
const r = getRegion(map, rx, ry);
- if (r === undefined)
+ if (r === undefined) {
continue;
+ }
for (const entity of r.colliders) {
const entityX = toScreenX(entity.x - baseX) | 0;
@@ -171,7 +172,8 @@ export function generateRegionCollider(region: Reg
}
}
}
- } else {
+ }
+ else {
for (const pc of ponyColliders) {
const tx0 = (baseX0 + pc.x) | 0;
const ty0 = (baseY0 + pc.y) | 0;
@@ -210,7 +212,8 @@ export function getRegionGlobal(map: IMap, x: number, y: number): T {
export function getRegion(map: IMap, x: number, y: number): T {
if (x < 0 || y < 0 || x >= map.regionsX || y >= map.regionsY) {
throw new Error(`Invalid region coords (${x}, ${y})`);
- } else {
+ }
+ else {
return map.regions[((x | 0) + (y | 0) * map.regionsX) | 0];
}
}
@@ -218,7 +221,8 @@ export function getRegion(map: IMap, x: number, y: number): T {
export function getRegionUnsafe(map: IMap, x: number, y: number): T | undefined {
if (x < 0 || y < 0 || x >= map.regionsX || y >= map.regionsY) {
return undefined;
- } else {
+ }
+ else {
return map.regions[((x | 0) + (y | 0) * map.regionsX) | 0];
}
}
diff --git a/src/ts/common/rollbar.ts b/src/ts/common/rollbar.ts
index 94d8f3c..45c769b 100644
--- a/src/ts/common/rollbar.ts
+++ b/src/ts/common/rollbar.ts
@@ -80,9 +80,11 @@ export interface Person {
function getLabel(arg: LogArgument | undefined) {
if (typeof arg === 'string') {
return arg;
- } else if (arg && 'message' in arg) {
+ }
+ else if (arg && 'message' in arg) {
return (arg as any).message + (arg.stack || '');
- } else {
+ }
+ else {
return arg ? arg.toString() : '';
}
}
diff --git a/src/ts/common/security.ts b/src/ts/common/security.ts
index 58708ae..f7c72a3 100644
--- a/src/ts/common/security.ts
+++ b/src/ts/common/security.ts
@@ -17,10 +17,12 @@ function createRegExpFromList(list: string | undefined, wholeWords = false): Reg
if (wholeWords) {
return new RegExp(`\\b(${combined})\\b`, 'ui');
- } else {
+ }
+ else {
return new RegExp(combined, 'ui');
}
- } else {
+ }
+ else {
return undefined;
}
}
@@ -47,8 +49,9 @@ export const createIsSuspiciousMessage = (general: GeneralSettings) => {
const testWholeInstant = createCachedTest(true);
return (text: string, { filterSwears }: GameServerSettings): Suspicious => {
- if (test(general.suspiciousMessages, text))
+ if (test(general.suspiciousMessages, text)) {
return Suspicious.Very;
+ }
if (filterSwears) {
if (testSafeInstant(general.suspiciousSafeInstantMessages, text) ||
@@ -85,7 +88,8 @@ export const createIsSuspiciousAuth =
function tryParseJSON(value: string): any {
try {
return JSON.parse(value);
- } catch {
+ }
+ catch {
return undefined;
}
}
@@ -108,7 +112,8 @@ function matchPony(info: PonyInfoNumber, match: Partial) {
function comparePonyInfoFields(a: any, b: any): boolean {
if (typeof a === 'number' && typeof b === 'string') {
return a === parseColorFast(b);
- } else {
+ }
+ else {
return undefined as any;
}
}
diff --git a/src/ts/common/spriteUtils.ts b/src/ts/common/spriteUtils.ts
index 7bf703a..2725d15 100644
--- a/src/ts/common/spriteUtils.ts
+++ b/src/ts/common/spriteUtils.ts
@@ -10,7 +10,9 @@ export function addTitles(sprites: ColorExtraSets, titles: string[]): ColorExtra
}
export function addLabels(sprites: ColorExtraSets, labels: string[]) {
- sprites && sprites.forEach((s, i) => s && s[0] ? s[0]!.label = labels[i] : undefined);
+ if (sprites) {
+ sprites.forEach((s, i) => s && s[0] ? s[0]!.label = labels[i] : undefined);
+ }
return sprites;
}
diff --git a/src/ts/common/stringUtils.ts b/src/ts/common/stringUtils.ts
index c63a498..7bae56f 100644
--- a/src/ts/common/stringUtils.ts
+++ b/src/ts/common/stringUtils.ts
@@ -213,7 +213,8 @@ export function filterString(value: string | undefined, filter: (code: number) =
code = fromSurrogate(code, extra);
i++;
size++;
- } else {
+ }
+ else {
invalidSurrogate = true;
}
}
diff --git a/src/ts/common/swears.ts b/src/ts/common/swears.ts
index 5ef3c43..8168b7a 100644
--- a/src/ts/common/swears.ts
+++ b/src/ts/common/swears.ts
@@ -1478,7 +1478,8 @@ const ascii = createBadWords(true);
function tryRegex(value: string, flags: string) {
try {
return new RegExp(value, flags);
- } catch (e) {
+ }
+ catch (e) {
console.error(e);
return new RegExp(/(?!.*)/);
}
diff --git a/src/ts/common/tags.ts b/src/ts/common/tags.ts
index 208627f..6aff6be 100644
--- a/src/ts/common/tags.ts
+++ b/src/ts/common/tags.ts
@@ -42,9 +42,11 @@ export function getTagPalette(tag: CharacterTag, palettes: FontPalettes) {
export function canUseTag(account: AccountRoles, tag: string) {
if (tag === 'mod') {
return hasRole(account, 'mod');
- } else if (tag === 'dev' || /^dev:/.test(tag)) {
+ }
+ else if (tag === 'dev' || /^dev:/.test(tag)) {
return hasRole(account, 'dev');
- } else {
+ }
+ else {
return false;
}
}
diff --git a/src/ts/common/tileUtils.ts b/src/ts/common/tileUtils.ts
index f60d1cb..caf65a4 100644
--- a/src/ts/common/tileUtils.ts
+++ b/src/ts/common/tileUtils.ts
@@ -423,7 +423,8 @@ function getTileNormal(
) {
if (x >= 0 && y >= 0 && x < REGION_SIZE && y < REGION_SIZE) {
return normalizeTile(tiles[x | (y << 3)], base);
- } else {
+ }
+ else {
const mapX = clamp(x + baseX, 0, map.width - 1);
const mapY = clamp(y + baseY, 0, map.height - 1);
const region = getRegionGlobal(map, mapX, mapY);
@@ -432,7 +433,8 @@ function getTileNormal(
const regionX = mapX - region.x * REGION_SIZE;
const regionY = mapY - region.y * REGION_SIZE;
return normalizeTile(region.tiles[regionX | (regionY << 3)], base);
- } else {
+ }
+ else {
return TileType.None;
}
}
@@ -446,7 +448,8 @@ function getTileIndex(region: Region, index: number, x: number, y: number, map:
if (type === TileType.Dirt || type === TileType.ElevatedDirt) {
baseTileIndex = 47;
- } else if (type !== TileType.None) {
+ }
+ else if (type !== TileType.None) {
let topLeft = 0, top = 0, topRight = 0, left = 0, right = 0, bottomLeft = 0, bottom = 0, bottomRight = 0;
if (x > 1 && y > 1 && x < (REGION_SIZE - 1) && y < (REGION_SIZE - 1)) {
@@ -458,7 +461,8 @@ function getTileIndex(region: Region, index: number, x: number, y: number, map:
bottomLeft = normalizeTile(tiles[(x - 1) | (y + 1) << 3], type);
bottom = normalizeTile(tiles[(x) | (y + 1) << 3], type);
bottomRight = normalizeTile(tiles[(x + 1) | (y + 1) << 3], type);
- } else {
+ }
+ else {
const baseX = (region.x * REGION_SIZE) | 0;
const baseY = (region.y * REGION_SIZE) | 0;
topLeft = getTileNormal(tiles, baseX, baseY, x - 1, y - 1, map, type);
@@ -508,8 +512,9 @@ function valueToHeight(value: number, bottom: number, top: number) {
}
export function initializeTileHeightmaps() {
- if (tileHeightMapsInitialized)
+ if (tileHeightMapsInitialized) {
return;
+ }
function createTileHeightMaps(sprite: Sprite, tileType: TileTypeNumber, bottom: number, top: number) {
const sheetData = sprites.normalSpriteSheet.data!;
@@ -591,11 +596,14 @@ export function getTileHeight(
return heightMaps[tx + ty * tileWidth];
}
}
- } else if (typeNumber === TileTypeNumber.SnowOnIce) {
+ }
+ else if (typeNumber === TileTypeNumber.SnowOnIce) {
return -0.2;
- } else if (tileType === TileType.ElevatedDirt) {
+ }
+ else if (tileType === TileType.ElevatedDirt) {
return 0.5;
- } else if (typeNumber === TileTypeNumber.Boat) {
+ }
+ else if (typeNumber === TileTypeNumber.Boat) {
const frame = ((gameTime / 1000) * WATER_FPS) | 0;
return waterHeight[frame % waterHeight.length];
}
@@ -610,7 +618,8 @@ export function getTile(map: IMap, x: number, y: number): TileType {
const regionX = Math.floor(x - region.x * REGION_SIZE);
const regionY = Math.floor(y - region.y * REGION_SIZE);
return getRegionTile(region, regionX, regionY);
- } else {
+ }
+ else {
return TileType.None;
}
}
@@ -618,8 +627,9 @@ export function getTile(map: IMap, x: number, y: number): TileType {
export function setTile(map: WorldMap, worldX: number, worldY: number, type: TileType) {
const region = getRegionGlobal(map, worldX, worldY);
- if (!region)
+ if (!region) {
return;
+ }
const x = Math.floor(worldX - region.x * REGION_SIZE);
const y = Math.floor(worldY - region.y * REGION_SIZE);
diff --git a/src/ts/common/timing.ts b/src/ts/common/timing.ts
index 9d45e65..7dc4205 100644
--- a/src/ts/common/timing.ts
+++ b/src/ts/common/timing.ts
@@ -31,7 +31,8 @@ export function timeStart(name: string) {
entry.time = performance.now();
entry.name = name;
entriesCount++;
- } else {
+ }
+ else {
console.warn(`exceeded timing entry limit`);
}
}
@@ -44,7 +45,8 @@ export function timeEnd() {
entry.time = performance.now();
entry.name = undefined;
entriesCount++;
- } else {
+ }
+ else {
console.warn(`exceeded timing entry limit`);
}
}
@@ -70,7 +72,8 @@ export function timingCollate(): TimingResult[] {
if (entry.name !== undefined) {
startStack.push({ ...entry, excludedTime: 0 });
- } else {
+ }
+ else {
const start = startStack.pop()!;
const name = start.name!;
const time = entry.time - start.time;
diff --git a/src/ts/common/utils.ts b/src/ts/common/utils.ts
index 76b8f8b..d841140 100644
--- a/src/ts/common/utils.ts
+++ b/src/ts/common/utils.ts
@@ -52,11 +52,14 @@ export function formatDuration(duration: number) {
if (d > 0) {
return h ? `${d}d ${h}h` : `${d}d`;
- } else if (h > 0) {
+ }
+ else if (h > 0) {
return m ? `${h}h ${m}m` : `${h}h`;
- } else if (m > 0) {
+ }
+ else if (m > 0) {
return s ? `${m}m ${s}s` : `${m}m`;
- } else {
+ }
+ else {
return `${s}s`;
}
}
@@ -93,7 +96,8 @@ export function createValidBirthDate(day: number, month: number, year: number) {
year >= (currentYear - 120) && year < currentYear
) {
return date;
- } else {
+ }
+ else {
return undefined;
}
}
@@ -165,7 +169,9 @@ export function toInt(value: any): number {
}
export function dispose(obj: T | undefined): undefined {
- obj && obj.dispose();
+ if (obj) {
+ obj.dispose();
+ }
return undefined;
}
@@ -267,7 +273,8 @@ export function removeItem(items: T[], item: T): boolean {
if (index !== -1) {
items.splice(index, 1);
return true;
- } else {
+ }
+ else {
return false;
}
}
@@ -279,7 +286,8 @@ export function removeItemFast(items: T[], item: T): boolean {
items[index] = items[items.length - 1];
items.pop();
return true;
- } else {
+ }
+ else {
return false;
}
}
@@ -291,7 +299,8 @@ export function removeById(items: T[], id: U): T | undef
const item = items[index];
items.splice(index, 1);
return item;
- } else {
+ }
+ else {
return undefined;
}
}
@@ -316,7 +325,8 @@ export function pushUniq(array: T[], item: T) {
if (index === -1) {
array.push(item);
return array.length;
- } else {
+ }
+ else {
return index + 1;
}
}
@@ -433,13 +443,17 @@ export function createError(status: number, data: string | { error: string; }):
return new Error(PROTECTION_ERROR);
// } else if (status === 400) {
// return new Error('Bad Request');
- } else if (status === 403) {
+ }
+ else if (status === 403) {
return new Error(ACCESS_ERROR);
- } else if (status === 404) {
+ }
+ else if (status === 404) {
return new Error(NOT_FOUND_ERROR);
- } else if (typeof data === 'string') {
+ }
+ else if (typeof data === 'string') {
return new Error(data || OFFLINE_ERROR);
- } else {
+ }
+ else {
return new Error((data && data.error) || OFFLINE_ERROR);
}
}
@@ -455,7 +469,8 @@ export function observableToPromise(observable: Observable) {
try {
error = JSON.parse(error);
- } catch { }
+ }
+ catch { }
const e: RequestError = createError(status || 0, error);
e.status = status;
@@ -518,7 +533,9 @@ export function processCommand(text: string) {
}
export function parseSeason(value?: string): Season | undefined {
- if (!value) return undefined;
+ if (!value) {
+ return undefined;
+ }
switch (value.toLowerCase()) {
case 'spring': return Season.Spring;
case 'summer': return Season.Summer;
@@ -529,7 +546,9 @@ export function parseSeason(value?: string): Season | undefined {
}
export function parseHoliday(value?: string): Holiday | undefined {
- if (!value) return undefined;
+ if (!value) {
+ return undefined;
+ }
switch (value.toLowerCase()) {
case 'none': return Holiday.None;
case 'halloween': return Holiday.Halloween;
diff --git a/src/ts/components/admin/admin-account-details/admin-account-details.ts b/src/ts/components/admin/admin-account-details/admin-account-details.ts
index 0e723cd..7f86c89 100644
--- a/src/ts/components/admin/admin-account-details/admin-account-details.ts
+++ b/src/ts/components/admin/admin-account-details/admin-account-details.ts
@@ -145,9 +145,15 @@ export class AdminAccountDetails implements OnInit, OnDestroy {
}
ngOnDestroy() {
this.model.updated = () => { };
- this.authsSubscription && this.authsSubscription.unsubscribe();
- this.accountSubscription && this.accountSubscription.unsubscribe();
- this.originsSubscription && this.originsSubscription.unsubscribe();
+ if (this.authsSubscription) {
+ this.authsSubscription.unsubscribe();
+ }
+ if (this.accountSubscription) {
+ this.accountSubscription.unsubscribe();
+ }
+ if (this.originsSubscription) {
+ this.originsSubscription.unsubscribe();
+ }
}
refresh() {
const account = this.account;
@@ -160,10 +166,14 @@ export class AdminAccountDetails implements OnInit, OnDestroy {
this.accountObject = undefined;
this.loadingDuplicates = false;
- this.authsSubscription && this.authsSubscription.unsubscribe();
+ if (this.authsSubscription) {
+ this.authsSubscription.unsubscribe();
+ }
this.authsSubscription = undefined;
- this.originsSubscription && this.originsSubscription.unsubscribe();
+ if (this.originsSubscription) {
+ this.originsSubscription.unsubscribe();
+ }
this.originsSubscription = undefined;
this.auths = [];
@@ -201,7 +211,8 @@ export class AdminAccountDetails implements OnInit, OnDestroy {
this.originsSubscription = this.model.accountOrigins
.subscribe(account._id, origins => this.origins = origins || []);
- } else {
+ }
+ else {
this.duplicates = [];
this.ignores = [];
this.ignoredBy = [];
@@ -468,7 +479,8 @@ export class AdminAccountDetails implements OnInit, OnDestroy {
if (merge.data) {
return `${mergeInfo('ACCOUNT', merge.data.account)}\n\n${mergeInfo('MERGED', merge.data.merge)}`;
- } else {
+ }
+ else {
return '';
}
}
@@ -552,7 +564,9 @@ export class AdminAccountDetails implements OnInit, OnDestroy {
}
private update() {
if (this.id) {
- this.accountSubscription && this.accountSubscription.unsubscribe();
+ if (this.accountSubscription) {
+ this.accountSubscription.unsubscribe();
+ }
this.accountSubscription = this.id ? this.model.accounts.subscribe(this.id, a => this.setAccount(a)) : undefined;
this.events = this.model.events
diff --git a/src/ts/components/admin/admin-other/admin-other.ts b/src/ts/components/admin/admin-other/admin-other.ts
index 4eab94d..4f02aba 100644
--- a/src/ts/components/admin/admin-other/admin-other.ts
+++ b/src/ts/components/admin/admin-other/admin-other.ts
@@ -49,7 +49,9 @@ export class AdminOther implements OnInit, OnDestroy {
});
}
ngOnDestroy() {
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
}
saveFields() {
let settings: any = {};
@@ -67,7 +69,8 @@ export class AdminOther implements OnInit, OnDestroy {
try {
compact(this.suspiciousPonies!.split(/\n/g).map(x => x.trim())).map(x => JSON.parse(x));
this.model.updateSettings({ suspiciousPonies: this.suspiciousPonies });
- } catch (e) {
+ }
+ catch (e) {
this.suspiciousPoniesError = isErrorAlike(e) ? e.message : 'Unknown error';
}
}
diff --git a/src/ts/components/admin/admin-ponies/admin-ponies.ts b/src/ts/components/admin/admin-ponies/admin-ponies.ts
index ff521c9..1c17ba5 100644
--- a/src/ts/components/admin/admin-ponies/admin-ponies.ts
+++ b/src/ts/components/admin/admin-ponies/admin-ponies.ts
@@ -90,7 +90,8 @@ export class AdminPonies implements OnInit {
}
this.items = result.items;
- } else {
+ }
+ else {
this.items = [];
}
})
diff --git a/src/ts/components/admin/admin-reports/admin-reports-perf/admin-reports-perf.ts b/src/ts/components/admin/admin-reports/admin-reports-perf/admin-reports-perf.ts
index 781a426..07ab7ee 100644
--- a/src/ts/components/admin/admin-reports/admin-reports-perf/admin-reports-perf.ts
+++ b/src/ts/components/admin/admin-reports/admin-reports-perf/admin-reports-perf.ts
@@ -112,7 +112,8 @@ export class AdminReportsPerf {
element.style.left = `${x + 10}px`;
element.style.top = `${y + 10}px`;
element.innerText = tooltip.text;
- } else {
+ }
+ else {
element.style.display = 'none';
}
}
@@ -208,8 +209,9 @@ export class AdminReportsPerf {
this.tooltips.length = 0;
- if (!this.timings.length)
+ if (!this.timings.length) {
return;
+ }
const firstTime = this.timings[0].time;
const startTime = this.startTime;
@@ -254,7 +256,8 @@ export class AdminReportsPerf {
for (const entry of this.timings) {
if (entry.type === TimingEntryType.Start) {
startStack.push(entry);
- } else {
+ }
+ else {
const start = startStack.pop()!;
const name = start.name!;
const startX = timeToX(start.time);
@@ -267,9 +270,11 @@ export class AdminReportsPerf {
if (startStack.length === 0) {
context.fillStyle = '#efc457';
text = `${text} (${time.toFixed(2)} ms) ${(100 * time / frameTime).toFixed(0)}%`;
- } else if (/\(\)$/.test(name)) {
+ }
+ else if (/\(\)$/.test(name)) {
context.fillStyle = '#d4ecc6';
- } else {
+ }
+ else {
context.fillStyle = '#c6dcec';
}
@@ -298,7 +303,8 @@ export class AdminReportsPerf {
for (const entry of this.timings) {
if (entry.type === TimingEntryType.Start) {
startStack.push({ ...entry, excludedTime: 0 });
- } else {
+ }
+ else {
const start = startStack.pop()!;
const name = start.name!;
const time = entry.time - start.time;
diff --git a/src/ts/components/admin/admin.ts b/src/ts/components/admin/admin.ts
index 36e1ae4..d71923d 100644
--- a/src/ts/components/admin/admin.ts
+++ b/src/ts/components/admin/admin.ts
@@ -41,11 +41,14 @@ export class AdminApp {
get loading() {
if (!this.model.initialized) {
return 'Initializing';
- } else if (!this.model.connected) {
+ }
+ else if (!this.model.connected) {
return 'Connecting';
- } else if (!this.model.loaded) {
+ }
+ else if (!this.model.loaded) {
return 'Loading';
- } else {
+ }
+ else {
return '';
}
}
diff --git a/src/ts/components/admin/base-table.ts b/src/ts/components/admin/base-table.ts
index 9930238..d988bfe 100644
--- a/src/ts/components/admin/base-table.ts
+++ b/src/ts/components/admin/base-table.ts
@@ -48,7 +48,8 @@ export abstract class BaseTable {
sortBy(field: string) {
if (this.sortedBy === field) {
this.sortedAsc = !this.sortedAsc;
- } else {
+ }
+ else {
this.sortedBy = field;
this.sortedAsc = true;
}
diff --git a/src/ts/components/admin/pipes/translitPipe.ts b/src/ts/components/admin/pipes/translitPipe.ts
index c08f4a4..c57dce5 100644
--- a/src/ts/components/admin/pipes/translitPipe.ts
+++ b/src/ts/components/admin/pipes/translitPipe.ts
@@ -7,8 +7,9 @@ import { transliterate } from 'transliteration';
})
export class TranslitPipe implements PipeTransform {
transform(value: string) {
- if (!value || /^[a-z0-9-_.,[]!@#$%^&*{}|\/\\ ]+$/i.test(value))
+ if (!value || /^[a-z0-9-_.,[]!@#$%^&*{}|\/\\ ]+$/i.test(value)) {
return undefined;
+ }
const translit = transliterate(value);
return translit !== value ? translit : undefined;
diff --git a/src/ts/components/admin/shared/account-info-remote/account-info-remote.ts b/src/ts/components/admin/shared/account-info-remote/account-info-remote.ts
index a05b2f7..b21152b 100644
--- a/src/ts/components/admin/shared/account-info-remote/account-info-remote.ts
+++ b/src/ts/components/admin/shared/account-info-remote/account-info-remote.ts
@@ -20,7 +20,9 @@ export class AccountInfoRemote implements OnDestroy {
constructor(private model: AdminModel) {
}
ngOnDestroy() {
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
}
get accountId() {
return this._accountId;
diff --git a/src/ts/components/admin/shared/account-info/account-info.ts b/src/ts/components/admin/shared/account-info/account-info.ts
index e0ee3b7..e0fec77 100644
--- a/src/ts/components/admin/shared/account-info/account-info.ts
+++ b/src/ts/components/admin/shared/account-info/account-info.ts
@@ -134,11 +134,14 @@ export class AccountInfo implements OnInit, OnChanges {
if (this.account.flags) {
return 'text-banned';
- } else if (!counters && !this.account.supporter) {
+ }
+ else if (!counters && !this.account.supporter) {
return 'text-muted';
- } else if (counters && ((counters.spam || 0) > 100 || (counters.swears || 0) > 10)) {
+ }
+ else if (counters && ((counters.spam || 0) > 100 || (counters.swears || 0) > 10)) {
return 'text-alert';
- } else {
+ }
+ else {
return 'text-present';
}
}
@@ -190,7 +193,9 @@ export class AccountInfo implements OnInit, OnChanges {
this.alertModalRef = this.modalService.show(this.alertModal, { ignoreBackdropClick: true });
}
cancelAlert() {
- this.alertModalRef && this.alertModalRef.hide();
+ if (this.alertModalRef) {
+ this.alertModalRef.hide();
+ }
this.alertModalRef = undefined;
}
confirmAlert() {
@@ -206,7 +211,8 @@ export class AccountInfo implements OnInit, OnChanges {
if (cached && cached.generatedAt > threshold.getTime()) {
this.duplicates = cached;
- } else {
+ }
+ else {
this.model.getAllDuplicatesQuickInfo(account._id)
.then(duplicates => {
if (duplicates) {
diff --git a/src/ts/components/admin/shared/admin-chat-log/admin-chat-log.ts b/src/ts/components/admin/shared/admin-chat-log/admin-chat-log.ts
index a1c15cc..91b0af1 100644
--- a/src/ts/components/admin/shared/admin-chat-log/admin-chat-log.ts
+++ b/src/ts/components/admin/shared/admin-chat-log/admin-chat-log.ts
@@ -42,7 +42,8 @@ export class AdminChatLog implements OnDestroy {
set autoRefresh(value: boolean) {
if (value) {
this.refreshInterval = this.refreshInterval || setInterval(() => this.refresh(), 10 * 1000);
- } else {
+ }
+ else {
this.stopInterval();
}
}
@@ -75,7 +76,8 @@ export class AdminChatLog implements OnDestroy {
add(account: Account) {
if (!this.account) {
this.show(account);
- } else if (account !== this.account && !includes(this.accounts, account)) {
+ }
+ else if (account !== this.account && !includes(this.accounts, account)) {
this.date = this.date || this.today;
this.accounts.push(account);
this.refresh();
@@ -116,7 +118,8 @@ export class AdminChatLog implements OnDestroy {
if (this.account) {
const accounts = [this.account._id, ...this.accounts.map(a => a._id)];
this.handleChat(this.model.accountsFormattedChat(accounts, date));
- } else if (this.search) {
+ }
+ else if (this.search) {
this.handleChat(this.model.searchFormattedChat(this.search, date));
}
}
@@ -177,7 +180,8 @@ export class AdminChatLog implements OnDestroy {
this.atNode += i;
this.processIdle = requestIdleCallback(() => this.processNodes());
- } else {
+ }
+ else {
this.nodesToProcess = undefined;
}
}
diff --git a/src/ts/components/admin/shared/auth-info-edit/auth-info-edit.ts b/src/ts/components/admin/shared/auth-info-edit/auth-info-edit.ts
index 330c550..e297fe8 100644
--- a/src/ts/components/admin/shared/auth-info-edit/auth-info-edit.ts
+++ b/src/ts/components/admin/shared/auth-info-edit/auth-info-edit.ts
@@ -30,12 +30,16 @@ export class AuthInfoEdit implements OnDestroy {
if (this.authId !== value) {
this._authId = value;
this.auth = undefined;
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
this.subscription = value ? this.model.auths.subscribe(value, auth => this.auth = auth) : undefined;
}
}
ngOnDestroy() {
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
}
removeAuth(auth: Auth | undefined) {
if (auth && confirm('Are you sure?')) {
diff --git a/src/ts/components/admin/shared/auth-info-remote/auth-info-remote.ts b/src/ts/components/admin/shared/auth-info-remote/auth-info-remote.ts
index bebbdde..b541ec3 100644
--- a/src/ts/components/admin/shared/auth-info-remote/auth-info-remote.ts
+++ b/src/ts/components/admin/shared/auth-info-remote/auth-info-remote.ts
@@ -23,11 +23,15 @@ export class AuthInfoRemote implements OnDestroy {
if (this.authId !== value) {
this._authId = value;
this.auth = undefined;
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
this.subscription = value ? this.model.auths.subscribe(value, auth => this.auth = auth) : undefined;
}
}
ngOnDestroy() {
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
}
}
diff --git a/src/ts/components/admin/shared/auth-list-remote/auth-list-remote.ts b/src/ts/components/admin/shared/auth-list-remote/auth-list-remote.ts
index b3967b7..0ff7fe3 100644
--- a/src/ts/components/admin/shared/auth-list-remote/auth-list-remote.ts
+++ b/src/ts/components/admin/shared/auth-list-remote/auth-list-remote.ts
@@ -26,7 +26,9 @@ export class AuthListRemote implements OnDestroy {
this._accountId = value;
this.auths = [];
this.loading = true;
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
this.subscription = value ? this.model.accountAuths.subscribe(value, auths => {
this.auths = auths || [];
this.loading = false;
@@ -34,6 +36,8 @@ export class AuthListRemote implements OnDestroy {
}
}
ngOnDestroy() {
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
}
}
diff --git a/src/ts/components/admin/shared/ban-icon/ban-icon.ts b/src/ts/components/admin/shared/ban-icon/ban-icon.ts
index 5eb57f1..9cdefee 100644
--- a/src/ts/components/admin/shared/ban-icon/ban-icon.ts
+++ b/src/ts/components/admin/shared/ban-icon/ban-icon.ts
@@ -37,9 +37,11 @@ export class BanIcon implements OnInit, OnDestroy, OnChanges {
get className() {
if (this.isPerma) {
return 'text-banned';
- } else if (this.isTimedOut) {
+ }
+ else if (this.isTimedOut) {
return 'text-alert';
- } else {
+ }
+ else {
return 'text-muted';
}
}
diff --git a/src/ts/components/admin/shared/events-table/events-table.ts b/src/ts/components/admin/shared/events-table/events-table.ts
index 47d7795..3d5ba5a 100644
--- a/src/ts/components/admin/shared/events-table/events-table.ts
+++ b/src/ts/components/admin/shared/events-table/events-table.ts
@@ -48,7 +48,8 @@ export class EventsTable {
onShowChat(e: MouseEvent, event: Event, account: Account | undefined) {
if (e.shiftKey) {
this.addChat.emit({ event, account });
- } else {
+ }
+ else {
this.showChat.emit({ event, account });
}
}
diff --git a/src/ts/components/admin/shared/from-now.ts b/src/ts/components/admin/shared/from-now.ts
index 022296e..4206bc3 100644
--- a/src/ts/components/admin/shared/from-now.ts
+++ b/src/ts/components/admin/shared/from-now.ts
@@ -24,7 +24,9 @@ export class FromNow implements OnInit, OnDestroy, OnChanges {
this.update();
}
ngOnDestroy() {
- this.unsubscribe && this.unsubscribe();
+ if (this.unsubscribe) {
+ this.unsubscribe();
+ }
}
private update() {
const text = this.date
diff --git a/src/ts/components/admin/shared/origin-info-remote/origin-info-remote.ts b/src/ts/components/admin/shared/origin-info-remote/origin-info-remote.ts
index b9675b0..0b5241f 100644
--- a/src/ts/components/admin/shared/origin-info-remote/origin-info-remote.ts
+++ b/src/ts/components/admin/shared/origin-info-remote/origin-info-remote.ts
@@ -23,11 +23,15 @@ export class OriginInfoRemote implements OnDestroy {
if (this.originIP !== value) {
this._originIP = value;
this.origin = undefined;
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
this.subscription = value ? this.model.origins.subscribe(value, origin => this.origin = origin) : undefined;
}
}
ngOnDestroy() {
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
}
}
diff --git a/src/ts/components/admin/shared/origin-list-remote/origin-list-remote.ts b/src/ts/components/admin/shared/origin-list-remote/origin-list-remote.ts
index af986e5..e4105a6 100644
--- a/src/ts/components/admin/shared/origin-list-remote/origin-list-remote.ts
+++ b/src/ts/components/admin/shared/origin-list-remote/origin-list-remote.ts
@@ -24,11 +24,15 @@ export class OriginListRemote implements OnDestroy {
if (this.accountId !== value) {
this._accountId = value;
this.origins = [];
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
this.subscription = value ? this.model.accountOrigins.subscribe(value, x => this.origins = x || []) : undefined;
}
}
ngOnDestroy() {
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
}
}
diff --git a/src/ts/components/admin/shared/pony-info-remote/pony-info-remote.ts b/src/ts/components/admin/shared/pony-info-remote/pony-info-remote.ts
index 673b6b4..87c564c 100644
--- a/src/ts/components/admin/shared/pony-info-remote/pony-info-remote.ts
+++ b/src/ts/components/admin/shared/pony-info-remote/pony-info-remote.ts
@@ -24,11 +24,15 @@ export class PonyInfoRemote implements OnDestroy {
if (this.ponyId !== value) {
this._ponyId = value;
this.pony = undefined;
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
this.subscription = value ? this.model.ponies.subscribe(value, pony => this.pony = pony) : undefined;
}
}
ngOnDestroy() {
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
}
}
diff --git a/src/ts/components/admin/shared/pony-info/pony-info.ts b/src/ts/components/admin/shared/pony-info/pony-info.ts
index 99e5b28..1422fff 100644
--- a/src/ts/components/admin/shared/pony-info/pony-info.ts
+++ b/src/ts/components/admin/shared/pony-info/pony-info.ts
@@ -25,9 +25,11 @@ export class PonyInfo implements OnChanges {
if (this.pony) {
if (isForbiddenName(this.pony.name)) {
this.labelClass = 'badge-forbidden';
- } else if (hasFlag(this.pony.flags, CharacterFlags.BadCM)) {
+ }
+ else if (hasFlag(this.pony.flags, CharacterFlags.BadCM)) {
this.labelClass = 'badge-danger';
- } else {
+ }
+ else {
this.labelClass = 'badge-none';
}
}
diff --git a/src/ts/components/admin/shared/pony-list-remote/pony-list-remote.ts b/src/ts/components/admin/shared/pony-list-remote/pony-list-remote.ts
index b10f021..03bc3e5 100644
--- a/src/ts/components/admin/shared/pony-list-remote/pony-list-remote.ts
+++ b/src/ts/components/admin/shared/pony-list-remote/pony-list-remote.ts
@@ -39,7 +39,9 @@ export class PonyListRemote implements OnDestroy {
this.ponies = [];
this.ponyInfos = [];
this.loading = true;
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
this.subscription = value ? this.model.accountPonies.subscribe(value, (x = []) => {
this.ponyInfos = x;
this.updatePonies();
@@ -48,7 +50,9 @@ export class PonyListRemote implements OnDestroy {
}
}
ngOnDestroy() {
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
}
remove(characterId: string) {
if (confirm('Are you sure?')) {
diff --git a/src/ts/components/app/app.ts b/src/ts/components/app/app.ts
index cc2829d..b952ad9 100644
--- a/src/ts/components/app/app.ts
+++ b/src/ts/components/app/app.ts
@@ -193,7 +193,8 @@ export class App implements OnInit, OnDestroy {
if (isSelected(this.game, message.entityId)) {
this.game.whisperTo = entity;
chatBox.setChatType('whisper');
- } else {
+ }
+ else {
this.game.select(entity as Pony);
}
}
diff --git a/src/ts/components/app/character/character.ts b/src/ts/components/app/character/character.ts
index b222e5f..251a166 100644
--- a/src/ts/components/app/character/character.ts
+++ b/src/ts/components/app/character/character.ts
@@ -490,8 +490,11 @@ export class Character implements OnInit, OnDestroy {
await this.model.savePony(pony, true);
imported++;
}
- } catch (e) {
- DEVELOPMENT && console.error(e);
+ }
+ catch (e) {
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
}
}
diff --git a/src/ts/components/app/help/help.ts b/src/ts/components/app/help/help.ts
index 00bd448..97faaa7 100644
--- a/src/ts/components/app/help/help.ts
+++ b/src/ts/components/app/help/help.ts
@@ -28,7 +28,9 @@ export class Help {
ngAfterViewInit() {
this.route.fragment.subscribe(f => {
const element = document.querySelector('#' + f);
- if (element) setTimeout(() => element.scrollIntoView(), 10);
+ if (element) {
+ setTimeout(() => element.scrollIntoView(), 10);
+ }
});
}
}
diff --git a/src/ts/components/services/adminModel.ts b/src/ts/components/services/adminModel.ts
index 2cda65d..a19a5af 100644
--- a/src/ts/components/services/adminModel.ts
+++ b/src/ts/components/services/adminModel.ts
@@ -177,8 +177,9 @@ export class AdminModel {
return this.liveEvents.finished;
}
initialize(live: boolean) {
- if (this.initializedLive)
+ if (this.initializedLive) {
return;
+ }
notification.requestPermission();
@@ -545,8 +546,9 @@ export class AdminModel {
}
private updateStateTimeout: any;
private updateState(): void {
- if (!this.running)
+ if (!this.running) {
return;
+ }
clearTimeout(this.updateStateTimeout);
@@ -590,7 +592,8 @@ export class AdminModel {
function decodeDate(value: number | undefined, base: string | undefined): Date {
if (value == null || base == null) {
return new Date(0);
- } else {
+ }
+ else {
const d = new Date(base);
d.setTime(d.getTime() + value);
return d;
diff --git a/src/ts/components/services/audio.ts b/src/ts/components/services/audio.ts
index c15cbd9..81a1a70 100644
--- a/src/ts/components/services/audio.ts
+++ b/src/ts/components/services/audio.ts
@@ -76,7 +76,8 @@ function fadeOut(track: Track, id: number, volume: number) {
howl
.fade(volume, 0, 1000, id)
.once('fade', () => howl.pause(id).stop(id), id);
- } else {
+ }
+ else {
howl
.volume(0, id)
.pause(id)
@@ -124,7 +125,8 @@ export class Audio {
if (this.playing) {
if (this.instance) {
this.setInstanceVolume(this.instance, this.volume);
- } else if (this.volume) {
+ }
+ else if (this.volume) {
this.playRandomTrack();
}
}
@@ -137,12 +139,14 @@ export class Audio {
if (this.volume) {
if (this.instance) {
this.resumeInstance(this.instance);
- } else {
+ }
+ else {
this.playRandomTrack();
}
}
}
- } catch (e) {
+ }
+ catch (e) {
console.error(e);
}
}
@@ -150,10 +154,12 @@ export class Audio {
if (FADE_TRACKS) {
if (this.playing && this.volume) {
this.playRandomTrack();
- } else {
+ }
+ else {
this.play();
}
- } else {
+ }
+ else {
this.play();
}
}
@@ -175,15 +181,15 @@ export class Audio {
private switchToTrack(track: Track) {
if (this.instance && this.instance.track === track) {
return false;
- } else {
+ }
+ else {
this.stopInstance(this.instance);
this.instance = this.playTrack(track);
return true;
}
}
playRandomTrack() {
- while (!this.switchToTrack(sample(this.tracks)!))
- ;
+ while (!this.switchToTrack(sample(this.tracks)!)) {}
this.loops = random(4, 7);
}
@@ -215,7 +221,8 @@ export class Audio {
if (volume && !howl.playing(instance.id)) {
howl.play(instance.id);
- } else if (!volume && howl.playing(instance.id)) {
+ }
+ else if (!volume && howl.playing(instance.id)) {
howl.pause(instance.id);
}
}
@@ -243,7 +250,8 @@ export class Audio {
if (this.volume && this.playing) {
this.playRandomTrack();
- } else {
+ }
+ else {
this.stopInstance(this.instance);
}
}
diff --git a/src/ts/components/services/authGuard.ts b/src/ts/components/services/authGuard.ts
index b185f5f..9f60751 100644
--- a/src/ts/components/services/authGuard.ts
+++ b/src/ts/components/services/authGuard.ts
@@ -13,7 +13,8 @@ export class AuthGuard implements CanActivate {
.then(account => {
if (account) {
return true;
- } else {
+ }
+ else {
this.router.navigate(['/']);
return false;
}
diff --git a/src/ts/components/services/gameService.ts b/src/ts/components/services/gameService.ts
index 7376eac..dca6fcb 100644
--- a/src/ts/components/services/gameService.ts
+++ b/src/ts/components/services/gameService.ts
@@ -14,7 +14,7 @@ import { meetsRequirement } from '../../common/accountUtils';
import { isLanguage, isFocused, sortServersForRussian } from '../../client/clientUtils';
import { StorageService } from './storageService';
-export interface ClientSocketService extends SocketService { }
+export type ClientSocketService = SocketService;
function createSocket(
gameService: GameService, game: PonyTownGame, model: Model, zone: NgZone, options: ClientOptions,
@@ -183,7 +183,8 @@ export class GameService {
if (reason === LeaveReason.Swearing) {
this.leftMessage = 'Kicked for swearing or inappropriate language';
this.locked = true;
- } else {
+ }
+ else {
this.leftMessage = undefined;
}
@@ -233,11 +234,14 @@ export class GameService {
private getAndUpdateStatus(account: AccountData | undefined) {
if (this.joining || this.playing || !account || !isFocused()) {
return Promise.resolve();
- } else {
+ }
+ else {
return this.model.status(this.initialized)
.then(status => this.updateStatus(account, status))
.catch((e: RequestError) => {
- DEVELOPMENT && console.error(e);
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
this.offline = e.message === OFFLINE_ERROR;
this.versionError = e.message === VERSION_ERROR;
this.protectionError = e.message === PROTECTION_ERROR;
@@ -255,14 +259,16 @@ export class GameService {
if (existing) {
merge(existing, server);
- } else if ('name' in server) {
+ }
+ else if ('name' in server) {
const info = server as ServerInfo;
info.countryFlags = info.flag && /^[a-z]{2}( [a-z]{2})*$/.test(info.flag) ? info.flag.split(/ /g) : [];
if (info.name && account && meetsRequirement(account, info.require)) {
this.servers.push(info);
}
- } else {
+ }
+ else {
// got new server on the list
this.initialized = false;
}
@@ -302,7 +308,8 @@ export class GameService {
if (socket.isConnected) {
clearInterval(interval);
this.zone.run(resolve);
- } else if (!this.joining) {
+ }
+ else if (!this.joining) {
clearInterval(interval);
this.zone.run(() => reject(new Error('Cancelled (poll)')));
}
diff --git a/src/ts/components/services/intervalUpdateService.ts b/src/ts/components/services/intervalUpdateService.ts
index 1f04415..f244779 100644
--- a/src/ts/components/services/intervalUpdateService.ts
+++ b/src/ts/components/services/intervalUpdateService.ts
@@ -35,7 +35,8 @@ export class IntervalUpdateService {
return (on: boolean) => {
if (on && !unsubscribe) {
unsubscribe = this.subscribe(action);
- } else if (!on && unsubscribe) {
+ }
+ else if (!on && unsubscribe) {
unsubscribe();
unsubscribe = undefined;
}
diff --git a/src/ts/components/services/liveCollection.ts b/src/ts/components/services/liveCollection.ts
index 4c69456..4c43727 100644
--- a/src/ts/components/services/liveCollection.ts
+++ b/src/ts/components/services/liveCollection.ts
@@ -51,7 +51,8 @@ export class LiveCollection {
if (removeFromList || this.options.deleteItems) {
removeItem(this.items, item);
this.itemsMap.delete(key);
- } else if (deleted) {
+ }
+ else if (deleted) {
item.deleted = true;
}
@@ -64,8 +65,9 @@ export class LiveCollection {
return this.server.assignAccount(this.name, id, account);
}
live(): Promise {
- if (!this.running)
+ if (!this.running) {
return Promise.resolve();
+ }
clearTimeout(this.liveTimeout);
@@ -129,11 +131,13 @@ export class LiveCollection {
if (doc) {
if (this.options.onUpdate) {
this.options.onUpdate(doc, update);
- } else {
+ }
+ else {
Object.assign(doc, update);
}
all.push(doc);
- } else if (!liveFetch || !this.options.ignore || !this.options.ignore(update)) {
+ }
+ else if (!liveFetch || !this.options.ignore || !this.options.ignore(update)) {
this.push(update);
added.push(update);
all.push(update);
diff --git a/src/ts/components/services/model.ts b/src/ts/components/services/model.ts
index 246f9b1..99ecdbd 100644
--- a/src/ts/components/services/model.ts
+++ b/src/ts/components/services/model.ts
@@ -78,7 +78,8 @@ export function getPonyTag(pony: PonyObject, account: AccountData | undefined) {
if (account) {
const tag = canUseTag(account, pony.tag || '') ? pony.tag : undefined;
return (!tag && account.supporter && !pony.hideSupport) ? `sup${account.supporter}` : tag;
- } else {
+ }
+ else {
return undefined;
}
}
@@ -179,7 +180,8 @@ export class Model {
modStatus.mod = isMod(account);
modStatus.check = account.check;
modStatus.editor = account.editor || modStatus.editor;
- } catch { }
+ }
+ catch { }
if (modStatus.editor) {
modStatus.editor.typeToName.forEach(({ type, name }) => entityTypeToName.set(type, name));
@@ -208,18 +210,22 @@ export class Model {
if (e.message === ACCESS_ERROR) {
this.loading = false;
this.storage.setItem('vid', '---');
- } else if (e.message === LIMIT_ERROR) {
+ }
+ else if (e.message === LIMIT_ERROR) {
this.loadingError = 'request-limit';
return delay(5000).then(() => this.initializeAccount());
- } else if (e.message === OFFLINE_ERROR) {
+ }
+ else if (e.message === OFFLINE_ERROR) {
this.loadingError = 'cannot-connect';
return delay(5000).then(() => this.initializeAccount());
- } else if (e.message === PROTECTION_ERROR) {
+ }
+ else if (e.message === PROTECTION_ERROR) {
this.loadingError = 'cloudflare-error';
this.protectionErrors.next();
// } else if (e.message === VERSION_ERROR) {
// this.updating = true;
- } else {
+ }
+ else {
setTimeout(() => this.loadingError = 'unexpected-error', 5 * SECOND);
console.error(e);
}
@@ -240,7 +246,9 @@ export class Model {
})).sort(compareFriends);
})
.catch(e => {
- DEVELOPMENT && console.error(e);
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
setTimeout(() => this.fetchFriends(), 5000);
});
}
@@ -275,7 +283,8 @@ export class Model {
try {
const ponyInfo = decompressPonyString(pony.info, true);
return { ponyInfo, ...pony };
- } catch (e) {
+ }
+ catch (e) {
this.errorReporter.reportError(e, { ponyInfo: pony.info });
this.errorReporter.reportError('Pony info reading error', { originalError: isErrorAlike(e) ? e.message: '', ponyInfo: pony.info });
throw new Error('Error while reading pony info');
@@ -283,7 +292,9 @@ export class Model {
}
selectPony(pony: PonyObject) {
const copy = this.parsePonyObject(pony);
- copy.ponyInfo && syncLockedPonyInfo(copy.ponyInfo);
+ if (copy.ponyInfo) {
+ syncLockedPonyInfo(copy.ponyInfo);
+ }
this._pony = copy;
}
// account
@@ -308,7 +319,8 @@ export class Model {
if (isStandalone()) {
window.open(url);
- } else {
+ }
+ else {
location.href = url;
}
}
@@ -394,7 +406,8 @@ export class Model {
if (pony.id) {
removeById(this.ponies, pony.id);
- } else {
+ }
+ else {
this.account!.characterCount++;
}
@@ -443,7 +456,8 @@ export class Model {
if (this.account.birthyear) {
age = currentYear - this.account.birthyear;
- } else if (this.account.birthdate) {
+ }
+ else if (this.account.birthdate) {
const [year, month] = this.account.birthdate.split('-');
const before = parseInt(month, 10) > currentMonth;
age = Math.max(0, currentYear - parseInt(year, 10) - (before ? 1 : 0));
@@ -458,12 +472,15 @@ export class Model {
return observableToPromise(this.http.get('/api2/game/status', { params }));
}
join(serverId: string, ponyId: string): Promise {
- if (this.pending)
+ if (this.pending) {
return Promise.reject(new Error('Joining in progress'));
- if (!serverId)
+ }
+ if (!serverId) {
return Promise.reject(new Error('Invalid server ID'));
- if (!ponyId)
+ }
+ if (!ponyId) {
return Promise.reject(new Error('Invalid pony ID'));
+ }
this.pending = true;
diff --git a/src/ts/components/services/modelSubscriber.ts b/src/ts/components/services/modelSubscriber.ts
index e047237..ca81000 100644
--- a/src/ts/components/services/modelSubscriber.ts
+++ b/src/ts/components/services/modelSubscriber.ts
@@ -60,7 +60,8 @@ export class ModelSubscriber {
if (subscription.value !== undefined) {
callback(subscription.value);
}
- } else {
+ }
+ else {
this.socket.server.subscribe(this.type, id);
this.subscriptions.set(id, {
value: this.defaultValue,
diff --git a/src/ts/components/services/rollbarErrorHandler.ts b/src/ts/components/services/rollbarErrorHandler.ts
index 0802696..95818a4 100644
--- a/src/ts/components/services/rollbarErrorHandler.ts
+++ b/src/ts/components/services/rollbarErrorHandler.ts
@@ -1,3 +1,4 @@
+/* eslint-disable camelcase */
import { ErrorHandler, Injectable, Injector, InjectionToken } from '@angular/core';
import Rollbar from 'rollbar';
import { version } from '../../client/data';
@@ -34,7 +35,8 @@ export const RollbarService = new InjectionToken('rollbar');
export function rollbarFactory() {
if (DEVELOPMENT) {
return undefined;
- } else {
+ }
+ else {
const rollbar = Rollbar.init(rollbarConfig);
rollbar.configure({ checkIgnore: rollbarCheckIgnore });
return rollbar;
diff --git a/src/ts/components/services/rollbarErrorReporter.ts b/src/ts/components/services/rollbarErrorReporter.ts
index 3ffb189..26a4af2 100644
--- a/src/ts/components/services/rollbarErrorReporter.ts
+++ b/src/ts/components/services/rollbarErrorReporter.ts
@@ -25,7 +25,9 @@ export class RollbarErrorReporter extends ErrorReporter {
}
}
reportError(error: any, data?: any) {
- DEVELOPMENT && console.error(error, data);
+ if (DEVELOPMENT) {
+ console.error(error, data);
+ }
if (this.rollbar && !isIgnoredError(error)) {
this.rollbar.error(error, data);
diff --git a/src/ts/components/services/settingsService.ts b/src/ts/components/services/settingsService.ts
index d472f9f..ad52ff8 100644
--- a/src/ts/components/services/settingsService.ts
+++ b/src/ts/components/services/settingsService.ts
@@ -32,7 +32,8 @@ export class SettingsService {
if (this.save(settings)) {
return Promise.resolve();
- } else {
+ }
+ else {
return this.model.saveSettings(settings);
}
}
diff --git a/src/ts/components/services/storageService.ts b/src/ts/components/services/storageService.ts
index 54e40f2..f942d8b 100644
--- a/src/ts/components/services/storageService.ts
+++ b/src/ts/components/services/storageService.ts
@@ -9,18 +9,21 @@ export class StorageService {
if (typeof localStorage === 'undefined') {
this.data = new Map();
}
- } catch {
+ }
+ catch {
this.data = new Map();
}
}
getItem(key: string) {
if (this.data) {
return this.data.get(key);
- } else {
+ }
+ else {
try {
const value = localStorage.getItem(key);
return value == null ? undefined : value;
- } catch {
+ }
+ catch {
return undefined;
}
}
@@ -29,7 +32,8 @@ export class StorageService {
try {
localStorage.setItem(key, data);
this.data = undefined;
- } catch {
+ }
+ catch {
if (!this.data) {
this.data = new Map();
}
@@ -40,25 +44,30 @@ export class StorageService {
removeItem(key: string) {
if (this.data) {
this.data.delete(key);
- } else {
+ }
+ else {
try {
localStorage.removeItem(key);
- } catch { }
+ }
+ catch { }
}
}
clear() {
if (this.data) {
this.data.clear();
- } else {
+ }
+ else {
try {
localStorage.clear();
- } catch { }
+ }
+ catch { }
}
}
getJSON(key: string, defaultValue: T): T {
try {
return JSON.parse(this.getItem(key) || '');
- } catch {
+ }
+ catch {
return defaultValue;
}
}
@@ -77,7 +86,8 @@ export class StorageService {
setBoolean(key: string, value: boolean) {
if (value) {
this.setItem(key, 'true');
- } else {
+ }
+ else {
this.removeItem(key);
}
}
diff --git a/src/ts/components/shared/action-bar/action-bar.ts b/src/ts/components/shared/action-bar/action-bar.ts
index 7a62058..c5dbc95 100644
--- a/src/ts/components/shared/action-bar/action-bar.ts
+++ b/src/ts/components/shared/action-bar/action-bar.ts
@@ -117,7 +117,8 @@ export class ActionBar {
while (actions.length < 5 || (last(actions)!.action !== undefined && actions.length < ACTIONS_LIMIT)) {
actions.push({ action: undefined });
}
- } else {
+ }
+ else {
while (actions.length > 0 && last(actions)!.action === undefined) {
actions.pop();
}
diff --git a/src/ts/components/shared/actions-modal/actions-modal.ts b/src/ts/components/shared/actions-modal/actions-modal.ts
index b377f0b..8a2d21d 100644
--- a/src/ts/components/shared/actions-modal/actions-modal.ts
+++ b/src/ts/components/shared/actions-modal/actions-modal.ts
@@ -96,7 +96,9 @@ export class ActionsModal implements OnInit, OnDestroy {
document.body.classList.remove('actions-modal-opened');
this.game.editingActions = false;
clearInterval(this.interval);
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
this.close.emit(); // need to emit in case the menu wasn't closed with the Close button
this.notify.emit();
}
diff --git a/src/ts/components/shared/bitmap-box/bitmap-box.ts b/src/ts/components/shared/bitmap-box/bitmap-box.ts
index 235e9be..6e34269 100644
--- a/src/ts/components/shared/bitmap-box/bitmap-box.ts
+++ b/src/ts/components/shared/bitmap-box/bitmap-box.ts
@@ -33,9 +33,11 @@ export class BitmapBox implements OnChanges {
if (this.bitmap) {
if (this.tool === 'eraser') {
this.bitmap[index] = '';
- } else if (this.tool === 'brush') {
+ }
+ else if (this.tool === 'brush') {
this.bitmap[index] = parseColor(this.bitmap[index]) === parseColor(this.color) ? '' : this.color;
- } else if (this.tool === 'eyedropper') {
+ }
+ else if (this.tool === 'eyedropper') {
this.color = this.bitmap[index];
this.colorChange.emit(this.color);
}
diff --git a/src/ts/components/shared/character-list/character-list.ts b/src/ts/components/shared/character-list/character-list.ts
index 0ddc582..45d238b 100644
--- a/src/ts/components/shared/character-list/character-list.ts
+++ b/src/ts/components/shared/character-list/character-list.ts
@@ -16,9 +16,11 @@ function getSortTag(pony: PonyObject) {
function sortTagToNumber(tag: string) {
if (tag === 'top') {
return -1;
- } else if (tag === 'end') {
+ }
+ else if (tag === 'end') {
return 999999999;
- } else {
+ }
+ else {
return +tag;
}
}
@@ -33,11 +35,14 @@ function comparePonies(a: PonyObject, b: PonyObject) {
if (aTag && bTag) {
return (sortTagToNumber(aTag) - sortTagToNumber(bTag)) || fallbackComparePonies(a, b);
- } else if (aTag) {
+ }
+ else if (aTag) {
return aTag === 'end' ? 1 : -1;
- } else if (bTag) {
+ }
+ else if (bTag) {
return bTag === 'end' ? -1 : 1;
- } else {
+ }
+ else {
return fallbackComparePonies(a, b);
}
}
@@ -93,20 +98,25 @@ export class CharacterList implements OnInit {
e.stopPropagation();
this.search = '';
this.updatePonies();
- } else {
+ }
+ else {
this.closed();
}
- } else if (e.keyCode === Key.ENTER) {
+ }
+ else if (e.keyCode === Key.ENTER) {
const pony = this.ponies[this.selectedIndex];
if (pony) {
this.select(pony);
- } else {
+ }
+ else {
this.closed();
}
- } else if (e.keyCode === Key.UP) {
+ }
+ else if (e.keyCode === Key.UP) {
this.setSelectedIndex(this.selectedIndex <= 0 ? (this.ponies.length - 1) : (this.selectedIndex - 1));
- } else if (e.keyCode === Key.DOWN) {
+ }
+ else if (e.keyCode === Key.DOWN) {
this.setSelectedIndex(this.selectedIndex === (this.ponies.length - 1) ? 0 : (this.selectedIndex + 1));
}
}
@@ -141,7 +151,8 @@ export class CharacterList implements OnInit {
const text = `${pony.name} ${pony.desc || ''}`.toLowerCase();
return matchesWords(text, words);
}).sort(comparePonies);
- } else {
+ }
+ else {
this.ponies = this.model.ponies.slice().sort(comparePonies);
}
@@ -166,7 +177,8 @@ export class CharacterList implements OnInit {
if (pony) {
this.setPreview(pony);
- } else if (this.previewPony) {
+ }
+ else if (this.previewPony) {
this.unsetPreview(this.previewPony);
}
});
diff --git a/src/ts/components/shared/character-preview/character-preview.ts b/src/ts/components/shared/character-preview/character-preview.ts
index 12aa384..6927ed5 100644
--- a/src/ts/components/shared/character-preview/character-preview.ts
+++ b/src/ts/components/shared/character-preview/character-preview.ts
@@ -85,7 +85,8 @@ export class CharacterPreview implements OnDestroy, OnChanges, AfterViewInit {
if (this.nextBlink < now) {
this.blinkFrame = 0;
}
- } else {
+ }
+ else {
this.blinkFrame++;
if (this.blinkFrame >= BLINK_FRAMES.length) {
@@ -106,11 +107,13 @@ export class CharacterPreview implements OnDestroy, OnChanges, AfterViewInit {
private tryDraw() {
try {
this.draw();
- } catch { }
+ }
+ catch { }
}
private draw() {
- if (!this.initialized)
+ if (!this.initialized) {
return;
+ }
const canvas = this.canvas.nativeElement as HTMLCanvasElement;
@@ -121,8 +124,9 @@ export class CharacterPreview implements OnDestroy, OnChanges, AfterViewInit {
const bufferWidth = Math.round(canvas.width / scale);
const bufferHeight = Math.round(canvas.height / scale);
- if (!bufferWidth || !bufferHeight)
+ if (!bufferWidth || !bufferHeight) {
return;
+ }
this.batch = this.batch || new ContextSpriteBatch(createCanvas(bufferWidth, bufferHeight));
resizeCanvas(this.batch.canvas, bufferWidth, bufferHeight);
@@ -136,7 +140,8 @@ export class CharacterPreview implements OnDestroy, OnChanges, AfterViewInit {
try {
const options = { ...DEFAULT_OPTIONS, shadow: !this.noShadow, extra: !!this.extra };
drawPony(this.batch, toPalette(this.pony), this.state || DEFAULT_STATE, x, y, options);
- } catch (e) {
+ }
+ catch (e) {
console.error(e);
}
@@ -145,8 +150,9 @@ export class CharacterPreview implements OnDestroy, OnChanges, AfterViewInit {
const viewContext = canvas.getContext('2d');
- if (!viewContext)
+ if (!viewContext) {
return;
+ }
disableImageSmoothing(viewContext);
diff --git a/src/ts/components/shared/chat-box/chat-box.ts b/src/ts/components/shared/chat-box/chat-box.ts
index 34b7c47..89cf842 100644
--- a/src/ts/components/shared/chat-box/chat-box.ts
+++ b/src/ts/components/shared/chat-box/chat-box.ts
@@ -103,14 +103,16 @@ export class ChatBox implements AfterViewInit, OnDestroy {
this.toggleEmojiBox();
if (!this.message) {
this.message = emoji;
- } else if (this.input.maxLength > this.message.length) {
+ }
+ else if (this.input.maxLength > this.message.length) {
this.message += emoji;
}
}
toggleEmojiBox() {
if (this.emojiBoxState === 'none') {
this.emojiBoxState = 'inline-block';
- } else {
+ }
+ else {
this.emojiBoxState = 'none';
}
}
@@ -134,8 +136,9 @@ export class ChatBox implements AfterViewInit, OnDestroy {
do {
offset = message.indexOf(' ', offset);
- if (offset === -1)
+ if (offset === -1) {
break;
+ }
const name = message.substr(0, offset);
entity = findBestEntityByName(this.game, name);
@@ -145,7 +148,8 @@ export class ChatBox implements AfterViewInit, OnDestroy {
if (entity) {
message = message.substr(offset);
entityId = entity.id;
- } else {
+ }
+ else {
entityId = 0;
}
}
@@ -176,20 +180,25 @@ export class ChatBox implements AfterViewInit, OnDestroy {
if (names.length === 1) {
this.message = `${this.message.substring(0, space)} ${names[0]}`;
}
- } else {
+ }
+ else {
this.message = autocompleteMesssage(this.message, e.shiftKey, this.state);
}
}
e.preventDefault();
- } else if (e.keyCode === Key.ENTER && this.isOpen) {
+ }
+ else if (e.keyCode === Key.ENTER && this.isOpen) {
this.send(e);
- } else if (e.keyCode === Key.ESCAPE) {
+ }
+ else if (e.keyCode === Key.ESCAPE) {
this.close();
e.preventDefault();
- } else if (e.keyCode === Key.SPACE) {
- if (!this.message)
+ }
+ else if (e.keyCode === Key.SPACE) {
+ if (!this.message) {
return;
+ }
const isParty = /^\/(p|party)$/i.test(this.message);
const isSay = /^\/(s|say)$/i.test(this.message);
@@ -208,33 +217,43 @@ export class ChatBox implements AfterViewInit, OnDestroy {
if (isSayOrInvalid) {
this.changeChatType(e, ChatType.Say);
- } else if (isParty) {
+ }
+ else if (isParty) {
this.changeChatType(e, ChatType.Party);
- } else if (isSup) {
+ }
+ else if (isSup) {
this.changeChatType(e, ChatType.Supporter);
- } else if (isSup1) {
+ }
+ else if (isSup1) {
this.changeChatType(e, ChatType.Supporter1);
- } else if (isSup2) {
+ }
+ else if (isSup2) {
this.changeChatType(e, ChatType.Supporter2);
- } else if (isSup3) {
+ }
+ else if (isSup3) {
this.changeChatType(e, ChatType.Supporter3);
- } else if (/^\/(t|think)$/i.test(this.message)) {
+ }
+ else if (/^\/(t|think)$/i.test(this.message)) {
if (isPartyChat(this.chatType)) {
this.changeChatType(e, ChatType.PartyThink);
- } else {
+ }
+ else {
this.changeChatType(e, ChatType.Think);
}
- } else if (/^\/(r|reply)$/i.test(this.message)) {
+ }
+ else if (/^\/(r|reply)$/i.test(this.message)) {
const lastWhisperFrom = this.game.lastWhisperFrom;
const entity = lastWhisperFrom && findEntityOrMockByAnyMeans(this.game, lastWhisperFrom.entityId);
if (entity) {
this.game.whisperTo = entity;
this.changeChatType(e, ChatType.Whisper);
- } else {
+ }
+ else {
this.changeChatType(e, ChatType.Say);
}
- } else if (/^\/(w|whisper) .+$/i.test(this.message) && !e.shiftKey) {
+ }
+ else if (/^\/(w|whisper) .+$/i.test(this.message) && !e.shiftKey) {
const name = this.message.substr(/^\/w /i.test(this.message) ? 3 : 9);
const entity = findBestEntityByName(this.game, name);
@@ -252,7 +271,8 @@ export class ChatBox implements AfterViewInit, OnDestroy {
return !!this.game.send(server =>
server.say(entityId, ((rawMessage !== '') ? rawMessage + ' ' : '') + `¯\\_(ツ)_/¯`,
chatType));
- } else {
+ }
+ else {
return !!this.game.send(server => server.say(entityId, message, chatType));
}
}
@@ -265,7 +285,8 @@ export class ChatBox implements AfterViewInit, OnDestroy {
private chat(event: Event | undefined) {
if (this.isOpen) {
this.send(event);
- } else {
+ }
+ else {
this.open();
}
}
@@ -299,12 +320,15 @@ export class ChatBox implements AfterViewInit, OnDestroy {
toggle() {
if (this.isOpen) {
this.close();
- } else {
+ }
+ else {
this.open();
}
}
onMouseEnterEmojiButton(event: MouseEvent) {
- if (!event.target) return;
+ if (!event.target) {
+ return;
+ }
const emoji = sample(emojis)!;
this.btnEmoji = emoji.names[0];
}
@@ -318,10 +342,12 @@ export class ChatBox implements AfterViewInit, OnDestroy {
if (type === 'say') {
this.chatType = ChatType.Say;
this.open();
- } else if (type === 'party' && isInParty(this.game)) {
+ }
+ else if (type === 'party' && isInParty(this.game)) {
this.chatType = ChatType.Party;
this.open();
- } else if (type === 'whisper') {
+ }
+ else if (type === 'whisper') {
this.chatType = ChatType.Whisper;
this.open();
}
@@ -344,7 +370,8 @@ export class ChatBox implements AfterViewInit, OnDestroy {
if (this.chatType === ChatType.Whisper) {
typePrefix = 'To ';
typeName = this.game.whisperTo && this.game.whisperTo.name || 'unknown';
- } else {
+ }
+ else {
typePrefix = '';
typeName = chatTypeNames[this.chatType];
}
diff --git a/src/ts/components/shared/chat-log/chat-log.ts b/src/ts/components/shared/chat-log/chat-log.ts
index 52ef72f..cb848e2 100644
--- a/src/ts/components/shared/chat-log/chat-log.ts
+++ b/src/ts/components/shared/chat-log/chat-log.ts
@@ -145,7 +145,9 @@ export function updateChatLogLine(line: ChatLogLineDOM, entry: ChatLogMessage, h
function updateTime(line: ChatLogLineDOM, hourMode?: '12' | '24') {
line.time.style.display = 'inline';
- if (!hourMode) return;
+ if (!hourMode) {
+ return;
+ }
if (hourMode === '24') {
replaceNodes(line.timeContent, `[${format(new Date(), 'HH:mm:ss')}] `);
@@ -157,9 +159,15 @@ function updateTime(line: ChatLogLineDOM, hourMode?: '12' | '24') {
}
function setNameColors(line: ChatLogLineDOM | undefined, colors?: string[]) {
- if (!colors || !line) return;
- if (colors[1]) line.name.style.color = colors[1];
- if (colors[0]) line.nameContent.style.color = colors[0];
+ if (!colors || !line) {
+ return;
+ }
+ if (colors[1]) {
+ line.name.style.color = colors[1];
+ }
+ if (colors[0]) {
+ line.nameContent.style.color = colors[0];
+ }
}
function updateChatLogName(line: ChatLogLineDOM, { name, index }: ChatLogMessage) {
@@ -168,7 +176,8 @@ function updateChatLogName(line: ChatLogLineDOM, { name, index }: ChatLogMessage
replaceNodes(line.nameContent, name);
line.index.style.display = (index > 0) ? 'inline' : 'none';
line.indexText.nodeValue = (index > 0) ? ` #${index + 1}` : '';
- } else {
+ }
+ else {
line.name.style.display = 'none';
}
}
@@ -302,7 +311,8 @@ export class ChatLog implements AfterViewInit, OnDestroy, DoCheck {
this.setUnread(0);
this.regenerateList();
this.scrollToEnd();
- } else {
+ }
+ else {
this.clearList();
}
@@ -333,7 +343,8 @@ export class ChatLog implements AfterViewInit, OnDestroy, DoCheck {
if (this.scrollingToEnd) {
this.scrolledToEnd = true;
this.scrollingToEnd = false;
- } else {
+ }
+ else {
const clientHeight = scroll.getBoundingClientRect().height;
this.scrolledToEnd = scroll.scrollTop >= (scroll.scrollHeight - clientHeight - SCROLL_END_THRESHOLD);
}
@@ -468,7 +479,8 @@ export class ChatLog implements AfterViewInit, OnDestroy, DoCheck {
this.clearTimeOutAutoClear();
this.filterChatLogLines('', false);
return;
- } else {
+ }
+ else {
this.filterColor = this.bg;
}
@@ -487,17 +499,22 @@ export class ChatLog implements AfterViewInit, OnDestroy, DoCheck {
this.filterInput.nativeElement.style.color = '';
if (value.startsWith('#')) {
value = value.slice(1);
- } else if (value.startsWith('/')) {
+ }
+ else if (value.startsWith('/')) {
value = value.slice(1);
try {
const regExp = new RegExp(value);
this.filterChatLogLines(regExp, toLowerCase);
- } catch (err) {// If the user inputs invalid regExp we just notify him by changing text color to red
- if (DEVELOPMENT) console.error(err);
+ }
+ catch (err) {// If the user inputs invalid regExp we just notify him by changing text color to red
+ if (DEVELOPMENT) {
+ console.error(err);
+ }
this.filterInput.nativeElement.style.color = '#ff6666';
}
return;
- } else {
+ }
+ else {
value = value.toLowerCase();
toLowerCase = true;
}
@@ -515,10 +532,12 @@ export class ChatLog implements AfterViewInit, OnDestroy, DoCheck {
if (typeof content === 'string') {
if (caseSensitive) {
lines[i].hidden = !textContent.toLowerCase().includes(content);
- } else {
+ }
+ else {
lines[i].hidden = !textContent.includes(content);
}
- } else {
+ }
+ else {
lines[i].hidden = !textContent.match(content);
}
}
@@ -534,18 +553,27 @@ export class ChatLog implements AfterViewInit, OnDestroy, DoCheck {
if (hsl.l < 40) {
if (hsl.l > 20 && hsl.l < 40) {
hsl.l += 20;
- if (hsl.s > 11) hsl.s -= 11;
- } else {
+ if (hsl.s > 11) {
+ hsl.s -= 11;
+ }
+ }
+ else {
hsl.l = 40;
- if (hsl.s > 11) hsl.s = 0;
+ if (hsl.s > 11) {
+ hsl.s = 0;
+ }
}
}
return hsl;
}
private getCharacterColors(id: number | undefined) {
- if (!id) return;
+ if (!id) {
+ return;
+ }
const entity = findEntityById(this.game.map, id) as Pony;
- if (!entity || !entity.palettePonyInfo) return;
+ if (!entity || !entity.palettePonyInfo) {
+ return;
+ }
let colors = [];
let { body, mane } = entity.palettePonyInfo;
if (body && body.palette && body.palette.colors[1]) {
@@ -559,29 +587,36 @@ export class ChatLog implements AfterViewInit, OnDestroy, DoCheck {
const hsl = rgb2hsl(rgb);
this.brightenDarkColors(hsl);
colors.push(hsl2CSS(hsl));
- } else if (colors && colors[0]) {
+ }
+ else if (colors && colors[0]) {
colors.push((colors[0]));
}
return colors;
}
clearTimeOutAutoClear() {
- if (this.autoClear) clearTimeout(this.autoClear);
+ if (this.autoClear) {
+ clearTimeout(this.autoClear);
+ }
this.autoClear = undefined;
this.filterColor = this.inactiveBg;
}
clearTimeOutAutoUnfocus() {
- if (this.autoUnfocus) clearTimeout(this.autoUnfocus);
+ if (this.autoUnfocus) {
+ clearTimeout(this.autoUnfocus);
+ }
this.autoUnfocus = undefined;
}
focus() {
this.clearTimeOutAutoUnfocus();
- if (this.filterInput.nativeElement)
+ if (this.filterInput.nativeElement) {
this.filterInput.nativeElement.focus();
+ }
}
unFocus() {
this.clearTimeOutAutoUnfocus();
- if (this.filterInput.nativeElement)
+ if (this.filterInput.nativeElement) {
this.filterInput.nativeElement.blur();
+ }
}
addMessage(message: ChatMessage) {
if (message.name && message.message) {
@@ -681,10 +716,12 @@ export class ChatLog implements AfterViewInit, OnDestroy, DoCheck {
tab.classList.add('active');
tab.classList.remove('unread');
tab.style.backgroundColor = this.bg;
- } else {
+ }
+ else {
tab.classList.remove('active');
- if (!tab.classList.contains('unread'))
+ if (!tab.classList.contains('unread')) {
tab.style.backgroundColor = this.inactiveBg;
+ }
}
}
scrollToEnd() {
@@ -762,7 +799,8 @@ export class ChatLog implements AfterViewInit, OnDestroy, DoCheck {
if (value) {
count.textContent = value > 99 ? '99+' : `${value}`;
toggle.classList.add('has-unread');
- } else {
+ }
+ else {
count.textContent = '';
toggle.classList.remove('has-unread');
}
diff --git a/src/ts/components/shared/color-picker/color-picker.ts b/src/ts/components/shared/color-picker/color-picker.ts
index d3218d0..748b438 100644
--- a/src/ts/components/shared/color-picker/color-picker.ts
+++ b/src/ts/components/shared/color-picker/color-picker.ts
@@ -119,7 +119,8 @@ export class ColorPicker {
if (!this.isDisabled) {
if (this.isOpen) {
this.close();
- } else {
+ }
+ else {
this.open();
}
}
diff --git a/src/ts/components/shared/date-picker/date-picker.ts b/src/ts/components/shared/date-picker/date-picker.ts
index 57ce249..067cdfb 100644
--- a/src/ts/components/shared/date-picker/date-picker.ts
+++ b/src/ts/components/shared/date-picker/date-picker.ts
@@ -51,7 +51,8 @@ function getMonthNames() {
date.setMonth(i);
return format.format(date);
});
- } catch {
+ }
+ catch {
return MONTH_NAMES_EN;
}
}
diff --git a/src/ts/components/shared/directives/agDrag.ts b/src/ts/components/shared/directives/agDrag.ts
index 32c46b3..f2fb70c 100644
--- a/src/ts/components/shared/directives/agDrag.ts
+++ b/src/ts/components/shared/directives/agDrag.ts
@@ -89,7 +89,9 @@ export function handleDrag(element: HTMLElement, emit: (event: AgDragEvent) => v
send(lastEvent, 'end');
window.removeEventListener(events.move, move);
window.removeEventListener(events.up, up);
- events.up2 && window.removeEventListener(events.up2, up);
+ if (events.up2) {
+ window.removeEventListener(events.up2, up);
+ }
window.removeEventListener('blur', end);
dragging = false;
}
@@ -106,7 +108,9 @@ export function handleDrag(element: HTMLElement, emit: (event: AgDragEvent) => v
window.addEventListener(events.move, move);
window.addEventListener(events.up, up);
- events.up2 && window.addEventListener(events.up2, up);
+ if (events.up2) {
+ window.addEventListener(events.up2, up);
+ }
window.addEventListener('blur', end);
e.stopPropagation();
diff --git a/src/ts/components/shared/directives/draggable.ts b/src/ts/components/shared/directives/draggable.ts
index 29022b7..eac0643 100644
--- a/src/ts/components/shared/directives/draggable.ts
+++ b/src/ts/components/shared/directives/draggable.ts
@@ -106,7 +106,8 @@ export class DraggableDrop implements OnInit, OnDestroy {
if (active) {
element.classList.add('draggable-hover');
- } else {
+ }
+ else {
element.classList.remove('draggable-hover');
}
}
@@ -185,7 +186,9 @@ export class DraggableItem implements OnInit, OnDestroy {
for (let i = 0; i < src.length; i++) {
const context = dst.item(i).getContext('2d');
- context && context.drawImage(src.item(i), 0, 0);
+ if (context) {
+ context.drawImage(src.item(i), 0, 0);
+ }
}
this.service.startMove(this.draggable, this.item!);
@@ -197,7 +200,8 @@ export class DraggableItem implements OnInit, OnDestroy {
this.draggable!.parentNode!.removeChild(this.draggable!);
this.draggable = undefined;
this.service.endMove();
- } else {
+ }
+ else {
const x = clamp(this.startX + e.dx, 0, window.innerWidth - this.width);
const y = clamp(this.startY + e.dy, 0, window.innerHeight - this.height);
setTransform(this.draggable, `translate3d(${x}px, ${y}px, 0px)`);
diff --git a/src/ts/components/shared/directives/dropdown.ts b/src/ts/components/shared/directives/dropdown.ts
index 4b64f41..b5b2b8a 100644
--- a/src/ts/components/shared/directives/dropdown.ts
+++ b/src/ts/components/shared/directives/dropdown.ts
@@ -45,7 +45,8 @@ export class DropdownMenu {
if (!this.ref) {
if (useOutlet) {
this.ref = this.service.viewContainer!.createEmbeddedView(this.templateRef);
- } else {
+ }
+ else {
this.ref = this.viewContainer.createEmbeddedView(this.templateRef);
}
@@ -63,7 +64,8 @@ export class DropdownMenu {
if ((rect.bottom + menuRect.height) > window.innerHeight) {
transform = `translate3d(${Math.round(rect.left)}px, ${Math.round(rect.top - menuRect.height)}px, 0)`;
renderer.addClass(root, 'dropdown-menu-up');
- } else {
+ }
+ else {
transform = `translate3d(${Math.round(rect.left)}px, ${Math.round(rect.bottom)}px, 0)`;
renderer.removeClass(root, 'dropdown-menu-up');
}
@@ -184,7 +186,8 @@ export class Dropdown {
toggle() {
if (this.isOpen) {
this.close();
- } else {
+ }
+ else {
this.open();
}
}
@@ -196,7 +199,8 @@ export class Dropdown {
&& !(this.autoClose === 'outsideClick' && this.menu.checkTarget(e))
) {
this.close();
- } else if (this.autoClose && e.keyCode === 27) { // esc
+ }
+ else if (this.autoClose && e.keyCode === 27) { // esc
this.close();
}
};
diff --git a/src/ts/components/shared/directives/focusTrap.ts b/src/ts/components/shared/directives/focusTrap.ts
index 6057903..05cb05c 100644
--- a/src/ts/components/shared/directives/focusTrap.ts
+++ b/src/ts/components/shared/directives/focusTrap.ts
@@ -32,7 +32,8 @@ export class FocusTrap implements OnInit, OnDestroy {
if (!isParentOf(this.element.nativeElement, this.lastActiveElement)) {
setTimeout(() => this.lastActiveElement = focusFirstElement(this.element.nativeElement));
}
- } else {
+ }
+ else {
this.lastActiveElement = undefined;
document.removeEventListener('focusin', this.focus);
}
@@ -41,13 +42,15 @@ export class FocusTrap implements OnInit, OnDestroy {
private focus = (e: Event) => {
if (isParentOf(this.element.nativeElement, e.target as any)) {
this.lastActiveElement = e.target as any;
- } else {
+ }
+ else {
const focusable = findFocusableElements(this.element.nativeElement);
if (focusable.length) {
if (this.lastActiveElement === focusable[0]) {
this.lastActiveElement = focusable[focusable.length - 1];
- } else {
+ }
+ else {
this.lastActiveElement = focusable[0];
}
diff --git a/src/ts/components/shared/directives/hasFeature.ts b/src/ts/components/shared/directives/hasFeature.ts
index 7ca3cc2..45f52ba 100644
--- a/src/ts/components/shared/directives/hasFeature.ts
+++ b/src/ts/components/shared/directives/hasFeature.ts
@@ -52,7 +52,8 @@ export class HasFeature implements AfterViewInit, OnDestroy {
if (show) {
this.ref = this.ref || this.viewContainer.createEmbeddedView(this.templateRef);
- } else {
+ }
+ else {
this.viewContainer.clear();
this.ref = undefined;
}
diff --git a/src/ts/components/shared/discord-pony/discord-pony.ts b/src/ts/components/shared/discord-pony/discord-pony.ts
index 43b8902..ab15b3b 100644
--- a/src/ts/components/shared/discord-pony/discord-pony.ts
+++ b/src/ts/components/shared/discord-pony/discord-pony.ts
@@ -67,18 +67,21 @@ export class DiscordPony implements OnInit, OnDestroy {
this.state.headAnimation = undefined;
this.state.headAnimationFrame = 0;
this.characterPreview.blink();
- } else {
+ }
+ else {
this.state.headAnimation = this.headAnimation;
this.state.headAnimationFrame = frame % this.headAnimation.frames.length;
}
- } else {
+ }
+ else {
this.state.headAnimation = undefined;
if (this.expression) {
if (Math.random() < 0.01) {
this.expression = undefined;
}
- } else {
+ }
+ else {
if (Math.random() < 0.005) {
this.expression = BLEP;
}
diff --git a/src/ts/components/shared/emote-box/emote-box.ts b/src/ts/components/shared/emote-box/emote-box.ts
index 7b531f1..64ca03d 100644
--- a/src/ts/components/shared/emote-box/emote-box.ts
+++ b/src/ts/components/shared/emote-box/emote-box.ts
@@ -70,7 +70,8 @@ export class EmoteBox implements AfterViewInit {
image.alt = emote ? emote.symbol : '';
image.style.visibility = 'visible';
});
- } else {
+ }
+ else {
image.style.width = `0px`;
image.style.height = `0px`;
image.src = '';
diff --git a/src/ts/components/shared/party-list/party-list.ts b/src/ts/components/shared/party-list/party-list.ts
index c41a893..cd7edbc 100644
--- a/src/ts/components/shared/party-list/party-list.ts
+++ b/src/ts/components/shared/party-list/party-list.ts
@@ -49,7 +49,9 @@ export class PartyList implements OnInit, OnDestroy {
this.resized();
}
ngOnDestroy() {
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
}
isMe(member: PartyMember) {
return this.game.player && this.game.player.id === member.id;
@@ -64,7 +66,8 @@ export class PartyList implements OnInit, OnDestroy {
while (this.start > 0 && this.members.length <= this.start) {
this.start = 0;
}
- } else {
+ }
+ else {
this.members = [];
this.start = 0;
}
diff --git a/src/ts/components/shared/play-box/play-box.ts b/src/ts/components/shared/play-box/play-box.ts
index 11b121e..c1ae16e 100644
--- a/src/ts/components/shared/play-box/play-box.ts
+++ b/src/ts/components/shared/play-box/play-box.ts
@@ -146,7 +146,9 @@ export class PlayBox implements OnInit {
this.errorReporter.reportError(e, { status: e.status, text: e.text });
}
- DEVELOPMENT && console.error(e);
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
}
})
.finally(() => this.joining = false)
diff --git a/src/ts/components/shared/set-selection/set-selection.ts b/src/ts/components/shared/set-selection/set-selection.ts
index a417edb..0c3bbe7 100644
--- a/src/ts/components/shared/set-selection/set-selection.ts
+++ b/src/ts/components/shared/set-selection/set-selection.ts
@@ -47,9 +47,11 @@ export class SetSelection implements OnChanges {
if (pat && !pat.colors) {
return 0;
- } else if (pat) {
+ }
+ else if (pat) {
return getColorCount(pat);
- } else {
+ }
+ else {
return this.nonLockable ? 1 : 0;
}
}
diff --git a/src/ts/components/shared/settings-box/settings-box.ts b/src/ts/components/shared/settings-box/settings-box.ts
index 3570327..95fb2ac 100644
--- a/src/ts/components/shared/settings-box/settings-box.ts
+++ b/src/ts/components/shared/settings-box/settings-box.ts
@@ -82,13 +82,16 @@ export class SettingsBox implements OnInit, OnDestroy {
.subscribe(text => {
if (this.dropdown.isOpen) {
this.zone.run(() => this.time = text);
- } else {
+ }
+ else {
this.time = text;
}
});
}
ngOnDestroy() {
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
}
toggleVolume() {
this.volume = this.volume === 0 ? 50 : 0;
diff --git a/src/ts/components/shared/settings-modal/settings-modal.ts b/src/ts/components/shared/settings-modal/settings-modal.ts
index 774b050..12cdbe6 100644
--- a/src/ts/components/shared/settings-modal/settings-modal.ts
+++ b/src/ts/components/shared/settings-modal/settings-modal.ts
@@ -102,7 +102,9 @@ export class SettingsModal implements OnInit, OnDestroy {
this.cancel();
}
- this.subscription && this.subscription.unsubscribe();
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
}
reset() {
this.account = this.settingsService.account = {};
@@ -125,7 +127,8 @@ export class SettingsModal implements OnInit, OnDestroy {
if (filter.length > MAX_FILTER_WORDS_LENGTH) {
this.account.filterWords = '';
- } else {
+ }
+ else {
this.account.filterWords = filter;
}
}
@@ -136,9 +139,15 @@ export class SettingsModal implements OnInit, OnDestroy {
this.close.emit();
}
switchTimestamp(state?: string) {
- if (!state) this.browser.timestamp = undefined;
- else if (state === '12') this.browser.timestamp = '12';
- else if (state === '24') this.browser.timestamp = '24';
+ if (!state) {
+ this.browser.timestamp = undefined;
+ }
+ else if (state === '12') {
+ this.browser.timestamp = '12';
+ }
+ else if (state === '24') {
+ this.browser.timestamp = '24';
+ }
}
updateChatlogRange(range: number | undefined) {
document.body.classList.add('translucent-modals');
diff --git a/src/ts/components/shared/slider-bar/slider-bar.ts b/src/ts/components/shared/slider-bar/slider-bar.ts
index d684eff..4f35fe8 100644
--- a/src/ts/components/shared/slider-bar/slider-bar.ts
+++ b/src/ts/components/shared/slider-bar/slider-bar.ts
@@ -35,8 +35,9 @@ export class SliderBar {
return clamp(((this.value - this.min) / (this.max - this.min)) * 100, 0, 100);
}
drag({ type, x, event }: AgDragEvent) {
- if (this.disabled)
+ if (this.disabled) {
return;
+ }
event.preventDefault();
@@ -58,21 +59,25 @@ export class SliderBar {
}
@HostListener('keydown', ['$event'])
keydown(e: KeyboardEvent) {
- if (this.disabled)
+ if (this.disabled) {
return;
+ }
const step = this.step || 1;
if (e.keyCode === Key.LEFT || e.keyCode === Key.DOWN || e.keyCode === Key.PAGE_DOWN) {
e.preventDefault();
this.setValue(this.value - step * (e.keyCode === Key.PAGE_DOWN ? this.largeStep : 1), true);
- } else if (e.keyCode === Key.RIGHT || e.keyCode === Key.UP || e.keyCode === Key.PAGE_UP) {
+ }
+ else if (e.keyCode === Key.RIGHT || e.keyCode === Key.UP || e.keyCode === Key.PAGE_UP) {
e.preventDefault();
this.setValue(this.value + step * (e.keyCode === Key.PAGE_UP ? this.largeStep : 1), true);
- } else if (e.keyCode === Key.HOME) {
+ }
+ else if (e.keyCode === Key.HOME) {
e.preventDefault();
this.setValue(this.min, true);
- } else if (e.keyCode === Key.END) {
+ }
+ else if (e.keyCode === Key.END) {
e.preventDefault();
this.setValue(this.max, true);
}
diff --git a/src/ts/components/shared/sprite-box/sprite-box.ts b/src/ts/components/shared/sprite-box/sprite-box.ts
index 4299168..9a727e6 100644
--- a/src/ts/components/shared/sprite-box/sprite-box.ts
+++ b/src/ts/components/shared/sprite-box/sprite-box.ts
@@ -87,8 +87,9 @@ export class SpriteBox implements AfterViewInit, OnChanges, DoCheck {
const scale = this.scale;
const canvas = this.canvas.nativeElement as HTMLCanvasElement;
- if (!size || this.invisible)
+ if (!size || this.invisible) {
return;
+ }
if (canvas.width !== size || canvas.height !== size) {
canvas.width = size;
@@ -97,8 +98,9 @@ export class SpriteBox implements AfterViewInit, OnChanges, DoCheck {
const context = canvas.getContext('2d');
- if (!context)
+ if (!context) {
return;
+ }
context.save();
context.clearRect(0, 0, canvas.width, canvas.height);
@@ -149,7 +151,8 @@ export class SpriteBox implements AfterViewInit, OnChanges, DoCheck {
for (const color of sprite.colorMany) {
batch.drawSprite(color, WHITE, palette, x, y);
}
- } else {
+ }
+ else {
batch.drawSprite(sprite.color, WHITE, palette, x, y);
}
@@ -175,7 +178,8 @@ function addRect(rect: Rect, sprite: Sprite | undefined) {
rect.y = sprite.oy;
rect.w = sprite.w;
rect.h = sprite.h;
- } else {
+ }
+ else {
const x = Math.min(rect.x, sprite.ox);
const y = Math.min(rect.y, sprite.oy);
rect.w = Math.max(rect.x + rect.w, sprite.ox + sprite.w) - x;
diff --git a/src/ts/components/shared/sprite-selection/sprite-selection.ts b/src/ts/components/shared/sprite-selection/sprite-selection.ts
index 09cf7c1..a430caf 100644
--- a/src/ts/components/shared/sprite-selection/sprite-selection.ts
+++ b/src/ts/components/shared/sprite-selection/sprite-selection.ts
@@ -78,18 +78,23 @@ export class SpriteSelection {
if (keyCode === Key.RIGHT || keyCode === Key.DOWN) {
if (this.selected >= (this.sprites.length - 1)) {
return this.skip;
- } else {
+ }
+ else {
return this.selected + 1;
}
- } else if (keyCode === Key.LEFT || keyCode === Key.UP) {
+ }
+ else if (keyCode === Key.LEFT || keyCode === Key.UP) {
if (this.selected <= this.skip) {
return this.sprites.length - 1;
- } else {
+ }
+ else {
return this.selected - 1;
}
- } else if (keyCode === Key.HOME) {
+ }
+ else if (keyCode === Key.HOME) {
return this.skip;
- } else if (keyCode === Key.END) {
+ }
+ else if (keyCode === Key.END) {
return this.sprites.length - 1;
}
}
diff --git a/src/ts/components/shared/swap-box/swap-box.ts b/src/ts/components/shared/swap-box/swap-box.ts
index 3fa5b53..ae1299a 100644
--- a/src/ts/components/shared/swap-box/swap-box.ts
+++ b/src/ts/components/shared/swap-box/swap-box.ts
@@ -28,7 +28,9 @@ export class SwapBox {
swapPony(pony: PonyObject) {
this.game.send(server => server.actionParam(Action.SwapCharacter, pony.id));
setTimeout(() => {
- this.dropdown && this.dropdown.close();
+ if (this.dropdown) {
+ this.dropdown.close();
+ }
pony.lastUsed = (new Date()).toISOString();
this.model.sortPonies();
});
diff --git a/src/ts/components/shared/tabset/tabset.ts b/src/ts/components/shared/tabset/tabset.ts
index 71bf642..f9f0e50 100644
--- a/src/ts/components/shared/tabset/tabset.ts
+++ b/src/ts/components/shared/tabset/tabset.ts
@@ -49,7 +49,8 @@ export class Tabset {
set justify(className: 'start' | 'center' | 'end' | 'fill' | 'justified') {
if (className === 'fill' || className === 'justified') {
this.justifyClass = `nav-${className}`;
- } else {
+ }
+ else {
this.justifyClass = `justify-content-${className}`;
}
}
@@ -75,20 +76,26 @@ export class Tabset {
if (index !== undefined) {
e.preventDefault();
const element = document.getElementById(this.tabs.toArray()[index].id);
- element && element.focus();
+ if (element) {
+ element.focus();
+ }
this.select(index);
}
}
private handleKey(keyCode: number) {
if (keyCode === Key.LEFT) {
return this.activeIndex === 0 ? this.tabs.length - 1 : this.activeIndex - 1;
- } else if (keyCode === Key.RIGHT) {
+ }
+ else if (keyCode === Key.RIGHT) {
return this.activeIndex === this.tabs.length - 1 ? 0 : this.activeIndex + 1;
- } else if (keyCode === Key.HOME) {
+ }
+ else if (keyCode === Key.HOME) {
return 0;
- } else if (keyCode === Key.END) {
+ }
+ else if (keyCode === Key.END) {
return this.tabs.length - 1;
- } else {
+ }
+ else {
return undefined;
}
}
diff --git a/src/ts/components/shared/virtual-list/virtual-list.ts b/src/ts/components/shared/virtual-list/virtual-list.ts
index fc67147..ebf0fab 100644
--- a/src/ts/components/shared/virtual-list/virtual-list.ts
+++ b/src/ts/components/shared/virtual-list/virtual-list.ts
@@ -77,7 +77,8 @@ export class VirtualFor implements DoCheck, OnDestroy, AfterViewInit {
if (!this.differ && value) {
try {
this.differ = this.differs.find(value).create();
- } catch {
+ }
+ catch {
throw new Error(`Cannot find a differ`);
}
}
@@ -130,7 +131,8 @@ export class VirtualFor implements DoCheck, OnDestroy, AfterViewInit {
view.context.$implicit = null!;
view.context._currentIndex = index;
viewContainer.insert(view, i);
- } else {
+ }
+ else {
const context: Context = { $implicit: null!, index: -1, count: -1, _currentIndex: index };
view = viewContainer.createEmbeddedView(this.template, context, i);
}
diff --git a/src/ts/components/shared/visit-pt-pony/visit-pt-pony.ts b/src/ts/components/shared/visit-pt-pony/visit-pt-pony.ts
index 3d4909a..8051797 100644
--- a/src/ts/components/shared/visit-pt-pony/visit-pt-pony.ts
+++ b/src/ts/components/shared/visit-pt-pony/visit-pt-pony.ts
@@ -1,3 +1,4 @@
+/* eslint-disable camelcase */
import { Component, OnInit, OnDestroy, Input, ViewChild, ChangeDetectionStrategy } from '@angular/core';
import { defaultExpression } from '../../../common/ponyUtils';
import { defaultPonyState } from '../../../common/ponyHelpers';
@@ -81,18 +82,21 @@ export class VisitPTPony implements OnInit, OnDestroy {
this.state.headAnimation = undefined;
this.state.headAnimationFrame = 0;
this.characterPreview.blink();
- } else {
+ }
+ else {
this.state.headAnimation = this.headAnimation;
this.state.headAnimationFrame = frame % this.headAnimation.frames.length;
}
- } else {
+ }
+ else {
this.state.headAnimation = undefined;
if (this.expression) {
if (Math.random() < 0.01) {
this.expression = undefined;
}
- } else {
+ }
+ else {
if (Math.random() < 0.005) {
this.expression = BLEP;
}
@@ -106,7 +110,8 @@ export class VisitPTPony implements OnInit, OnDestroy {
this.bodyAnimation = undefined;
this.state.animation = stand;
this.state.animationFrame = 0;
- } else {
+ }
+ else {
this.state.animation = this.bodyAnimation;
this.state.animationFrame = frame % this.bodyAnimation.frames.length;
}
diff --git a/src/ts/components/tools/shared/tools-frame/tools-frame.ts b/src/ts/components/tools/shared/tools-frame/tools-frame.ts
index b169cc4..ec446cc 100644
--- a/src/ts/components/tools/shared/tools-frame/tools-frame.ts
+++ b/src/ts/components/tools/shared/tools-frame/tools-frame.ts
@@ -42,6 +42,7 @@ export class ToolsFrame {
openedPopover.popoverIsOpen = false;
}
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
openedPopover = this;
}
@@ -50,7 +51,8 @@ export class ToolsFrame {
if (this.popoverIsOpen) {
this.selected = false;
window.addEventListener('mousedown', this.closePopover);
- } else {
+ }
+ else {
window.removeEventListener('mousedown', this.closePopover);
}
diff --git a/src/ts/components/tools/sheetExport.ts b/src/ts/components/tools/sheetExport.ts
index 1182003..bf65b0f 100644
--- a/src/ts/components/tools/sheetExport.ts
+++ b/src/ts/components/tools/sheetExport.ts
@@ -43,7 +43,8 @@ function getSets(sheet: Sheet, key: string, override?: string): Sets | undefined
if (sheet.duplicateFirstFrame !== undefined) {
return times(sheet.duplicateFirstFrame, () => sets[0]);
- } else {
+ }
+ else {
return sheet.single ? [sets] : sets;
}
}
@@ -60,7 +61,8 @@ export function getCols(sheet: Sheet) {
export function getRows(sheet: Sheet) {
if (sheet.rows !== undefined) {
return sheet.rows;
- } else {
+ }
+ else {
const sets = getSetsForFirstKey(sheet);
const maxFrames = sets && max(sets.map(f => f ? f.length : 0));
return (maxFrames || 0) + 1;
@@ -117,7 +119,8 @@ function drawPsdLayer(
pony.head = ignoreSet();
pony.nose = ignoreSet();
pony.ears = ignoreSet();
- } else if (layer.noFace) {
+ }
+ else if (layer.noFace) {
baseState.headAnimation = createHeadAnimation('', 1, false, [[]]);
pony.head = ignoreSet();
pony.nose = ignoreSet();
@@ -143,7 +146,9 @@ function drawPsdLayer(
options.no = setFlag(options.no, NoDraw.BackFarLeg, true);
}
- layer.setup && layer.setup(pony, baseState);
+ if (layer.setup) {
+ layer.setup(pony, baseState);
+ }
syncLockedPonyInfoNumber(pony);
@@ -159,8 +164,12 @@ function drawPsdLayer(
const state = cloneDeep(baseState);
- sheet.frame && sheet.frame(pony, state, options, xIndex, yIndex, pattern);
- layer.frame && layer.frame(pony, state, options, xIndex, yIndex, pattern);
+ if (sheet.frame) {
+ sheet.frame(pony, state, options, xIndex, yIndex, pattern);
+ }
+ if (layer.frame) {
+ layer.frame(pony, state, options, xIndex, yIndex, pattern);
+ }
state.animationFrame = xIndex;
@@ -183,10 +192,12 @@ function drawPsdLayer(
if (aframe && typeIndex < aframe.length && aframe[typeIndex] && pattern < aframe[typeIndex]!.length) {
set.pattern = pattern;
- } else {
+ }
+ else {
set.type = -1;
}
- } else {
+ }
+ else {
set.fills = whiteColors;
set.outlines = whiteColors;
@@ -195,7 +206,9 @@ function drawPsdLayer(
}
}
- layer.frameSet && layer.frameSet(set, xIndex, yIndex, pattern);
+ if (layer.frameSet) {
+ layer.frameSet(set, xIndex, yIndex, pattern);
+ }
(pony as any)[fieldName] = set.type === -1 ? ignoreSet() : set;
}
@@ -210,7 +223,8 @@ function drawPsdLayer(
if (extra) {
set.palette = mockPaletteManager.add([0, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK]);
- } else {
+ }
+ else {
set.extraPalette = undefined;
}
}
@@ -247,7 +261,8 @@ function createPsdLayer(sheet: Sheet, rows: number, cols: number, layer: SheetLa
if (layer.set) {
return { name, children: createPsdPatternLayers(sheet, rows, cols, layer) };
- } else {
+ }
+ else {
return { name, canvas: drawPsdLayer(sheet, rows, cols, layer) };
}
}
@@ -352,7 +367,11 @@ export function drawPsd(psd: Psd, scale: number, canvas?: HTMLCanvasElement): HT
function drawLayer(layer: Layer, context: CanvasRenderingContext2D) {
if (!layer.hidden) {
- layer.canvas && context.drawImage(layer.canvas, 0, 0);
- layer.children && layer.children.forEach(c => drawLayer(c, context));
+ if (layer.canvas) {
+ context.drawImage(layer.canvas, 0, 0);
+ }
+ if (layer.children) {
+ layer.children.forEach(c => drawLayer(c, context));
+ }
}
}
diff --git a/src/ts/components/tools/tools-animation/tools-animation.ts b/src/ts/components/tools/tools-animation/tools-animation.ts
index 4fb7171..21867fb 100644
--- a/src/ts/components/tools/tools-animation/tools-animation.ts
+++ b/src/ts/components/tools/tools-animation/tools-animation.ts
@@ -213,7 +213,8 @@ export class ToolsAnimation implements OnInit, OnDestroy {
headFrame = Math.min(headFrame, headFrames - 1);
this.state.headAnimationFrame = headFrame;
}
- } else {
+ }
+ else {
this.state.headAnimationFrame = this.frame;
}
}
@@ -301,7 +302,8 @@ export class ToolsAnimation implements OnInit, OnDestroy {
.subscribe(({ type, animation }) => {
if (type === 'body') {
this.bodyAnimations.push(animation);
- } else {
+ }
+ else {
this.headAnimations.push(animation);
}
@@ -312,7 +314,8 @@ export class ToolsAnimation implements OnInit, OnDestroy {
private createAnimation(): BodyAnimation | HeadAnimation {
if (this.mode === 'body') {
return { name: 'new animation', loop: true, fps: 24, frames: [createDefaultBodyFrame()] };
- } else {
+ }
+ else {
return { name: 'new animation', loop: true, fps: 24, frames: [createDefaultHeadFrame()] };
}
}
@@ -341,7 +344,8 @@ export class ToolsAnimation implements OnInit, OnDestroy {
selectAnimation(animation: BodyAnimation | HeadAnimation) {
if (this.mode === 'body') {
this.selectBodyAnimation(animation as BodyAnimation);
- } else {
+ }
+ else {
this.selectHeadAnimation(animation as HeadAnimation);
}
}
@@ -435,11 +439,14 @@ export class ToolsAnimation implements OnInit, OnDestroy {
handleKey(keyCode: number) {
if (keyCode === Key.OPEN_BRACKET || keyCode === Key.LEFT || keyCode === Key.COMMA) {
this.prevFrame();
- } else if (keyCode === Key.CLOSE_BRACKET || keyCode === Key.RIGHT || keyCode === Key.PERIOD) {
+ }
+ else if (keyCode === Key.CLOSE_BRACKET || keyCode === Key.RIGHT || keyCode === Key.PERIOD) {
this.nextFrame();
- } else if (keyCode === Key.ENTER) {
+ }
+ else if (keyCode === Key.ENTER) {
this.playing = !this.playing;
- } else {
+ }
+ else {
return false;
}
@@ -470,7 +477,8 @@ export class ToolsAnimation implements OnInit, OnDestroy {
const shadow = this.bodyAnimation.frames.map(f => [f.shadowFrame, f.shadowOffset]);
console.log(`shadow: [${shadow.map(x => `[${x.join(', ')}]`).join(', ')}]`);
}
- } else {
+ }
+ else {
const frames = this.headAnimation.frames
.map(f => [f.duration, '[' + compressHeadFrame(f).join(', ') + ']'])
.map(([repeat, frame]) => parseInt(`${repeat}`, 10) > 1 ? `...repeat(${repeat}, ${frame})` : frame);
@@ -555,7 +563,8 @@ export class ToolsAnimation implements OnInit, OnDestroy {
this.state.animation = this.bodyAnimationsToPlay[this.bodyAnimationPlaying];
this.state.animationFrame = 0;
this.time = 0;
- } else {
+ }
+ else {
this.state.animationFrame = frame % this.state.animation.frames.length;
}
}
@@ -657,7 +666,8 @@ function fromBodyAnimation({ name, frames, fps, loop, shadow }: IBodyAnimation,
&& l.wing === f.wing
) {
l.duration++;
- } else {
+ }
+ else {
fs.push({
duration: 1,
...f,
@@ -731,7 +741,8 @@ function fromHeadAnimation({ name, fps, loop, properties, frames }: IHeadAnimati
if (l && l.headX === f.headX && l.headY === f.headY && l.left === f.left && l.right === f.right && l.mouth === f.mouth) {
l.duration++;
- } else {
+ }
+ else {
fs.push({ duration: 1, ...f });
}
});
diff --git a/src/ts/components/tools/tools-chat/tools-chat.ts b/src/ts/components/tools/tools-chat/tools-chat.ts
index 555983e..1fa0a02 100644
--- a/src/ts/components/tools/tools-chat/tools-chat.ts
+++ b/src/ts/components/tools/tools-chat/tools-chat.ts
@@ -97,8 +97,9 @@ export class ToolsChat implements AfterViewInit {
this.redraw();
}
redraw() {
- if (!this.initialized)
+ if (!this.initialized) {
return;
+ }
const canvas1 = drawCanvas(500, 400, sprites.paletteSpriteSheet, undefined, batch => {
const palettes = createCommonPalettes(mockPaletteManager);
@@ -162,7 +163,7 @@ export class ToolsChat implements AfterViewInit {
});
const canvas3 = drawCanvas(500, 400, sprites.paletteSpriteSheet, undefined, batch => {
- /* tslint:disable */
+ // eslint-disable-next-line max-len
const loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce scelerisque interdum scelerisque. Suspendisse malesuada, enim in viverra ornare, dui ex laoreet ipsum, at mollis orci felis vitae ipsum. In faucibus venenatis augue, ac ornare libero. Etiam vitae aliquet neque.';
const text = lineBreak(loremIpsum, fontPal, 200);
diff --git a/src/ts/components/tools/tools-collisions/tools-collisions.ts b/src/ts/components/tools/tools-collisions/tools-collisions.ts
index 0facdee..5123d21 100644
--- a/src/ts/components/tools/tools-collisions/tools-collisions.ts
+++ b/src/ts/components/tools/tools-collisions/tools-collisions.ts
@@ -118,10 +118,12 @@ export class ToolsCollisions implements OnInit {
if (shiftKey) {
if (Math.abs(dx) > Math.abs(dy)) {
this.target = toWorld({ x, y: toScreenY(this.start.y) });
- } else {
+ }
+ else {
this.target = toWorld({ x: toScreenX(this.start.x), y });
}
- } else {
+ }
+ else {
this.target = toWorld({ x, y });
}
@@ -146,7 +148,8 @@ export class ToolsCollisions implements OnInit {
this.steps.push(collision);
current.x = collision.x;
current.y = collision.y;
- } else {
+ }
+ else {
this.steps.push(point(this.target.x, this.target.y));
}
@@ -156,19 +159,22 @@ export class ToolsCollisions implements OnInit {
if (steps <= 0) {
console.error('Failed');
}
- } else {
+ }
+ else {
const collision = getClosestCollisionOld(this.start, this.target, this.rects);
if (equal(this.target, collision)) {
this.deflection = { ...this.target };
- } else {
+ }
+ else {
const coll = getClosestCollisionOld(collision, this.target, this.rects);
if (equal(collision, coll)) {
const horizontal = getClosestCollisionOld(collision, { x: this.target.x, y: collision.y }, this.rects);
const vertical = getClosestCollisionOld(collision, { x: collision.x, y: this.target.y }, this.rects);
this.deflection = equal(collision, horizontal) ? vertical : horizontal;
- } else {
+ }
+ else {
console.log('not', collision, coll);
}
}
@@ -214,13 +220,15 @@ export class ToolsCollisions implements OnInit {
if (ay < (y + 1)) {
x++;
- } else {
+ }
+ else {
y++;
}
checkedTiles.add(`${x}-${y}`);
}
- } else {
+ }
+ else {
while (--steps && (x !== x1 || y !== y1)) {
const dx = (x + 1) - srcX;
const dy = dx * DYbyDX;
@@ -228,7 +236,8 @@ export class ToolsCollisions implements OnInit {
if (ay >= y) {
x++;
- } else {
+ }
+ else {
y--;
}
@@ -441,12 +450,14 @@ function getCollisionTest({ x, y }: Point, b: Point, r: Rect): Point | undefined
if (q[i] < 0) {
return undefined;
}
- } else {
+ }
+ else {
const t = q[i] / p[i];
if (p[i] < 0 && u1 < t) {
u1 = t;
- } else if (p[i] > 0 && u2 > t) {
+ }
+ else if (p[i] > 0 && u2 > t) {
u2 = t;
}
}
@@ -523,24 +534,29 @@ function checkInLine(srcX: number, srcY: number, dstX: number, dstY: number, col
oy = 1;
stepYT = 1 | 0;
stepXF = 1 | 0;
- } else {
+ }
+ else {
ox = 1;
stepYT = -1 | 0;
stepXF = 1 | 0;
}
- } else if (srcX > dstX) {
+ }
+ else if (srcX > dstX) {
if (srcY < dstY) {
oy = 1;
stepYT = 1 | 0;
stepXF = -1 | 0;
- } else {
+ }
+ else {
stepYT = -1 | 0;
stepXF = -1 | 0;
}
- } else {
+ }
+ else {
if (srcY < dstY) {
stepYF = stepYT = 1 | 0;
- } else {
+ }
+ else {
stepYF = stepYT = -1 | 0;
}
}
@@ -555,7 +571,8 @@ function checkInLine(srcX: number, srcY: number, dstX: number, dstY: number, col
if (useGt ? (fx > fy) : (fx < fy)) {
tx = (tx + stepXT) | 0;
ty = (ty + stepYT) | 0;
- } else {
+ }
+ else {
tx = (tx + stepXF) | 0;
ty = (ty + stepYF) | 0;
}
@@ -583,17 +600,20 @@ function checkInLine(srcX: number, srcY: number, dstX: number, dstY: number, col
actualNY -= 1;
dstY -= 1;
collides = false;
- } else if (shiftDown && (canShiftDown = !isColliding(actualX, actualY + 1)) && !isColliding(actualNX, actualY + 1)) {
+ }
+ else if (shiftDown && (canShiftDown = !isColliding(actualX, actualY + 1)) && !isColliding(actualNX, actualY + 1)) {
actualNX = actualX;
actualNY += 1;
dstY += 1;
collides = false;
- } else if (shiftUp && canShiftUp && !isColliding(actualNX, actualY - 2)) {
+ }
+ else if (shiftUp && canShiftUp && !isColliding(actualNX, actualY - 2)) {
actualNX = actualX;
actualNY -= 1;
dstY -= 1;
collides = false;
- } else if (shiftDown && canShiftDown && !isColliding(actualNX, actualY + 2)) {
+ }
+ else if (shiftDown && canShiftDown && !isColliding(actualNX, actualY + 2)) {
actualNX = actualX;
actualNY += 1;
dstY += 1;
@@ -601,7 +621,8 @@ function checkInLine(srcX: number, srcY: number, dstX: number, dstY: number, col
}
canMove = canShiftUp || canShiftDown;
- } else {
+ }
+ else {
let canShiftLeft = false;
let canShiftRight = false;
@@ -610,17 +631,20 @@ function checkInLine(srcX: number, srcY: number, dstX: number, dstY: number, col
actualNY = actualY;
dstX -= 1;
collides = false;
- } else if (shiftRight && (canShiftRight = !isColliding(actualX + 1, actualY)) && !isColliding(actualX + 1, actualNY)) {
+ }
+ else if (shiftRight && (canShiftRight = !isColliding(actualX + 1, actualY)) && !isColliding(actualX + 1, actualNY)) {
actualNX += 1;
actualNY = actualY;
dstX += 1;
collides = false;
- } else if (shiftLeft && canShiftLeft && !isColliding(actualX - 2, actualNY)) {
+ }
+ else if (shiftLeft && canShiftLeft && !isColliding(actualX - 2, actualNY)) {
actualNX -= 1;
actualNY = actualY;
dstX -= 1;
collides = false;
- } else if (shiftRight && canShiftRight && !isColliding(actualX + 2, actualNY)) {
+ }
+ else if (shiftRight && canShiftRight && !isColliding(actualX + 2, actualNY)) {
actualNX += 1;
actualNY = actualY;
dstX += 1;
@@ -635,7 +659,8 @@ function checkInLine(srcX: number, srcY: number, dstX: number, dstY: number, col
actualX = actualNX;
actualY = actualNY;
checks.push({ x: actualX, y: actualY });
- } else if (!canMove || horizontalOrVertical) {
+ }
+ else if (!canMove || horizontalOrVertical) {
checks.push({ x: actualX, y: actualY, type: 'break' });
break;
}
@@ -705,12 +730,14 @@ function getCollision(
if (q < 0) {
return false;
}
- } else {
+ }
+ else {
const t = q / p;
if (p < 0 && u1 < t) {
u1 = t;
- } else if (p > 0 && u2 > t) {
+ }
+ else if (p > 0 && u2 > t) {
u2 = t;
}
}
@@ -724,12 +751,14 @@ function getCollision(
if (q < 0) {
return false;
}
- } else {
+ }
+ else {
const t = q / p;
if (p < 0 && u1 < t) {
u1 = t;
- } else if (p > 0 && u2 > t) {
+ }
+ else if (p > 0 && u2 > t) {
u2 = t;
}
}
@@ -743,12 +772,14 @@ function getCollision(
if (q < 0) {
return false;
}
- } else {
+ }
+ else {
const t = q / p;
if (p < 0 && u1 < t) {
u1 = t;
- } else if (p > 0 && u2 > t) {
+ }
+ else if (p > 0 && u2 > t) {
u2 = t;
}
}
@@ -762,12 +793,14 @@ function getCollision(
if (q < 0) {
return false;
}
- } else {
+ }
+ else {
const t = q / p;
if (p < 0 && u1 < t) {
u1 = t;
- } else if (p > 0 && u2 > t) {
+ }
+ else if (p > 0 && u2 > t) {
u2 = t;
}
}
diff --git a/src/ts/components/tools/tools-entity/tools-entity.ts b/src/ts/components/tools/tools-entity/tools-entity.ts
index 1d00da6..272f818 100644
--- a/src/ts/components/tools/tools-entity/tools-entity.ts
+++ b/src/ts/components/tools/tools-entity/tools-entity.ts
@@ -128,13 +128,17 @@ export class ToolsEntity implements OnInit {
handleKey(keyCode: number) {
if (keyCode === Key.UP) {
this.movePart(0, -1);
- } else if (keyCode === Key.DOWN) {
+ }
+ else if (keyCode === Key.DOWN) {
this.movePart(0, 1);
- } else if (keyCode === Key.LEFT) {
+ }
+ else if (keyCode === Key.LEFT) {
this.movePart(-1, 0);
- } else if (keyCode === Key.RIGHT) {
+ }
+ else if (keyCode === Key.RIGHT) {
this.movePart(1, 0);
- } else {
+ }
+ else {
return false;
}
@@ -149,7 +153,8 @@ export class ToolsEntity implements OnInit {
this.selectedPart = findLastIndex(this.parts, p => {
if (this.drawHold) {
return p.type === 'pickable';
- } else {
+ }
+ else {
const bounds = getBounds(p);
return !!bounds && containsPoint(0, 0, bounds, x, y);
}
@@ -176,7 +181,8 @@ export class ToolsEntity implements OnInit {
if (entity) {
this.name = entity.name;
this.parts = entity.parts;
- } else {
+ }
+ else {
this.name = '';
this.parts = [];
}
@@ -189,7 +195,8 @@ export class ToolsEntity implements OnInit {
if (existing) {
existing.parts = cloneDeep(this.parts);
- } else {
+ }
+ else {
this.entities.push({
name: this.name,
parts: cloneDeep(this.parts),
@@ -260,7 +267,8 @@ export class ToolsEntity implements OnInit {
const state = { ...defaultPonyState(), holding };
drawPony(batch, this.pony, state, X, Y, defaultDrawPonyOptions());
- } else {
+ }
+ else {
draw(batch);
}
});
@@ -344,7 +352,8 @@ function getBounds(part: Part): Rect | undefined {
h: color.h,
};
}
- } else if (part.type === 'cover' || part.type === 'collider') {
+ }
+ else if (part.type === 'cover' || part.type === 'collider') {
return part;
}
@@ -358,15 +367,20 @@ function getSprite(name: string): PaletteRenderable {
function drawSpritePart(batch: PaletteSpriteBatch, part: SpritePart, px: number, py: number) {
const sprite = getSprite(part.sprite);
- if (!sprite)
+ if (!sprite) {
return;
+ }
const x = px + part.x;
const y = py + part.y;
const palette = paletteManager.addArray(sprite.palettes![0]);
- sprite.shadow && batch.drawSprite(sprite.shadow, SHADOW_COLOR, defaultPalette, x, y);
- sprite.color && batch.drawSprite(sprite.color, WHITE, palette, x, y);
+ if (sprite.shadow) {
+ batch.drawSprite(sprite.shadow, SHADOW_COLOR, defaultPalette, x, y);
+ }
+ if (sprite.color) {
+ batch.drawSprite(sprite.color, WHITE, palette, x, y);
+ }
releasePalette(palette);
}
@@ -374,11 +388,14 @@ function drawSpritePart(batch: PaletteSpriteBatch, part: SpritePart, px: number,
function drawPart(batch: PaletteSpriteBatch, part: Part, x: number, y: number) {
if (part.type === 'sprite') {
return drawSpritePart(batch, part, x, y);
- } else if (part.type === 'cover' || part.type === 'collider') {
+ }
+ else if (part.type === 'cover' || part.type === 'collider') {
return drawOutline(batch, colors[part.type], part.x + x, part.y + y, part.w, part.h);
- } else if (part.type === 'pickable') {
+ }
+ else if (part.type === 'pickable') {
return drawOutline(batch, colors[part.type], part.x + x, part.y + y, 1, 1);
- } else {
+ }
+ else {
throw new Error(`Invalid part type (${(part as any).type})`);
}
}
@@ -395,8 +412,9 @@ function drawBufferScaled(canvas: HTMLCanvasElement, buffer: HTMLCanvasElement,
function drawMixin(sprite: PaletteRenderable, dx: number, dy: number, paletteIndex = 0): EntityPart {
const bounds = getRenderableBounds(sprite, dx, dy);
- if (SERVER && !TESTS)
+ if (SERVER && !TESTS) {
return { bounds };
+ }
const defaultPalette = sprite.shadow && createPalette(sprites.defaultPalette);
const palette = createPalette(att(sprite.palettes, paletteIndex));
diff --git a/src/ts/components/tools/tools-map/tools-map.ts b/src/ts/components/tools/tools-map/tools-map.ts
index 087b20b..2dda590 100644
--- a/src/ts/components/tools/tools-map/tools-map.ts
+++ b/src/ts/components/tools/tools-map/tools-map.ts
@@ -121,7 +121,8 @@ export class ToolsMap implements OnInit {
if (this.map && this.info) {
if (this.type === 'regular') {
drawTheMap(this.canvas.nativeElement, this.map, this.info, this.scale, this.grid);
- } else if (this.type === 'minimap') {
+ }
+ else if (this.type === 'minimap') {
drawMinimap(this.canvas.nativeElement, this.map, this.info, this.scale);
}
}
diff --git a/src/ts/components/tools/tools-perf/methods.ts b/src/ts/components/tools/tools-perf/methods.ts
index cff8896..5987d73 100644
--- a/src/ts/components/tools/tools-perf/methods.ts
+++ b/src/ts/components/tools/tools-perf/methods.ts
@@ -15,7 +15,8 @@ function forEachCharacter(value: string, callback: (code: number) => void) {
callback(((code & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
}
}
- } else {
+ }
+ else {
callback(code);
}
}
@@ -24,11 +25,14 @@ function forEachCharacter(value: string, callback: (code: number) => void) {
function charLengthInBytes(code: number): number {
if ((code & 0xffffff80) === 0) {
return 1;
- } else if ((code & 0xfffff800) === 0) {
+ }
+ else if ((code & 0xfffff800) === 0) {
return 2;
- } else if ((code & 0xffff0000) === 0) {
+ }
+ else if ((code & 0xffff0000) === 0) {
return 3;
- } else {
+ }
+ else {
return 4;
}
}
@@ -45,13 +49,16 @@ function encodeStringTo(buffer: Uint8Array | Buffer, offset: number, value: stri
if (length === 1) {
buffer[offset++] = code;
- } else {
+ }
+ else {
if (length === 2) {
buffer[offset++] = ((code >> 6) & 0x1f) | 0xc0;
- } else if (length === 3) {
+ }
+ else if (length === 3) {
buffer[offset++] = ((code >> 12) & 0x0f) | 0xe0;
buffer[offset++] = ((code >> 6) & 0x3f) | 0x80;
- } else {
+ }
+ else {
buffer[offset++] = ((code >> 18) & 0x07) | 0xf0;
buffer[offset++] = ((code >> 12) & 0x3f) | 0x80;
buffer[offset++] = ((code >> 6) & 0x3f) | 0x80;
@@ -65,8 +72,9 @@ function encodeStringTo(buffer: Uint8Array | Buffer, offset: number, value: stri
}
export function encodeString(value: string | null): Uint8Array | null {
- if (value == null)
+ if (value == null) {
return null;
+ }
const buffer = new Uint8Array(stringLengthInBytes(value));
encodeStringTo(buffer, 0, value);
@@ -74,8 +82,9 @@ export function encodeString(value: string | null): Uint8Array | null {
}
export function encodeStringNew(value: string | null): Uint8Array | null {
- if (value == null)
+ if (value == null) {
return null;
+ }
const buffer = new Uint8Array(stringLengthInBytes2(value));
encodeStringTo2(buffer, 0, value);
@@ -87,11 +96,14 @@ export function encodeStringNew(value: string | null): Uint8Array | null {
function charLengthInBytes2(code: number): number {
if ((code & 0xffffff80) === 0) {
return 1;
- } else if ((code & 0xfffff800) === 0) {
+ }
+ else if ((code & 0xfffff800) === 0) {
return 2;
- } else if ((code & 0xffff0000) === 0) {
+ }
+ else if ((code & 0xffff0000) === 0) {
return 3;
- } else {
+ }
+ else {
return 4;
}
}
@@ -108,13 +120,16 @@ export function encodeStringTo2(buffer: Uint8Array, offset: number, value: strin
if (length === 1) {
buffer[offset++] = code;
- } else {
+ }
+ else {
if (length === 2) {
buffer[offset++] = ((code >> 6) & 0x1f) | 0xc0;
- } else if (length === 3) {
+ }
+ else if (length === 3) {
buffer[offset++] = ((code >> 12) & 0x0f) | 0xe0;
buffer[offset++] = ((code >> 6) & 0x3f) | 0x80;
- } else {
+ }
+ else {
buffer[offset++] = ((code >> 18) & 0x07) | 0xf0;
buffer[offset++] = ((code >> 12) & 0x3f) | 0x80;
buffer[offset++] = ((code >> 6) & 0x3f) | 0x80;
@@ -143,10 +158,12 @@ function forEachCharacter2(value: string, callback: (code: number) => void) {
if ((extra & 0xfc00) === 0xdc00) {
i = (i + 1) | 0;
code = (((((code & 0x3ff) << 10) + (extra & 0x3ff)) | 0) + 0x10000) | 0;
- } else {
+ }
+ else {
continue;
}
- } else {
+ }
+ else {
continue;
}
}
diff --git a/src/ts/components/tools/tools-perf/tools-perf.ts b/src/ts/components/tools/tools-perf/tools-perf.ts
index 2355b0d..dfaa942 100644
--- a/src/ts/components/tools/tools-perf/tools-perf.ts
+++ b/src/ts/components/tools/tools-perf/tools-perf.ts
@@ -47,8 +47,9 @@ export class ToolsPerf {
}
function measure(name: string, iterations: number, func: (i: number) => void) {
- if (!iterations)
+ if (!iterations) {
return;
+ }
const start = performance.now();
let v: any;
@@ -124,12 +125,14 @@ export function compareArrays() {
let t: any;
function compareArrays(a: number[], b: number[]) {
- if (a.length !== b.length)
+ if (a.length !== b.length) {
return false;
+ }
for (let i = 0; i < a.length; i++) {
- if (a[i] !== b[i])
+ if (a[i] !== b[i]) {
return false;
+ }
}
return true;
diff --git a/src/ts/components/tools/tools-regions/tools-regions.ts b/src/ts/components/tools/tools-regions/tools-regions.ts
index 9b5e88b..5ae2e54 100644
--- a/src/ts/components/tools/tools-regions/tools-regions.ts
+++ b/src/ts/components/tools/tools-regions/tools-regions.ts
@@ -107,7 +107,8 @@ export class ToolsRegions implements OnInit, OnDestroy {
if (isAreaVisible(this.camera, x * regionWidth, y * regionHeight, regionWidth, regionHeight)) {
if (this.regions[y][x] === 'Sienna') {
this.regions[y][x] = 'SeaGreen';
- } else {
+ }
+ else {
this.regions[y][x] = 'Crimson';
}
}
@@ -130,13 +131,17 @@ export class ToolsRegions implements OnInit, OnDestroy {
if (e.keyCode === Key.KEY_P) {
this.zoom = this.zoom === 4 ? 1 : (this.zoom + 1);
this.update();
- } else if (e.keyCode === Key.RIGHT) {
+ }
+ else if (e.keyCode === Key.RIGHT) {
this.right = true;
- } else if (e.keyCode === Key.LEFT) {
+ }
+ else if (e.keyCode === Key.LEFT) {
this.left = true;
- } else if (e.keyCode === Key.UP) {
+ }
+ else if (e.keyCode === Key.UP) {
this.up = true;
- } else if (e.keyCode === Key.DOWN) {
+ }
+ else if (e.keyCode === Key.DOWN) {
this.down = true;
}
}
@@ -144,11 +149,14 @@ export class ToolsRegions implements OnInit, OnDestroy {
keyup(e: KeyboardEvent) {
if (e.keyCode === Key.RIGHT) {
this.right = false;
- } else if (e.keyCode === Key.LEFT) {
+ }
+ else if (e.keyCode === Key.LEFT) {
this.left = false;
- } else if (e.keyCode === Key.UP) {
+ }
+ else if (e.keyCode === Key.UP) {
this.up = false;
- } else if (e.keyCode === Key.DOWN) {
+ }
+ else if (e.keyCode === Key.DOWN) {
this.down = false;
}
}
@@ -160,10 +168,18 @@ export class ToolsRegions implements OnInit, OnDestroy {
let dx = 0;
let dy = 0;
- if (this.right) dx += 1;
- if (this.left) dx -= 1;
- if (this.up) dy -= 1;
- if (this.down) dy += 1;
+ if (this.right) {
+ dx += 1;
+ }
+ if (this.left) {
+ dx -= 1;
+ }
+ if (this.up) {
+ dy -= 1;
+ }
+ if (this.down) {
+ dy += 1;
+ }
if (dx || dy) {
this.player.x += dx * delta * PONY_SPEED_TROT;
diff --git a/src/ts/components/tools/tools-ui/tools-ui.ts b/src/ts/components/tools/tools-ui/tools-ui.ts
index 86ea9db..5b160f7 100644
--- a/src/ts/components/tools/tools-ui/tools-ui.ts
+++ b/src/ts/components/tools/tools-ui/tools-ui.ts
@@ -176,7 +176,8 @@ export class ToolsUI implements OnInit, OnDestroy {
if (this.spamChatInterval) {
clearInterval(this.spamChatInterval);
this.spamChatInterval = 0;
- } else {
+ }
+ else {
this.spamChatInterval = 1;
this.zone.runOutsideAngular(() => this.spamChatInterval = setInterval(() => {
chatlog.addMessage({
@@ -195,7 +196,8 @@ export class ToolsUI implements OnInit, OnDestroy {
set isPartyLeader(value: boolean) {
if (value) {
this.game.party!.leaderId = this.game.player!.id;
- } else {
+ }
+ else {
this.game.party!.leaderId = 1;
}
}
diff --git a/src/ts/components/tools/tools-variants/tools-variants.ts b/src/ts/components/tools/tools-variants/tools-variants.ts
index 75b4e76..03333ed 100644
--- a/src/ts/components/tools/tools-variants/tools-variants.ts
+++ b/src/ts/components/tools/tools-variants/tools-variants.ts
@@ -88,7 +88,8 @@ export class ToolsVariants implements OnInit {
if (this.justHead) {
viewContext.drawImage(buffer, 0, 0, 55, 45, x * 45 - 10, y * 45, 55, 45);
- } else {
+ }
+ else {
viewContext.drawImage(buffer, x * 60 - 10, y * 60);
}
}
diff --git a/src/ts/experiments/checkCode.ts b/src/ts/experiments/checkCode.ts
index 6bd2236..fc53ae4 100644
--- a/src/ts/experiments/checkCode.ts
+++ b/src/ts/experiments/checkCode.ts
@@ -22,7 +22,8 @@ function processDir(pathStr: string, client = false) {
if (file.isDirectory()) {
processDir(filePath);
- } else if (file.isFile()) {
+ }
+ else if (file.isFile()) {
if (file.name.endsWith('.ts')) {
const lines = fs.readFileSync(filePath, 'utf-8').split('\n').map(l => l.trim());
checked++;
@@ -37,7 +38,8 @@ function processDir(pathStr: string, client = false) {
console.warn('='.repeat(16));
}
}
- } else {
+ }
+ else {
console.log(`File not supported ${pathStr}`);
}
}
@@ -52,7 +54,8 @@ function main() {
}
if (issues) {
console.log(`Found ${issues} issues in ${checked} files`);
- } else {
+ }
+ else {
console.log(`Checked ${checked} files no issues have been found`);
}
}
diff --git a/src/ts/generated/gamepad-mappings.ts b/src/ts/generated/gamepad-mappings.ts
index a772294..57ae1f7 100644
--- a/src/ts/generated/gamepad-mappings.ts
+++ b/src/ts/generated/gamepad-mappings.ts
@@ -1,4 +1,4 @@
-/* tslint:disable:max-line-length */
+/* eslint-disable */
export interface GamepadMapping {
axes: AxesTable;
diff --git a/src/ts/generated/gamepad-template.ts b/src/ts/generated/gamepad-template.ts
index 7a2cadb..c0241c0 100644
--- a/src/ts/generated/gamepad-template.ts
+++ b/src/ts/generated/gamepad-template.ts
@@ -1,3 +1,4 @@
+/* eslint-disable camelcase */
export interface GamepadMapping {
axes: AxesTable;
buttons: ButtonsTable;
diff --git a/src/ts/graphics/baseSpriteBatch.ts b/src/ts/graphics/baseSpriteBatch.ts
index 8b31e48..0ce71e5 100644
--- a/src/ts/graphics/baseSpriteBatch.ts
+++ b/src/ts/graphics/baseSpriteBatch.ts
@@ -137,7 +137,8 @@ export abstract class BaseSpriteBatch extends BaseStateBatch implements SpriteBa
// return batch;
return this.vertices.slice(this.startBatchIndex, this.index);
- } catch {
+ }
+ catch {
return undefined;
}
}
@@ -145,8 +146,9 @@ export abstract class BaseSpriteBatch extends BaseStateBatch implements SpriteBa
// releaseBuffer(batch);
}
flush() {
- if (this.index === 0)
+ if (this.index === 0) {
return;
+ }
if (!this.vao || !this.vertexBuffer) {
throw new Error('Disposed');
@@ -155,14 +157,22 @@ export abstract class BaseSpriteBatch extends BaseStateBatch implements SpriteBa
const gl = this.gl;
if (this.batching) {
- TIMING && timeStart('bufferSubData');
+ if (TIMING) {
+ timeStart('bufferSubData');
+ }
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices.subarray(0, this.startBatchIndex));
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
- TIMING && timeStart('vao.draw');
+ if (TIMING) {
+ timeStart('vao.draw');
+ }
this.vao.draw(this.gl.TRIANGLES, this.startBatchSprites * 6, 0);
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
this.drawnTrisStats += this.startBatchSprites * 2;
this.spritesCount -= this.startBatchSprites;
@@ -170,15 +180,24 @@ export abstract class BaseSpriteBatch extends BaseStateBatch implements SpriteBa
this.vertices.copyWithin(0, this.startBatchIndex, this.startBatchIndex + this.index);
this.startBatchIndex = 0;
this.startBatchSprites = 0;
- } else {
- TIMING && timeStart('bufferSubData');
+ }
+ else {
+ if (TIMING) {
+ timeStart('bufferSubData');
+ }
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices.subarray(0, this.index));
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
- TIMING && timeStart('vao.draw');
+ if (TIMING) {
+ timeStart('vao.draw');
+ }
this.vao.draw(this.gl.TRIANGLES, this.spritesCount * 6, 0);
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
this.drawnTrisStats += this.spritesCount * 2;
this.spritesCount = 0;
@@ -197,8 +216,11 @@ function disposeBuffers(gl: WebGLRenderingContext, batch: BaseSpriteBatch) {
if (batch.vertexBuffer) {
gl.deleteBuffer(batch.vertexBuffer);
}
- } catch (e) {
- DEVELOPMENT && console.error(e);
+ }
+ catch (e) {
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
}
batch.vao = undefined;
diff --git a/src/ts/graphics/contextSpriteBatch.ts b/src/ts/graphics/contextSpriteBatch.ts
index d55d1ac..101c17a 100644
--- a/src/ts/graphics/contextSpriteBatch.ts
+++ b/src/ts/graphics/contextSpriteBatch.ts
@@ -92,7 +92,8 @@ export class ContextSpriteBatch extends BaseStateBatch implements PaletteSpriteB
drawImageNormal(
this.sheetData, this.data, this.transform, this.globalAlpha,
color, s.x, s.y, s.w, s.h, x + s.ox, y + s.oy, s.w, s.h);
- } else {
+ }
+ else {
drawImagePalette(
this.sheetData, this.data, this.transform, this.globalAlpha,
this.ignoreColor, this.disableShading,
@@ -117,7 +118,8 @@ export class ContextSpriteBatch extends BaseStateBatch implements PaletteSpriteB
this.sheetData, this.data, this.transform, this.globalAlpha,
colorOrType, sxOrColor, syOrPalette as number,
swOrSx, shOrSy, dxOrSw, dyOrSh, dwOrDx, dhOrDy);
- } else {
+ }
+ else {
drawImagePalette(
this.sheetData, this.data, this.transform, this.globalAlpha,
this.ignoreColor, this.disableShading,
@@ -155,8 +157,9 @@ function drawRect(
console.error('Transform not supported');
}
- if (!dst)
+ if (!dst) {
return;
+ }
x = Math.round(x + transform[4]);
y = Math.round(y + transform[5]);
@@ -172,14 +175,16 @@ function drawRect(
w += min(0, dst.width - (x + w));
h += min(0, dst.height - (y + h));
- if (w <= 0 && h <= 0)
+ if (w <= 0 && h <= 0) {
return;
+ }
const { r, g, b, a } = colorToRGBA(color);
const alpha = (globalAlpha * a) | 0;
- if (alpha === 0)
+ if (alpha === 0) {
return;
+ }
const dstData = dst.data;
const dstWidth = dst.width | 0;
@@ -197,15 +202,17 @@ function drawImageNormal(
tint: number, sx: number, sy: number, sw: number, sh: number,
dx: number, dy: number, dw: number, dh: number
) {
- if (sw !== dw || sh !== dh)
+ if (sw !== dw || sh !== dh) {
throw new Error('Different dimentions not supported');
+ }
if (DEVELOPMENT && !isTranslation(transform)) {
console.error('Transform not supported');
}
- if (!src || !dst)
+ if (!src || !dst) {
return;
+ }
dx = Math.round(dx + transform[4]);
dy = Math.round(dy + transform[5]);
@@ -226,8 +233,9 @@ function drawImageNormal(
w += min(0, src.width - (sx + w), dst.width - (dx + w));
h += min(0, src.height - (sy + h), dst.height - (dy + h));
- if (w <= 0 && h <= 0)
+ if (w <= 0 && h <= 0) {
return;
+ }
const { r, g, b, a } = colorToRGBA(tint);
const alpha = (globalAlpha * a) | 0;
@@ -262,8 +270,9 @@ function drawImagePalette(
type: number, tint: number, palette: Palette | undefined,
sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number
) {
- if (sw !== dw || sh !== dh)
+ if (sw !== dw || sh !== dh) {
throw new Error('Different dimentions not supported');
+ }
if (DEVELOPMENT && !isTranslation(transform)) {
console.error('Transform not supported');
@@ -273,8 +282,9 @@ function drawImagePalette(
palette = commonPalettes.defaultPalette;
}
- if (!src || !dst)
+ if (!src || !dst) {
return;
+ }
dx = Math.round(dx + transform[4]);
dy = Math.round(dy + transform[5]);
@@ -295,8 +305,9 @@ function drawImagePalette(
w += min(0, src.width - (sx + w), dst.width - (dx + w));
h += min(0, src.height - (sy + h), dst.height - (dy + h));
- if (w <= 0 && h <= 0)
+ if (w <= 0 && h <= 0) {
return;
+ }
const { r, g, b, a } = colorToRGBA(tint);
const alpha = (globalAlpha * a) | 0;
@@ -338,7 +349,8 @@ function blendPrecise(dstData: Uint8ClampedArray, dst0: number, r: number, g: nu
dstData[dst0 + 1] = g;
dstData[dst0 + 2] = b;
dstData[dst0 + 3] = alpha;
- } else {
+ }
+ else {
const dstAlpha = (0xff - alpha) | 0;
dstData[dst0] = ((((r * alpha) | 0) / 255) | 0) + ((((dstData[dst0] * dstAlpha) | 0) / 255) | 0);
dstData[dst0 + 1] = ((((g * alpha) | 0) / 255) | 0) + ((((dstData[dst0 + 1] * dstAlpha) | 0) / 255) | 0);
diff --git a/src/ts/graphics/graphicsUtils.ts b/src/ts/graphics/graphicsUtils.ts
index 03b7b7b..aec15bc 100644
--- a/src/ts/graphics/graphicsUtils.ts
+++ b/src/ts/graphics/graphicsUtils.ts
@@ -66,9 +66,11 @@ export function drawRoundBaloon(batch: AnyBatch, color: number, x: number, y: nu
function getMessagePalette(type: MessageType, palettes: FontPalettes) {
if (type === MessageType.Supporter2) {
return palettes.supporter2;
- } else if (type === MessageType.Supporter3) {
+ }
+ else if (type === MessageType.Supporter3) {
return palettes.supporter3;
- } else {
+ }
+ else {
return undefined;
}
}
@@ -77,8 +79,9 @@ export function drawBaloon(
batch: PaletteSpriteBatch, { message, type = MessageType.Chat, timer = 1, total = 10 }: Says,
x: number, y: number, bounds: Rect, palettes: CommonPalettes
) {
- if (!fontPal)
+ if (!fontPal) {
return;
+ }
let { w, h } = measureText(message, fontPal);
@@ -114,9 +117,11 @@ export function drawBaloon(
if (isThinking(type)) {
drawThinkingBaloon(batch, message, color, options, x, y, w, h, alpha, nippleX);
- } else if (isWhisper(type) || isWhisperTo(type)) {
+ }
+ else if (isWhisper(type) || isWhisperTo(type)) {
drawWhisperBaloon(batch, message, color, options, x, y, w, h, alpha, nippleX);
- } else {
+ }
+ else {
drawSpeechBaloon(batch, message, color, options, x, y, w, h, alpha, nippleX);
}
}
@@ -217,9 +222,11 @@ export enum DrawNameFlags {
function getNameColor(flags: DrawNameFlags) {
if (hasFlag(flags, DrawNameFlags.Party)) {
return PARTY_COLOR;
- } else if (hasFlag(flags, DrawNameFlags.Friend)) {
+ }
+ else if (hasFlag(flags, DrawNameFlags.Friend)) {
return FRIENDS_COLOR;
- } else {
+ }
+ else {
return WHITE;
}
}
diff --git a/src/ts/graphics/paletteManager.ts b/src/ts/graphics/paletteManager.ts
index e912d31..76d8bfc 100644
--- a/src/ts/graphics/paletteManager.ts
+++ b/src/ts/graphics/paletteManager.ts
@@ -106,7 +106,8 @@ export class PaletteManager implements IPaletteManager {
while (!this.arrange(this.dirty)) {
if (this.size < MAX_SIZE) {
this.initializeTexture(gl, this.size * 2);
- } else {
+ }
+ else {
throw new Error('Exceeded maximum palettes limit');
}
}
@@ -159,10 +160,12 @@ export class PaletteManager implements IPaletteManager {
try {
if (!this.paletteTexture) {
this.paletteTexture = createEmptyTexture(gl, true, size, size, gl.RGBA, gl.UNSIGNED_BYTE);
- } else if (this.paletteTexture.width !== size) {
+ }
+ else if (this.paletteTexture.width !== size) {
resizeTexture(gl, this.paletteTexture, size, size);
}
- } catch (e) {
+ }
+ catch (e) {
throw new Error(`Failed to create/resize texture (${size})${isErrorAlike(e) ? ` ${e.stack}` : ''}`);
}
@@ -210,8 +213,9 @@ export class PaletteManager implements IPaletteManager {
return true;
}
private updateTexture(gl: WebGLRenderingContext) {
- if (!this.paletteTexture || this.dirtyMinY > this.dirtyMaxY)
+ if (!this.paletteTexture || this.dirtyMinY > this.dirtyMaxY) {
return;
+ }
const width = this.size;
const height = (this.dirtyMaxY - this.dirtyMinY) + 1;
@@ -223,8 +227,9 @@ export class PaletteManager implements IPaletteManager {
for (let i = 0; i < palettes.length; i++) {
const { x, y, colors } = palettes[i];
- if (y < this.dirtyMinY || y > this.dirtyMaxY)
+ if (y < this.dirtyMinY || y > this.dirtyMaxY) {
continue;
+ }
let offset = (x + (y - this.dirtyMinY) * width) << 2;
diff --git a/src/ts/graphics/paletteSpriteBatch.ts b/src/ts/graphics/paletteSpriteBatch.ts
index ae81a2e..1a12a8c 100644
--- a/src/ts/graphics/paletteSpriteBatch.ts
+++ b/src/ts/graphics/paletteSpriteBatch.ts
@@ -227,7 +227,8 @@ export class PaletteSpriteBatch extends BaseSpriteBatch implements IPaletteSprit
);
this.spritesCount++;
}
- } else {
+ }
+ else {
this.index = pushQuad(
this.vertices,
this.transform, this.index, s.type, getColorFloat(color, this.globalAlpha),
diff --git a/src/ts/graphics/spriteBatch.ts b/src/ts/graphics/spriteBatch.ts
index 77ca095..b96e773 100644
--- a/src/ts/graphics/spriteBatch.ts
+++ b/src/ts/graphics/spriteBatch.ts
@@ -63,7 +63,8 @@ export class SpriteBatch extends BaseSpriteBatch implements ISpriteBatch {
if (rect) {
this.drawImage(color, rect.x, rect.y, rect.w, rect.h, x, y, w, h);
- } else {
+ }
+ else {
this.drawImage(color, 0, 0, 1, 1, x, y, w, h);
}
}
diff --git a/src/ts/graphics/spriteFont.ts b/src/ts/graphics/spriteFont.ts
index 3973260..8c3015e 100644
--- a/src/ts/graphics/spriteFont.ts
+++ b/src/ts/graphics/spriteFont.ts
@@ -91,7 +91,8 @@ function drawChars(
if (code === LINEFEED) {
currentX = x;
y += font.letterHeight + lineSpacing;
- } else {
+ }
+ else {
const charWidth = drawChar(batch, font, code, color, currentX, y, options);
currentX += (monospace ? font.letterWidth : charWidth) + font.letterSpacing;
}
@@ -180,7 +181,8 @@ function measureChars(chars: Uint32Array, length: number, font: SpriteFont): { w
maxW = Math.max(maxW, w);
w = 0;
lines++;
- } else {
+ }
+ else {
if (w) {
w += font.letterSpacing;
}
@@ -233,18 +235,21 @@ function drawChar(
if (!skipEmote) {
if (isPaletteSpriteBatch(batch)) {
batch.drawSprite(emote, emoteColor, options.emojiPalette, px, py);
- } else {
+ }
+ else {
batch.drawSprite(emote, emoteColor, px, py);
}
}
return emote.w + emote.ox;
- } else {
+ }
+ else {
const c = getChar(font, code);
if (isPaletteSpriteBatch(batch)) {
batch.drawSprite(c, color, options.palette, px, py);
- } else {
+ }
+ else {
batch.drawSprite(c, color, px, py);
}
diff --git a/src/ts/graphics/webgl/frameBuffer.ts b/src/ts/graphics/webgl/frameBuffer.ts
index 47f0520..9c35e9e 100644
--- a/src/ts/graphics/webgl/frameBuffer.ts
+++ b/src/ts/graphics/webgl/frameBuffer.ts
@@ -46,8 +46,11 @@ export function disposeFrameBuffer(gl?: WebGLRenderingContext, buffer?: FrameBuf
gl.deleteRenderbuffer(buffer.depthStencilRenderbuffer);
}
}
- } catch (e) {
- DEVELOPMENT && console.error(e);
+ }
+ catch (e) {
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
}
return undefined;
diff --git a/src/ts/graphics/webgl/glFbo.ts b/src/ts/graphics/webgl/glFbo.ts
index 3797bee..dc317ad 100644
--- a/src/ts/graphics/webgl/glFbo.ts
+++ b/src/ts/graphics/webgl/glFbo.ts
@@ -1,3 +1,4 @@
+/* eslint-disable camelcase */
import { Texture2D, resizeTexture, disposeTexture, createEmptyTexture } from './texture2d';
import { array } from '../../common/utils';
@@ -55,10 +56,12 @@ export function createFrameBuffer(gl: WebGL, width: number, height: number, opti
if (numColors < 0) {
throw new Error('Must specify a nonnegative number of colors');
- } else if (numColors > 1) {
+ }
+ else if (numColors > 1) {
if (!ext) {
throw new Error('Multiple draw buffer extension not supported');
- } else if (numColors > gl.getParameter(ext.MAX_COLOR_ATTACHMENTS_WEBGL)) {
+ }
+ else if (numColors > gl.getParameter(ext.MAX_COLOR_ATTACHMENTS_WEBGL)) {
throw new Error(`Context does not support ${numColors} draw buffers`);
}
}
@@ -72,7 +75,8 @@ export function createFrameBuffer(gl: WebGL, width: number, height: number, opti
}
colorType = gl.FLOAT;
- } else if (preferFloat && numColors > 0) {
+ }
+ else if (preferFloat && numColors > 0) {
if (OES_texture_float) {
colorType = gl.FLOAT;
}
@@ -124,9 +128,11 @@ export function resizeFrameBuffer(fbo: FrameBuffer, w: number, h: number) {
if (fbo.useDepth && fbo.useStencil) {
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h);
- } else if (fbo.useDepth) {
+ }
+ else if (fbo.useDepth) {
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, w, h);
- } else if (fbo.useStencil) {
+ }
+ else if (fbo.useStencil) {
gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, w, h);
}
}
@@ -191,7 +197,8 @@ function rebuild(fbo: FrameBuffer) {
if (ext) {
ext.drawBuffersWEBGL(colorAttachmentArrays![0]);
}
- } else if (numColors > 1) {
+ }
+ else if (numColors > 1) {
if (ext) {
ext.drawBuffersWEBGL(colorAttachmentArrays![numColors]);
}
@@ -203,15 +210,19 @@ function rebuild(fbo: FrameBuffer) {
if (useStencil) {
fbo.depth = initTexture(
gl, width, height, WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL, gl.DEPTH_STENCIL, gl.DEPTH_STENCIL_ATTACHMENT);
- } else if (useDepth) {
+ }
+ else if (useDepth) {
fbo.depth = initTexture(gl, width, height, gl.UNSIGNED_SHORT, gl.DEPTH_COMPONENT, gl.DEPTH_ATTACHMENT);
}
- } else {
+ }
+ else {
if (useDepth && useStencil) {
fbo.depthRenderBuffer = initRenderBuffer(gl, width, height, gl.DEPTH_STENCIL, gl.DEPTH_STENCIL_ATTACHMENT);
- } else if (useDepth) {
+ }
+ else if (useDepth) {
fbo.depthRenderBuffer = initRenderBuffer(gl, width, height, gl.DEPTH_COMPONENT16, gl.DEPTH_ATTACHMENT);
- } else if (useStencil) {
+ }
+ else if (useStencil) {
fbo.depthRenderBuffer = initRenderBuffer(gl, width, height, gl.STENCIL_INDEX8, gl.STENCIL_ATTACHMENT);
}
}
diff --git a/src/ts/graphics/webgl/glVao.ts b/src/ts/graphics/webgl/glVao.ts
index 6f3f046..5e753e1 100644
--- a/src/ts/graphics/webgl/glVao.ts
+++ b/src/ts/graphics/webgl/glVao.ts
@@ -1,3 +1,4 @@
+/* eslint-disable camelcase */
import { timeStart, timeEnd } from '../../common/timing';
export interface VAOAttributes {
@@ -72,13 +73,18 @@ class VAONative implements VAO {
this.elementsType = elementsType || this.gl.UNSIGNED_SHORT;
}
draw(mode: number, count: number, offset = 0) {
- TIMING && timeStart('VAONative.draw');
+ if (TIMING) {
+ timeStart('VAONative.draw');
+ }
if (this.useElements) {
this.gl.drawElements(mode, count, this.elementsType, offset);
- } else {
+ }
+ else {
this.gl.drawArrays(mode, offset, count);
}
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
}
}
@@ -104,13 +110,18 @@ class VAOEmulated implements VAO {
unbind() {
}
draw(mode: number, count: number, offset = 0) {
- TIMING && timeStart('VAOEmulated.draw');
+ if (TIMING) {
+ timeStart('VAOEmulated.draw');
+ }
if (this.elements) {
this.gl.drawElements(mode, count, this.elementsType, offset);
- } else {
+ }
+ else {
this.gl.drawArrays(mode, offset, count);
}
- TIMING && timeEnd();
+ if (TIMING) {
+ timeEnd();
+ }
}
}
@@ -146,7 +157,8 @@ function bindAttribs(
for (; i < maxAttribs; ++i) {
gl.disableVertexAttribArray(i);
}
- } else {
+ }
+ else {
gl.bindBuffer(gl.ARRAY_BUFFER, null);
for (let i = 0; i < maxAttribs; ++i) {
diff --git a/src/ts/graphics/webgl/shader.ts b/src/ts/graphics/webgl/shader.ts
index f8b612f..618c109 100644
--- a/src/ts/graphics/webgl/shader.ts
+++ b/src/ts/graphics/webgl/shader.ts
@@ -118,7 +118,10 @@ export function disposeShaderProgramData(gl: WebGLRenderingContext, data: Shader
if (gl) {
gl.deleteProgram(data.program);
}
- } catch (e) {
- DEVELOPMENT && console.error(e);
+ }
+ catch (e) {
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
}
}
diff --git a/src/ts/graphics/webgl/texture2d.ts b/src/ts/graphics/webgl/texture2d.ts
index 022cf05..1255f74 100644
--- a/src/ts/graphics/webgl/texture2d.ts
+++ b/src/ts/graphics/webgl/texture2d.ts
@@ -95,8 +95,11 @@ export function disposeTexture(gl: WebGL | undefined, texture: Texture2D | undef
if (gl && texture) {
gl.deleteTexture(texture.handle);
}
- } catch (e) {
- DEVELOPMENT && console.error(e);
+ }
+ catch (e) {
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
}
return undefined;
diff --git a/src/ts/graphics/webgl/webglUtils.ts b/src/ts/graphics/webgl/webglUtils.ts
index 8564424..ecb745a 100644
--- a/src/ts/graphics/webgl/webglUtils.ts
+++ b/src/ts/graphics/webgl/webglUtils.ts
@@ -67,13 +67,16 @@ export function unbindAllTexturesAndBuffers(gl: WebGLRenderingContext) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- } catch (e) {
- DEVELOPMENT && console.error(e);
+ }
+ catch (e) {
+ if (DEVELOPMENT) {
+ console.error(e);
+ }
}
}
export function clearWebGLErrors(gl: WebGLRenderingContext) {
- while (hasWebGLErrors(gl));
+ while (hasWebGLErrors(gl)){}
}
export function hasWebGLErrors(gl: WebGLRenderingContext) {
diff --git a/src/ts/lodash.ts b/src/ts/lodash.ts
index 1efe199..79c3afc 100644
--- a/src/ts/lodash.ts
+++ b/src/ts/lodash.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-require-imports */
type List = ArrayLike;
type PartialDeep = {
[P in keyof T]?: PartialDeep;
@@ -8,7 +9,7 @@ interface Dictionary {
interface NumericDictionary {
[index: number]: T;
}
-type NotVoid = {} | null | undefined;
+type NotVoid = NonNullable | null | undefined;
type ListIteratee = ListIterator | string | [string, any] | PartialDeep;
type ListIterator = (value: T, index: number, collection: List) => TResult;
type ListIterateeCustom = ListIterator | string | [string, any] | PartialDeep;
diff --git a/src/ts/server/accountUtils.ts b/src/ts/server/accountUtils.ts
index b75a1b9..24f7137 100644
--- a/src/ts/server/accountUtils.ts
+++ b/src/ts/server/accountUtils.ts
@@ -65,15 +65,19 @@ function createNewAccount(profile: Profile, options: CreateAccountOptions) {
if (!options.canCreateAccounts) {
throw new UserError(
'Creating accounts is temporarily disabled, try again later');
- } else if (options.connectOnly) {
+ }
+ else if (options.connectOnly) {
throw new UserError(connectOnlySocialError);
- } else if (options.creationLocked) {
+ }
+ else if (options.creationLocked) {
throw new UserError(
'Could not create account, try again later', { log: `account creation blocked by ACL (${options.ip})` });
- } else if (profile.suspended) {
+ }
+ else if (profile.suspended) {
throw new UserError(
'Cannot create new account using suspended social site account', { log: 'account creation blocked by suspended' });
- } else {
+ }
+ else {
return new Account();
}
}
@@ -84,17 +88,21 @@ async function hasDuplicatesAtOrigin(account: IAccount, ip: string) {
const duplicates: IAccount[] = await Account.find(query, '_id ban mute shadow flags name').lean().exec();
return duplicates.some(({ _id, ban = 0, mute = 0, shadow = 0, flags = 0, name }) => {
- if (_id.toString() === account._id.toString())
+ if (_id.toString() === account._id.toString()) {
return false;
+ }
- if (ban === -1 || ban > now || mute === -1 || mute > now || shadow === -1 || shadow > now)
+ if (ban === -1 || ban > now || mute === -1 || mute > now || shadow === -1 || shadow > now) {
return true;
+ }
- if (hasFlag(flags, AccountFlags.CreatingDuplicates))
+ if (hasFlag(flags, AccountFlags.CreatingDuplicates)) {
return true;
+ }
- if (name === account.name)
+ if (name === account.name) {
return true;
+ }
return false;
});
@@ -112,7 +120,8 @@ async function checkNewAccount(account: IAccount, options: CreateAccountOptions)
options.warn(account._id, `Potential duplicate`);
}
}
- } catch (e) {
+ }
+ catch (e) {
options.warn(account._id, `Error when checking new account`, isErrorAlike(e) ? e.message : undefined);
}
});
@@ -166,7 +175,8 @@ export async function findOrCreateAccount(auth: IAuth, profile: Profile, options
await account.save();
system(account._id, `created account "${account.name}"`);
checkNewAccount(account, options);
- } else {
+ }
+ else {
const { name, emails, lastVisit, lastUserAgent, lastBrowserId } = account;
await Account.updateOne({ _id: account._id }, { name, emails, lastVisit, lastUserAgent, lastBrowserId }).exec();
}
@@ -182,7 +192,8 @@ export function checkIfNotAdmin(account: IAccount, message: string) {
if (isAdmin(account)) {
logger.warn(`Cannot perform this action on admin user (${message})`);
throw new Error('Cannot perform this action on admin user');
- } else {
+ }
+ else {
return account;
}
}
diff --git a/src/ts/server/adminServerActions.ts b/src/ts/server/adminServerActions.ts
index 0b0473c..eca1759 100644
--- a/src/ts/server/adminServerActions.ts
+++ b/src/ts/server/adminServerActions.ts
@@ -98,7 +98,8 @@ export class AdminServerActions implements IAdminServerActions, SocketServer {
if (index !== -1) {
this.updates[index].update = update;
- } else {
+ }
+ else {
this.updates.push({ type, id, update });
}
@@ -114,8 +115,9 @@ export class AdminServerActions implements IAdminServerActions, SocketServer {
subscribe(type: ModelTypes, id: string) {
const key = `${type}:${id}`;
- if (this.subscriptions.has(key))
+ if (this.subscriptions.has(key)) {
return;
+ }
if (type === 'ponies') {
if (!this.adminService.ponies.get(id)) {
@@ -127,13 +129,17 @@ export class AdminServerActions implements IAdminServerActions, SocketServer {
if (type === 'accountAuths') {
subscription = this.adminService.subscribeToAccountAuths(id, update => this.pushUpdate(type, id, update));
- } else if (type === 'accountOrigins') {
+ }
+ else if (type === 'accountOrigins') {
subscription = this.adminService.subscribeToAccountOrigins(id, update => this.pushUpdate(type, id, update));
- } else if (type === 'accountPonies') {
+ }
+ else if (type === 'accountPonies') {
subscription = this.adminService.subscribeToAccountPonies(id, update => this.pushUpdate(type, id, update));
- } else if (type in this.adminService) {
+ }
+ else if (type in this.adminService) {
subscription = this.adminService[type].subscribe(id, (id, update) => this.pushUpdate(type, id, update));
- } else {
+ }
+ else {
throw new Error(`Invalid model type (${type})`);
}
@@ -152,7 +158,8 @@ export class AdminServerActions implements IAdminServerActions, SocketServer {
if (type === 'ponies') {
this.adminService.cleanupPony(id);
- } else if (type === 'accountPonies') {
+ }
+ else if (type === 'accountPonies') {
this.adminService.cleanupPoniesList(id);
}
}
@@ -266,7 +273,8 @@ export class AdminServerActions implements IAdminServerActions, SocketServer {
async clearOrigins(count: number, andHigher: boolean, options: ClearOrignsOptions) {
if (!this.adminService.loaded) {
throw new Error('Not loaded yet');
- } else {
+ }
+ else {
await clearOrigins(this.adminService, count, andHigher, options);
}
}
@@ -274,7 +282,8 @@ export class AdminServerActions implements IAdminServerActions, SocketServer {
async clearOriginsForAccounts(accounts: string[], options: ClearOrignsOptions) {
if (!this.adminService.loaded) {
throw new Error('Not loaded yet');
- } else {
+ }
+ else {
await clearOriginsForAccounts(this.adminService, accounts, options);
}
}
@@ -392,7 +401,8 @@ export class AdminServerActions implements IAdminServerActions, SocketServer {
async setAge(accountId: string, age: number) {
if (age === -1) {
await Account.updateOne({ _id: accountId }, { $unset: { birthyear: 1 } }).exec();
- } else {
+ }
+ else {
const birthyear = (new Date()).getFullYear() - age;
await Account.updateOne({ _id: accountId }, { birthyear }).exec();
}
@@ -479,7 +489,8 @@ export class AdminServerActions implements IAdminServerActions, SocketServer {
if (origin && origin.ip && origin.country) {
await addOrigin(accountId, origin);
system(accountId, `Added origin (${JSON.stringify(origin)}) ${this.by()}`);
- } else {
+ }
+ else {
throw new Error('Invalid origin');
}
}
diff --git a/src/ts/server/api/account.ts b/src/ts/server/api/account.ts
index 446c4fa..6dd369a 100644
--- a/src/ts/server/api/account.ts
+++ b/src/ts/server/api/account.ts
@@ -243,9 +243,11 @@ export const createRemoveSite =
if (!auth || auth.disabled) {
throw new UserError('Social account not found');
- } else if (auths === 1) {
+ }
+ else if (auths === 1) {
throw new UserError('Cannot remove your only one social account');
- } else {
+ }
+ else {
log(account._id, `removed auth: ${auth.name} [${auth._id}]`);
await Auth.updateOne({ _id: auth._id }, { disabled: true }).exec();
}
diff --git a/src/ts/server/api/admin-accounts.ts b/src/ts/server/api/admin-accounts.ts
index 1bcc724..116aff2 100644
--- a/src/ts/server/api/admin-accounts.ts
+++ b/src/ts/server/api/admin-accounts.ts
@@ -98,7 +98,8 @@ export async function updateAccountSafe(accountId: string, update: AccountUpdate
export async function setRole(accountId: string, role: string, set: boolean, isSuperadmin: boolean) {
if (role === 'superadmin' || !isSuperadmin) {
throw new Error('Not allowed');
- } else {
+ }
+ else {
await updateAccountAndNotify(accountId, set ? { $addToSet: { roles: [role] } } : { $pull: { roles: role } });
}
}
@@ -139,7 +140,8 @@ export async function findAccounts(
if (cache.findAccounts && isValidCache(cache.findAccounts, query, 5 * MINUTE)) {
found = cache.findAccounts.result;
- } else {
+ }
+ else {
found = filterAccounts(service.accounts.items, search, showOnly, not);
cache.findAccounts = {
query,
diff --git a/src/ts/server/api/admin-auths.ts b/src/ts/server/api/admin-auths.ts
index 592efcd..30f0764 100644
--- a/src/ts/server/api/admin-auths.ts
+++ b/src/ts/server/api/admin-auths.ts
@@ -5,16 +5,21 @@ import { checkIfNotAdmin } from '../accountUtils';
export async function assignAuth(authId: string, accountId: string) {
const auth = await Auth.findById(authId).exec();
- if (!auth)
+ if (!auth) {
return;
+ }
const [src, dest] = await Promise.all([
Account.findById(auth.account).exec(),
Account.findById(accountId).exec(),
]);
- src && checkIfNotAdmin(src, `assign auth from ${src._id}`);
- dest && checkIfNotAdmin(dest, `assign auth to ${dest._id}`);
+ if (src) {
+ checkIfNotAdmin(src, `assign auth from ${src._id}`);
+ }
+ if (dest) {
+ checkIfNotAdmin(dest, `assign auth to ${dest._id}`);
+ }
await Auth.updateOne({ _id: authId }, { account: accountId }).exec();
}
@@ -22,12 +27,15 @@ export async function assignAuth(authId: string, accountId: string) {
export async function removeAuth(service: AdminService, authId: string) {
const auth = await Auth.findById(authId).exec();
- if (!auth)
+ if (!auth) {
return;
+ }
if (auth.account) {
const account = await Account.findById(auth.account).exec();
- account && checkIfNotAdmin(account, `remove auth from ${account._id}`);
+ if (account) {
+ checkIfNotAdmin(account, `remove auth from ${account._id}`);
+ }
}
await Auth.deleteOne({ _id: authId }).exec();
diff --git a/src/ts/server/api/admin.ts b/src/ts/server/api/admin.ts
index a6fb996..ca7854d 100644
--- a/src/ts/server/api/admin.ts
+++ b/src/ts/server/api/admin.ts
@@ -124,13 +124,15 @@ export async function getChat(search: string, date: string, caseInsensitive: boo
try {
if (!search) {
return '';
- } else if (date === 'all') {
+ }
+ else if (date === 'all') {
const { stdout } = await execAsync(`for f in ${paths.pathTo('logs')}/*.log; do `
+ `echo "$f" | grep -o '[0-9]*';`
+ `cat "$f" | grep ${flags}"${query}";`
+ `done`, options);
return stdout;
- } else {
+ }
+ else {
let lines = 8192;
let more = '';
@@ -138,7 +140,8 @@ export async function getChat(search: string, date: string, caseInsensitive: boo
try {
const log = await fetchChatlog(lines);
return more + log;
- } catch (e) {
+ }
+ catch (e) {
if (isErrorAlike(e) && e.message !== 'stdout maxBuffer exceeded') {
throw e;
}
@@ -150,7 +153,8 @@ export async function getChat(search: string, date: string, caseInsensitive: boo
return '';
}
- } catch (e) {
+ }
+ catch (e) {
console.error('Failed to fetch chatlog: ', e);
return '';
}
@@ -191,7 +195,8 @@ export async function clearSessions(accountId: string) {
clearIds.push(session._id.toString());
}
}
- } catch (e) {
+ }
+ catch (e) {
logger.error('Error when clearing session', e, session._id, session.session);
}
});
@@ -210,7 +215,8 @@ export async function getUserCounts(): Promise {
const content = await fs.readFileAsync(statsFile, 'utf8');
const lines = content.trim().split(/\n/);
return lines.map(line => JSON.parse(line));
- } catch {
+ }
+ catch {
return [];
}
}
@@ -264,7 +270,8 @@ export async function getOtherStats(service: AdminService): Promise
for (const auth of service.auths.items) {
if (!auth.account) {
authsWithEmptyAccount++;
- } else if (!service.accounts.get(auth.account)) {
+ }
+ else if (!service.accounts.get(auth.account)) {
authsWithMissingAccount++;
}
}
diff --git a/src/ts/server/api/duplicates.ts b/src/ts/server/api/duplicates.ts
index 9608f99..ab7f93f 100644
--- a/src/ts/server/api/duplicates.ts
+++ b/src/ts/server/api/duplicates.ts
@@ -110,7 +110,8 @@ async function getAllDuplicates(service: AdminService, accountId: string): Promi
if (!account) {
return [];
- } else {
+ }
+ else {
return uniq([
...getDuplicatesByNote(service, account),
...getDuplicatesByEmail(service, account),
diff --git a/src/ts/server/api/game.ts b/src/ts/server/api/game.ts
index 25ce16c..552ee96 100644
--- a/src/ts/server/api/game.ts
+++ b/src/ts/server/api/game.ts
@@ -39,26 +39,33 @@ export const createJoinGame =
hasInvites(account._id),
]);
- if (clientVersion !== version)
+ if (clientVersion !== version) {
throw new UserError(VERSION_ERROR);
+ }
- if (new URL(url).host !== new URL(host).host && !debug && !local)
- throw new UserError('Invalid data', { message: 'Invalid host', desc: url });
+ if (new URL(url).host !== new URL(host).host && !debug && !local) {
+ throw new UserError('Invalid data', { message: 'Invalid host', desc: url });
+ }
- if (!server)
+ if (!server) {
throw new UserError('Invalid data');
+ }
- if (isServerOffline(server))
+ if (isServerOffline(server)) {
throw new UserError('Server is offline');
+ }
- if (server.state.settings.blockJoining)
+ if (server.state.settings.blockJoining) {
throw new UserError('Cannot join to the server');
+ }
- if (!meetsRequirement({ roles: account.roles, supporter: supporterLevel(account), supporterInvited }, server.state.require))
+ if (!meetsRequirement({ roles: account.roles, supporter: supporterLevel(account), supporterInvited }, server.state.require)) {
throw new UserError('Server is restricted');
+ }
- if (!characterId || typeof characterId !== 'string')
+ if (!characterId || typeof characterId !== 'string') {
throw new UserError('Invalid data', { message: 'Invalid pony ID', desc: `"${characterId}"` });
+ }
const req = waiting.get(accountId);
const time = new Date();
@@ -86,7 +93,8 @@ export const createJoinGame =
await addOrigin(account, origin);
const token = await join(server, account, character!);
return { token };
- } finally {
+ }
+ finally {
waiting.delete(accountId);
}
};
diff --git a/src/ts/server/api/internal.ts b/src/ts/server/api/internal.ts
index 8cdbee8..60243e3 100644
--- a/src/ts/server/api/internal.ts
+++ b/src/ts/server/api/internal.ts
@@ -207,9 +207,11 @@ export const createKick =
if (accountId) {
clearTokensForAccount(accountId);
return world.kickByAccount(accountId);
- } else if (characterId) {
+ }
+ else if (characterId) {
return world.kickByCharacter(characterId);
- } else {
+ }
+ else {
return false;
}
};
@@ -296,13 +298,15 @@ function getSupportStats(world: World): StatsTable {
for (const client of world.clients) {
if (client.supportsWasm) {
wasmYes++;
- } else {
+ }
+ else {
wasmNo++;
}
if (client.supportsLetAndConst) {
letAndConstYes++;
- } else {
+ }
+ else {
letAndConstNo++;
}
}
diff --git a/src/ts/server/api/merge.ts b/src/ts/server/api/merge.ts
index 57a32c8..db07496 100644
--- a/src/ts/server/api/merge.ts
+++ b/src/ts/server/api/merge.ts
@@ -74,7 +74,8 @@ function mergeStates(a: AccountState | undefined, b: AccountState | undefined) {
clovers: toInt(a.clovers) + toInt(b.clovers),
toys: toInt(a.toys) | toInt(b.toys),
};
- } else {
+ }
+ else {
return a || b;
}
}
@@ -169,7 +170,8 @@ async function removeDuplicateFriendRequests(id: string) {
if (checked.has(friendId)) {
removeRequests.push(request._id);
- } else {
+ }
+ else {
checked.add(friendId);
}
}
diff --git a/src/ts/server/api/origins.ts b/src/ts/server/api/origins.ts
index a482833..871d105 100644
--- a/src/ts/server/api/origins.ts
+++ b/src/ts/server/api/origins.ts
@@ -22,13 +22,15 @@ export async function getOriginStats(accounts: Account[]): Promise
if (uniques.has(origin.ip)) {
duplicates.add(origin.ip);
- } else {
+ }
+ else {
uniques.add(origin.ip);
}
if (origin.ip.indexOf(':') !== -1) {
totalOriginsIP6++;
- } else {
+ }
+ else {
totalOriginsIP4++;
}
}
diff --git a/src/ts/server/api/ponies.ts b/src/ts/server/api/ponies.ts
index 18a1150..c1eda5d 100644
--- a/src/ts/server/api/ponies.ts
+++ b/src/ts/server/api/ponies.ts
@@ -20,9 +20,11 @@ function createQuery({ search }: FindPonyQuery) {
if (search) {
if (search === 'orphan') {
and.push({ account: { $exists: false } });
- } else if (/^exact:/.test(search)) {
+ }
+ else if (/^exact:/.test(search)) {
and.push({ name: new RegExp(`^${escapeRegExp(search.substr(6))}$`, 'i') });
- } else {
+ }
+ else {
and.push({ name: new RegExp(escapeRegExp(search), 'i') });
}
}
@@ -57,8 +59,9 @@ export async function findPonies(query: FindPonyQuery, page: number) {
export async function assignCharacter(characterId: string, accountId: string) {
const character = await Character.findById(characterId).exec();
- if (!character)
+ if (!character) {
return;
+ }
await kickFromAllServersByCharacter(characterId);
await Character.updateOne({ _id: characterId }, { account: accountId }).exec();
@@ -71,8 +74,9 @@ export async function assignCharacter(characterId: string, accountId: string) {
export async function removeCharacter(service: AdminService, characterId: string) {
const character = await Character.findById(characterId).exec();
- if (!character)
+ if (!character) {
return;
+ }
await kickFromAllServersByCharacter(characterId);
await character.deleteOne();
diff --git a/src/ts/server/api/pony.ts b/src/ts/server/api/pony.ts
index 661441b..eb33ff5 100644
--- a/src/ts/server/api/pony.ts
+++ b/src/ts/server/api/pony.ts
@@ -92,7 +92,8 @@ export const createSavePony =
character.info = info;
character.flags = flags;
character.lastUsed = new Date();
- } catch (error) {
+ }
+ catch (error) {
const message = DEVELOPMENT ? `${CHARACTER_SAVING_ERROR} (${error})` : CHARACTER_SAVING_ERROR;
throw new UserError(message, { error: isError(error) ? error : new Error('Unknown error'), data: { pony: data }, desc: `info: "${data.info}"` });
}
@@ -116,7 +117,8 @@ export const createSavePony =
if (created) {
log(account._id.toString(), `created pony "${character.name}"`);
- } else if (nameChanged) {
+ }
+ else if (nameChanged) {
log(account._id.toString(), `renamed pony "${oldName}" => "${character.name}"`);
}
diff --git a/src/ts/server/authUtils.ts b/src/ts/server/authUtils.ts
index 3f9a401..09c42fc 100644
--- a/src/ts/server/authUtils.ts
+++ b/src/ts/server/authUtils.ts
@@ -12,7 +12,8 @@ export async function assignAuth(auth: IAuth, account: IAccount) {
system(account._id, `connected auth ${auth.name} [${auth._id}]`);
await updateAuth(auth._id, { account: account._id });
return true;
- } else {
+ }
+ else {
return false;
}
}
@@ -22,7 +23,8 @@ export async function findOrCreateAuth(profile: Profile, accountId: string | und
if (auth) {
await updateAuthInfo(updateAuth, auth, profile, accountId);
- } else {
+ }
+ else {
if (options.connectOnly && !accountId) {
if (profile.emails.length) {
const account = await Account.findOne({ emails: { $in: profile.emails } }).exec();
@@ -30,7 +32,8 @@ export async function findOrCreateAuth(profile: Profile, accountId: string | und
if (!account) {
throw new UserError(connectOnlySocialError);
}
- } else {
+ }
+ else {
throw new UserError(connectOnlySocialError);
}
}
@@ -45,8 +48,9 @@ export async function findOrCreateAuth(profile: Profile, accountId: string | und
export async function updateAuthInfo(
updateAuth: UpdateAuth, auth: IAuth | undefined, profile: Profile, accountId: string | undefined
) {
- if (!auth)
+ if (!auth) {
return;
+ }
const changes: MongoUpdate = {};
@@ -96,7 +100,8 @@ async function verifyOrRestoreAuth(auth: IAuth, mergeAccount: string | undefined
if (auth.disabled || auth.banned) {
if (!auth.banned && auth.account && !!mergeAccount) {
changes.disabled = false;
- } else {
+ }
+ else {
throw new UserError('Cannot sign-in using this social account');
}
}
diff --git a/src/ts/server/boot.ts b/src/ts/server/boot.ts
index 6cca835..49aa718 100644
--- a/src/ts/server/boot.ts
+++ b/src/ts/server/boot.ts
@@ -1,5 +1,6 @@
///
+// eslint-disable-next-line @typescript-eslint/no-require-imports
require('source-map-support').install();
import 'core-js/stable/promise/finally';
diff --git a/src/ts/server/characterUtils.ts b/src/ts/server/characterUtils.ts
index 4b5284f..da2b105 100644
--- a/src/ts/server/characterUtils.ts
+++ b/src/ts/server/characterUtils.ts
@@ -80,13 +80,15 @@ export function updatePonyFromState(pony: ServerEntity, state: CharacterState) {
if (type) {
pony.options.hold = type;
}
- } else if (pony.options.hold) {
+ }
+ else if (pony.options.hold) {
pony.options.hold = 0;
}
if (state.toy) {
pony.options.toy = state.toy;
- } else if (pony.options.toy) {
+ }
+ else if (pony.options.toy) {
pony.options.toy = 0;
}
@@ -120,7 +122,8 @@ export function updatePony(pony: ServerEntity, account: IAccount, character: ICh
if (character.tag && canUseTag(account, character.tag)) {
options.tag = character.tag;
- } else if (level && !hasFlag(character.flags, CharacterFlags.HideSupport)) {
+ }
+ else if (level && !hasFlag(character.flags, CharacterFlags.HideSupport)) {
options.tag = `sup${level}`;
}
@@ -139,7 +142,8 @@ export function updatePony(pony: ServerEntity, account: IAccount, character: ICh
ponyInfo.cm = undefined;
pony.infoSafe = compressPony(ponyInfo);
pony.encryptedInfoSafe = encryptInfo(pony.infoSafe);
- } else {
+ }
+ else {
pony.infoSafe = pony.info;
pony.encryptedInfoSafe = encryptInfo(info);
}
@@ -179,8 +183,9 @@ export function logRemovedCharacter({ _id, account, name, info }: ICharacter) {
}
export async function swapCharacter(client: IClient, { server }: World, query: QueryFilter) {
- if (client.isSwitchingMap)
+ if (client.isSwitchingMap) {
return;
+ }
if ((Date.now() - client.lastSwap) < SWAP_TIMEOUT) {
return;
diff --git a/src/ts/server/chat.ts b/src/ts/server/chat.ts
index c6375d1..88a6797 100644
--- a/src/ts/server/chat.ts
+++ b/src/ts/server/chat.ts
@@ -97,11 +97,13 @@ export const createSay =
const { command, args, type } = parseCommand(text, chatType);
const whisper = type === ChatType.Whisper;
- if (!command && !args)
+ if (!command && !args) {
return;
+ }
- if (whisper && client === target)
+ if (whisper && client === target) {
return;
+ }
const forbidden = command == null && isPublicChat(type) && isForbiddenMessage(args);
@@ -120,29 +122,34 @@ export const createSay =
checkSpam(client, text, settings);
}
}
- } else {
+ }
+ else {
const expression = parseExpression(text.substr(1), true);
if (expression) {
setEntityExpression(client.pony, expression);
- } else {
+ }
+ else {
saySystem(client, 'Invalid command');
}
}
- } else {
+ }
+ else {
const message = args;
const think = type === ChatType.Think || type === ChatType.PartyThink;
const expression = (think || whisper) ? undefined : parseExpression(message);
if (expression) {
setEntityExpression(client.pony, expression);
- } else if (!whisper && isLaugh(message)) {
+ }
+ else if (!whisper && isLaugh(message)) {
execAction(client, Action.Laugh, settings);
}
if (isPartyChat(type)) {
sayToParty(client, message, think ? MessageType.PartyThinking : MessageType.Party);
- } else {
+ }
+ else {
const friendWhisper = whisper && target !== undefined && isFriend(client, target);
const messageNoLinks = filterUrls(message);
const messageCensored = forbidden ? repeat('*', messageNoLinks.length) : filterBadWords(messageNoLinks);
@@ -171,11 +178,14 @@ export const createSay =
}
world.kick(client, 'swearing', LeaveReason.Swearing);
- } else if (!friendWhisper && forbidden) {
+ }
+ else if (!friendWhisper && forbidden) {
sayTo(client, client.pony, trimmedMessage, messageType);
- } else if (whisper) {
+ }
+ else if (whisper) {
sayWhisper(client, trimmedMessage, trimmedCensored, messageType, target, settings);
- } else {
+ }
+ else {
sayToEveryone(client, trimmedMessage, trimmedCensored, messageType, settings);
}
}
@@ -236,14 +246,17 @@ function sayWhisper(
) {
if (target === undefined || target.shadowed || isHiddenBy(client, target)) {
saySystem(client, `Couldn't find this player`);
- } else {
+ }
+ else {
const friend = isFriend(client, target);
if (!friend && client.accountSettings.ignoreNonFriendWhispers) {
saySystem(client, `You can only whisper to friends`);
- } else if (!friend && target.accountSettings.ignoreNonFriendWhispers) {
+ }
+ else if (!friend && target.accountSettings.ignoreNonFriendWhispers) {
saySystem(client, `Can't whisper to this player`);
- } else {
+ }
+ else {
sayTo(client, target.pony, message, toMessageType(type));
if (!isMutedOrShadowed(client)) {
@@ -256,9 +269,11 @@ function sayWhisper(
function sayToParty(client: IClient, message: string, type: MessageType) {
if (!client.party) {
saySystem(client, `you're not in a party`);
- } else if (isMutedOrShadowed(client)) {
+ }
+ else if (isMutedOrShadowed(client)) {
sayTo(client, client.pony, message, type);
- } else {
+ }
+ else {
for (const c of client.party.clients) {
sayTo(c, client.pony, message, type);
}
@@ -283,7 +298,8 @@ export function sayToEveryone(
client.accountSettings.ignorePublicChat
) {
sayTo(client, client.pony, message, type);
- } else {
+ }
+ else {
sayToAll(client.pony, message, censoredMessage, type, settings);
}
}
@@ -293,9 +309,11 @@ export function sayToOthers(
) {
if (isWhisper(type)) {
sayWhisper(client, message, message, type, target, settings);
- } else if (isPartyMessage(type)) {
+ }
+ else if (isPartyMessage(type)) {
sayToParty(client, message, type);
- } else {
+ }
+ else {
sayToEveryone(client, message, message, type, settings);
}
}
diff --git a/src/ts/server/cmUtils.ts b/src/ts/server/cmUtils.ts
index 7192f74..2eec786 100644
--- a/src/ts/server/cmUtils.ts
+++ b/src/ts/server/cmUtils.ts
@@ -432,8 +432,9 @@ export function theSameColor(a: LAB, b: LAB, delta = 27): boolean { // 27
}
export function isBadCM(cmString: string[], coatColor: string | undefined): string | undefined {
- if (!cmString || !cmString.length)
+ if (!cmString || !cmString.length) {
return undefined;
+ }
const pad = CM_SIZE * CM_SIZE - cmString.length;
const coat = hexToLab(coatColor || '000000');
diff --git a/src/ts/server/commands.ts b/src/ts/server/commands.ts
index f48ea40..bc625ef 100644
--- a/src/ts/server/commands.ts
+++ b/src/ts/server/commands.ts
@@ -58,8 +58,9 @@ export interface Command {
}
function hasRoleNull(client: IClient, role: string) {
- if (!role || hasRole(client.account, role))
+ if (!role || hasRole(client.account, role)) {
return true;
+ }
return (role === 'sup1' && (client.supporterLevel >= 1 || client.isMod)) ||
(role === 'sup2' && (client.supporterLevel >= 2 || client.isMod)) ||
@@ -263,15 +264,18 @@ export function createCommands(world: World): Command[] {
// house
command(['savehouse'], '/savehouse - saves current house setup', '', async ({ }, client) => {
- if (!isValidMapForEditing(client.map, client, true, false))
+ if (!isValidMapForEditing(client.map, client, true, false)) {
return;
+ }
client.lastMapLoadOrSave = Date.now();
const savedMap = JSON.stringify(saveMap(client.map,
{ saveTiles: true, saveEntities: true, saveWalls: true, saveOnlyEditableEntities: true }));
- DEVELOPMENT && console.log(savedMap);
+ if (DEVELOPMENT) {
+ console.log(savedMap);
+ }
client.account.savedMap = savedMap;
await Account.updateOne({ _id: client.accountId }, { savedMap }).exec();
@@ -280,11 +284,13 @@ export function createCommands(world: World): Command[] {
client.reporter.systemLog(`Saved house`);
}),
command(['loadhouse'], '/loadhouse - loads saved house setup', '', ({ world }, client) => {
- if (!isValidMapForEditing(client.map, client, true, true))
+ if (!isValidMapForEditing(client.map, client, true, true)) {
return;
+ }
- if (!client.account.savedMap)
+ if (!client.account.savedMap) {
return saySystem(client, 'No saved map state');
+ }
client.lastMapLoadOrSave = Date.now();
@@ -295,8 +301,9 @@ export function createCommands(world: World): Command[] {
client.reporter.systemLog(`Loaded house`);
}),
command(['resethouse'], '/resethouse - resets house setup to original state', '', ({ }, client) => {
- if (!isValidMapForEditing(client.map, client, true, true))
+ if (!isValidMapForEditing(client.map, client, true, true)) {
return;
+ }
client.lastMapLoadOrSave = Date.now();
@@ -309,8 +316,9 @@ export function createCommands(world: World): Command[] {
client.reporter.systemLog(`Reset house`);
}),
command(['lockhouse'], '/lockhouse - prevents other people from changing the house', '', ({ }, client) => {
- if (!isValidMapForEditing(client.map, client, false, true))
+ if (!isValidMapForEditing(client.map, client, false, true)) {
return;
+ }
client.map.editingLocked = true;
@@ -318,8 +326,9 @@ export function createCommands(world: World): Command[] {
client.reporter.systemLog(`House locked`);
}),
command(['unlockhouse'], '/unlockhouse - enables editing by other people', '', ({ }, client) => {
- if (!isValidMapForEditing(client.map, client, false, true))
+ if (!isValidMapForEditing(client.map, client, false, true)) {
return;
+ }
client.map.editingLocked = false;
@@ -327,8 +336,9 @@ export function createCommands(world: World): Command[] {
client.reporter.systemLog(`House unlocked`);
}),
command(['removetoolbox'], '/removetoolbox - removes toolbox from the house', '', ({ world }, client) => {
- if (!isValidMapForEditing(client.map, client, true, true))
+ if (!isValidMapForEditing(client.map, client, true, true)) {
return;
+ }
client.lastMapLoadOrSave = Date.now();
@@ -338,8 +348,9 @@ export function createCommands(world: World): Command[] {
client.reporter.systemLog(`Toolbox removed`);
}),
command(['restoretoolbox'], '/restoretoolbox - restores toolbox to the house', '', ({ }, client) => {
- if (!isValidMapForEditing(client.map, client, true, true))
+ if (!isValidMapForEditing(client.map, client, true, true)) {
return;
+ }
client.lastMapLoadOrSave = Date.now();
@@ -420,7 +431,8 @@ export function createCommands(world: World): Command[] {
if (season === undefined) {
throw new UserError('invalid season');
- } else {
+ }
+ else {
world.setSeason(season, holiday === undefined ? world.holiday : holiday);
}
}),
@@ -429,7 +441,8 @@ export function createCommands(world: World): Command[] {
if (weather === undefined) {
throw new UserError('invalid weather');
- } else {
+ }
+ else {
updateMapState(client.map, { weather });
}
}),
@@ -484,12 +497,14 @@ export function createCommands(world: World): Command[] {
if (interval) {
clearInterval(interval);
interval = undefined;
- } else {
+ }
+ else {
interval = setInterval(() => {
if (includes(world.clients, client)) {
const message = range(random(1, 10)).map(() => randomString(random(1, 10))).join(' ');
sayToEveryone(client, message, message, MessageType.Chat, settings);
- } else {
+ }
+ else {
clearInterval(interval);
}
}, 100);
@@ -522,7 +537,8 @@ export function createCommands(world: World): Command[] {
const { id, type, x, y, options } = entity;
const info = { id, type: getEntityTypeName(type), x, y, options };
saySystem(client, JSON.stringify(info, null, 2));
- } else {
+ }
+ else {
saySystem(client, 'undefined');
}
}),
@@ -562,13 +578,16 @@ export const createRunCommand =
try {
if (func && hasRoleNull(client, func.role)) {
func.handler(context, client, args, type, target, settings);
- } else {
+ }
+ else {
return false;
}
- } catch (e) {
+ }
+ catch (e) {
if (isUserError(e)) {
saySystem(client, e.message);
- } else {
+ }
+ else {
throw e;
}
}
@@ -605,7 +624,8 @@ export function parseCommand(text: string, type: ChatType): { command?: string;
if (chatType !== undefined) {
if (chatType === ChatType.Think) {
type = type === ChatType.Party ? ChatType.PartyThink : ChatType.Think;
- } else {
+ }
+ else {
type = chatType;
}
diff --git a/src/ts/server/config.ts b/src/ts/server/config.ts
index 52f675b..11731e7 100644
--- a/src/ts/server/config.ts
+++ b/src/ts/server/config.ts
@@ -73,7 +73,9 @@ export interface AppArgs {
}
export const args = argv as AppArgs;
+// eslint-disable-next-line @typescript-eslint/no-require-imports
export const { version, description }: AppPackage = require('../../../package.json');
+// eslint-disable-next-line @typescript-eslint/no-require-imports
export const config: AppConfig = require('../../../config.json');
// append / to host if the server op forgot it
diff --git a/src/ts/server/controllerUtils.ts b/src/ts/server/controllerUtils.ts
index d8b17ee..00156d8 100644
--- a/src/ts/server/controllerUtils.ts
+++ b/src/ts/server/controllerUtils.ts
@@ -12,7 +12,8 @@ export function give(type: number, message?: string) {
return (e: ServerEntity, client: IClient) => {
if (client.pony.options && client.pony.options.hold === type) {
unholdItem(client.pony);
- } else {
+ }
+ else {
if (message) {
sayTo(client, e, message, MessageType.Announcement);
}
@@ -71,7 +72,8 @@ export function updateLights(entities: ServerEntity[], on: boolean) {
if (entity.lightDelay === undefined || entity.lightDelay < Date.now()) {
if (on) {
turnOn(entity);
- } else {
+ }
+ else {
turnOff(entity);
}
}
@@ -96,7 +98,8 @@ export function createFenceMaker(
if (horizontal) {
add(sample(beamsH)!(x + dx * i + (size / 2), y));
- } else {
+ }
+ else {
add(sample(beamsV)!(x, y + dy * i));
}
}
diff --git a/src/ts/server/controllers/cloudController.ts b/src/ts/server/controllers/cloudController.ts
index 6c69d50..0bd32a8 100644
--- a/src/ts/server/controllers/cloudController.ts
+++ b/src/ts/server/controllers/cloudController.ts
@@ -17,8 +17,9 @@ export class CloudController implements Controller {
constructor(private world: World, private map: ServerMap, private cloudCount: number) {
}
initialize() {
- if (this.initialized)
+ if (this.initialized) {
return;
+ }
for (let i = 0; i < this.cloudCount; i++) {
this.addCloud(false, this.world.now / 1000);
diff --git a/src/ts/server/controllers/collectableController.ts b/src/ts/server/controllers/collectableController.ts
index 034334c..eba9b3f 100644
--- a/src/ts/server/controllers/collectableController.ts
+++ b/src/ts/server/controllers/collectableController.ts
@@ -61,7 +61,8 @@ export class CollectableController implements Controller {
if (this.check(client)) {
if (client.shadowed) {
pushRemoveEntityToClient(client, entity);
- } else {
+ }
+ else {
remove(this.items, e => e === entity);
this.world.removeEntity(entity, this.map);
this.generateItem();
diff --git a/src/ts/server/controllers/fakeClientController.ts b/src/ts/server/controllers/fakeClientController.ts
index 80d3657..3d2fc60 100644
--- a/src/ts/server/controllers/fakeClientController.ts
+++ b/src/ts/server/controllers/fakeClientController.ts
@@ -25,24 +25,28 @@ export class FakeClientsController implements Controller {
constructor(private world: World, private server: ServerConfig, private options: Options) {
}
initialize() {
- if (this.initialized)
+ if (this.initialized) {
return;
+ }
times(1000, async i => {
try {
const name = `perf-${i}`;
const account = await Account.findOne({ name }).exec();
- if (!account)
+ if (!account) {
throw new Error(`Missing debug account (${name})`);
+ }
const character = await Character.findOne({ account: account._id }).exec();
- if (!character)
+ if (!character) {
throw new Error(`Missing debug character (${name})`);
+ }
this.tokens.push({ id: name, account, character });
- } catch (e) {
+ }
+ catch (e) {
console.error(e);
}
});
@@ -78,7 +82,8 @@ export class FakeClientsController implements Controller {
const client = await joinFakeClient(token, this.server, this.world);
this.clients.push(client);
}
- } catch (e) {
+ }
+ catch (e) {
console.error(e);
}
}
@@ -127,10 +132,12 @@ async function joinFakeClient(token: any, server: ServerConfig, world: World): P
}
break;
- } catch (e) {
+ }
+ catch (e) {
if (e instanceof RangeError || isDataViewError(e)) {
resizeWriter(packetWriter);
- } else {
+ }
+ else {
throw e;
}
}
diff --git a/src/ts/server/controllers/flyingCritterController.ts b/src/ts/server/controllers/flyingCritterController.ts
index c705fe7..beea0a5 100644
--- a/src/ts/server/controllers/flyingCritterController.ts
+++ b/src/ts/server/controllers/flyingCritterController.ts
@@ -69,7 +69,8 @@ export function updateTreehidingEntities(
for (const entity of entities) {
moveRandomly(map, entity, speed, 0.02, timestamp);
}
- } else if (entities.length) {
+ }
+ else if (entities.length) {
// head to tree and disappear
const trees = findTrees(map);
@@ -81,7 +82,8 @@ export function updateTreehidingEntities(
if (distanceXY(e.x, e.y, e.targetTree.x, e.targetTree.y + offsetY) < 0.1) {
entities.splice(i, 1);
world.removeEntity(e, map);
- } else {
+ }
+ else {
moveTowards(e, e.targetTree.x, e.targetTree.y + offsetY, speed, timestamp);
}
}
diff --git a/src/ts/server/controllers/perfController.ts b/src/ts/server/controllers/perfController.ts
index da3ba66..c06b296 100644
--- a/src/ts/server/controllers/perfController.ts
+++ b/src/ts/server/controllers/perfController.ts
@@ -44,8 +44,9 @@ export class PerfController implements Controller {
}
}
initialize() {
- if (this.initialized)
+ if (this.initialized) {
return;
+ }
const world = this.world;
const map = world.getMainMap();
@@ -106,9 +107,11 @@ export class PerfController implements Controller {
for (const entity of this.entities) {
if ((entity.vy > 0 && entity.y > limitBottom) || (entity.vy < 0 && entity.y < this.limitTop)) {
updateEntityVelocity(entity, entity.vx, -entity.vy, now);
- } else if ((entity.vx > 0 && entity.x > limitRight) || (entity.vx < 0 && entity.x < this.limitLeft)) {
+ }
+ else if ((entity.vx > 0 && entity.x > limitRight) || (entity.vx < 0 && entity.x < this.limitLeft)) {
updateEntityVelocity(entity, -entity.vx, entity.vy, now);
- } else if (Math.random() < 0.1) {
+ }
+ else if (Math.random() < 0.1) {
updateEntityVelocity(entity, randomVelocity(), randomVelocity(), now);
}
diff --git a/src/ts/server/controllers/testController.ts b/src/ts/server/controllers/testController.ts
index 77aa1b8..aaef8f5 100644
--- a/src/ts/server/controllers/testController.ts
+++ b/src/ts/server/controllers/testController.ts
@@ -16,8 +16,9 @@ export class TestController implements Controller {
constructor(private world: World, private map: ServerMap) {
}
initialize() {
- if (this.initialized)
+ if (this.initialized) {
return;
+ }
const world = this.world;
const map = this.map;
@@ -78,7 +79,9 @@ export class TestController implements Controller {
for (const client of this.clients) {
for (const notification of client.notifications) {
- notification.accept && notification.accept();
+ if (notification.accept) {
+ notification.accept();
+ }
}
}
diff --git a/src/ts/server/controllers/wallController.ts b/src/ts/server/controllers/wallController.ts
index 6542ffe..df244b8 100644
--- a/src/ts/server/controllers/wallController.ts
+++ b/src/ts/server/controllers/wallController.ts
@@ -47,8 +47,9 @@ export class WallController implements Controller {
};
const updateCorner = (x: number, y: number) => {
- if (x < 0 || y < 0 || x >= width || y >= height)
+ if (x < 0 || y < 0 || x >= width || y >= height) {
return;
+ }
const top = this.top;
const isOutside = x === 0 || y <= top || x === map.width || this.isTall(x, y);
@@ -66,38 +67,46 @@ export class WallController implements Controller {
};
this.toggleWall = (x, y, type) => {
- if (x < 0 || y < 0 || x >= width || y >= height)
+ if (x < 0 || y < 0 || x >= width || y >= height) {
return;
+ }
- if (this.lockedTiles.has(`${x},${y}:${type}`))
+ if (this.lockedTiles.has(`${x},${y}:${type}`)) {
return;
+ }
const walls = type === TileType.WallH ? hWalls : vWalls;
const entity = getAt(walls, x, y);
const top = this.top;
- if (type === TileType.WallH && x === (width - 1))
+ if (type === TileType.WallH && x === (width - 1)) {
return;
+ }
- if (type === TileType.WallV && y === (height - 1))
+ if (type === TileType.WallV && y === (height - 1)) {
return;
+ }
if (this.lockOuterWalls) {
- if (type === TileType.WallH && (y <= top || y === (width - 1)))
+ if (type === TileType.WallH && (y <= top || y === (width - 1))) {
return;
- if (type === TileType.WallV && (x === 0 || x === (height - 1) || y < top))
+ }
+ if (type === TileType.WallV && (x === 0 || x === (height - 1) || y < top)) {
return;
+ }
}
if (entity) {
world.removeEntity(entity, map);
setAt(walls, x, y, undefined);
- } else {
+ }
+ else {
if (type === TileType.WallH) {
const ctor = (y <= top || this.isTall(x, y)) ?
wallH : (x === 0 ? wallCutL : (x === (width - 2) ? wallCutR : wallHShort));
setAt(walls, x, y, world.addEntity(ctor(x + 0.5, y + yOffset), map));
- } else {
+ }
+ else {
const ctor = (x === 0 || x === (width - 1) || this.isTall(x, y)) ? wallV : wallVShort;
setAt(walls, x, y, world.addEntity(ctor(x, y + 0.5), map));
}
diff --git a/src/ts/server/db.ts b/src/ts/server/db.ts
index efa037b..5715cf3 100644
--- a/src/ts/server/db.ts
+++ b/src/ts/server/db.ts
@@ -17,8 +17,8 @@ export interface Doc extends Document {
updatedAt: Date;
}
-export interface IOriginInfo extends OriginInfoBase { }
-export interface ITimestamps extends TimestampsBase { }
+export type IOriginInfo = OriginInfoBase;
+export type ITimestamps = TimestampsBase;
export interface IAuth extends AuthBase, Doc { }
export interface IOrigin extends OriginBase, Doc { }
export interface IEvent extends EventBase, Doc { }
@@ -266,7 +266,8 @@ function throwOnEmpty(message: string): (item: T | undefined) => T {
return item => {
if (item) {
return item;
- } else {
+ }
+ else {
throw new Error(message);
}
};
@@ -473,8 +474,9 @@ export async function findHidesForMerge(accountId: ID): Promise
}
export async function addHide(source: ID, target: ID, name: string) {
- if (source.toString() === target.toString())
+ if (source.toString() === target.toString()) {
return;
+ }
const existing = await HideRequest.findOne({ source, target }, '_id').lean().exec();
diff --git a/src/ts/server/entityUtils.ts b/src/ts/server/entityUtils.ts
index 893e2e5..d159724 100644
--- a/src/ts/server/entityUtils.ts
+++ b/src/ts/server/entityUtils.ts
@@ -30,7 +30,8 @@ export function setEntityName(entity: ServerEntity, name: string) {
export function getEntityName(entity: ServerEntity, client: IClient) {
if (entity.name && entity.nameBad && client.accountSettings.filterSwearWords) {
return filterName(entity.name);
- } else {
+ }
+ else {
return entity.name;
}
}
@@ -45,7 +46,8 @@ export function isHoldingGrapes(e: ServerEntity) {
export function canBoopEntity(e: ServerEntity, boopRect: Rect) {
if (e.type === PONY_TYPE) {
return isHoldingGrapes(e);
- } else {
+ }
+ else {
return e.boop !== undefined && containsPoint(0, 0, boopRect, e.x + (e.boopX || 0), e.y + (e.boopY || 0));
}
}
@@ -82,13 +84,17 @@ export function moveRandomly(
if (e.x < 0) {
vx = 1;
- } else if (e.x > map.width) {
+ }
+ else if (e.x > map.width) {
vx = -1;
- } else if (e.y < 0) {
+ }
+ else if (e.y < 0) {
vy = 1;
- } else if (e.y > map.height) {
+ }
+ else if (e.y > map.height) {
vy = -1;
- } else {
+ }
+ else {
vx = Math.random() - 0.5;
vy = Math.random() - 0.5;
}
@@ -158,7 +164,8 @@ export function pushUpdateEntity(update: EntityUpdateBase) {
if (isEntityShadowed(entity)) {
pushUpdateEntityToClient(entity.client, update);
- } else if (entity.region) {
+ }
+ else if (entity.region) {
pushUpdateEntityToRegion(entity.region, update);
}
}
@@ -168,7 +175,8 @@ function resizePreserveWriter(error: Error, writer: BinaryWriter, offset: number
resizeWriterWithData(writer);
writer.offset = offset;
// DEVELOPMENT && console.log(`resize writer to ${writer.view.byteLength} (${error.message})`);
- } else {
+ }
+ else {
throw error;
}
}
@@ -183,7 +191,8 @@ export function pushAddEntityToClient(client: IClient, entity: ServerEntity) {
writeUint8(writer, UpdateType.AddEntity);
writeOneEntity(writer, entity, client);
break;
- } catch (e) {
+ }
+ catch (e) {
resizePreserveWriter(e as Error, writer, offset);
}
}
@@ -199,7 +208,8 @@ export function pushUpdateEntityToClient(client: IClient, update: EntityUpdateBa
writeUint8(writer, UpdateType.UpdateEntity);
writeOneUpdate(writer, entity, flags, x, y, vx, vy, options, action, playerState);
break;
- } catch (e) {
+ }
+ catch (e) {
resizePreserveWriter(e as Error, writer, offset);
}
}
@@ -214,7 +224,8 @@ export function pushRemoveEntityToClient(client: IClient, entity: ServerEntity)
writeUint8(writer, UpdateType.RemoveEntity);
writeUint32(writer, entity.id);
break;
- } catch (e) {
+ }
+ catch (e) {
resizePreserveWriter(e as Error, writer, offset);
}
}
@@ -231,7 +242,8 @@ export function pushUpdateTileToClient(client: IClient, x: number, y: number, ty
writeUint16(writer, y);
writeUint8(writer, type);
break;
- } catch (e) {
+ }
+ catch (e) {
resizePreserveWriter(e as Error, writer, offset);
}
}
diff --git a/src/ts/server/internal.ts b/src/ts/server/internal.ts
index f3a6a9b..dd2dd70 100644
--- a/src/ts/server/internal.ts
+++ b/src/ts/server/internal.ts
@@ -78,7 +78,7 @@ export function getServer(id: string) {
return server;
}
-export function createApi(host: string, url: string, apiToken: string): T {
+export function createApi(host: string, url: string, apiToken: string): T {
return new Proxy({} as any, {
get: (_, key) =>
async (...args: any[]) => {
@@ -115,7 +115,8 @@ async function join(joinServer: InternalGameServerState, account: IAccount, char
const kicked = await mapGameServers(s => {
if (isMod(account) && s !== joinServer) {
return false;
- } else {
+ }
+ else {
return s.api.kick(account._id.toString(), undefined).catch(e => (logger.error(e), false));
}
});
@@ -125,7 +126,8 @@ async function join(joinServer: InternalGameServerState, account: IAccount, char
}
return await joinServer.api.join(account._id.toString(), character._id.toString());
- } catch (error) {
+ }
+ catch (error) {
if (
typeof error === 'object' &&
error !== null &&
@@ -136,7 +138,8 @@ async function join(joinServer: InternalGameServerState, account: IAccount, char
(error as any).error.userError
) {
throw new UserError((error as any).error.error);
- } else {
+ }
+ else {
logger.error(error);
throw new Error('Internal error');
}
@@ -154,13 +157,16 @@ export async function accountChanged(accountId: string) {
await mapGameServers(s => {
s.api.accountChanged(accountId).catch(noop);
});
- } else {
+ }
+ else {
await accountChangedHandler(accountId);
}
}
export async function accountMerged(accountId: string, mergedId: string) {
- await mapGameServers(s => { s.api.accountMerged(accountId, mergedId).catch(noop); });
+ await mapGameServers(s => {
+ s.api.accountMerged(accountId, mergedId).catch(noop);
+ });
}
export async function accountStatus(accountId: string) {
@@ -194,7 +200,11 @@ export type RemovedDocument = ReturnType;
export const createRemovedDocument =
(endPoints: EndPoints | undefined, adminService: AdminService | undefined) =>
(model: 'events' | 'ponies' | 'accounts' | 'auths' | 'origins', id: string) => {
- endPoints && model in endPoints && (endPoints as any)[model].removedItem(id);
- adminService && adminService.removedItem(model, id);
+ if (endPoints && model in endPoints) {
+ (endPoints as any)[model].removedItem(id);
+ }
+ if (adminService) {
+ adminService.removedItem(model, id);
+ }
return adminServer ? adminServer.api.removedDocument(model, id).catch(noop) : Promise.resolve();
};
diff --git a/src/ts/server/liveEndPoint.ts b/src/ts/server/liveEndPoint.ts
index 058a234..bc2dc20 100644
--- a/src/ts/server/liveEndPoint.ts
+++ b/src/ts/server/liveEndPoint.ts
@@ -124,7 +124,8 @@ export function createLiveEndPoint(
fixItems(items);
logger.warn(`Fetching ${items.length} ${model.modelName}s [${items[ITEM_LIMIT + 1].updatedAt.toISOString()}]`);
}
- } catch (e) {
+ }
+ catch (e) {
logger.error(e);
}
})
@@ -132,8 +133,9 @@ export function createLiveEndPoint(
}
function fixItems(items: T[]) {
- if (fixing || !fix)
+ if (fixing || !fix) {
return;
+ }
fixing = true;
logger.info(`Fixing ${model.modelName}s`);
diff --git a/src/ts/server/logger.ts b/src/ts/server/logger.ts
index 2182d3c..7386ff9 100644
--- a/src/ts/server/logger.ts
+++ b/src/ts/server/logger.ts
@@ -88,9 +88,11 @@ export function chat(
if (ignored) {
mod = '[ignored]';
- } else if (isMutedOrShadowed(client)) {
+ }
+ else if (isMutedOrShadowed(client)) {
mod = '[muted]';
- } else if (client.accountSettings.ignorePublicChat && isPublicChat(type)) {
+ }
+ else if (client.accountSettings.ignorePublicChat && isPublicChat(type)) {
mod = '[ignorepub]';
}
diff --git a/src/ts/server/mapUtils.ts b/src/ts/server/mapUtils.ts
index 998d132..09c65a3 100644
--- a/src/ts/server/mapUtils.ts
+++ b/src/ts/server/mapUtils.ts
@@ -232,7 +232,8 @@ export function positionClover(map: ServerMap) {
y: patch.y + bounds.y / tileHeight + random(0, bounds.h / tileHeight, true),
};
return position;
- } else {
+ }
+ else {
return randomPosition(map);
}
}
@@ -246,8 +247,9 @@ export function createBunny(waypoints: Point[]) {
let sleepUntil = 0;
entity.serverUpdate = (_delta, now) => {
- if (sleepUntil > now)
+ if (sleepUntil > now) {
return;
+ }
const { x, y } = waypoints[waypoint];
const reachedX = Math.abs(entity.x - x) < 0.2;
@@ -260,21 +262,26 @@ export function createBunny(waypoints: Point[]) {
if (rand < 0.1) {
setEntityAnimation(entity, BunnyAnimation.Clean);
sleepUntil = now + 2;
- } else if (rand < 0.2) {
+ }
+ else if (rand < 0.2) {
setEntityAnimation(entity, BunnyAnimation.Look);
sleepUntil = now + 2;
- } else if (rand < 0.3) {
+ }
+ else if (rand < 0.3) {
setEntityAnimation(entity, BunnyAnimation.Blink);
sleepUntil = now + 2;
- } else if (rand < 0.6) {
+ }
+ else if (rand < 0.6) {
setEntityAnimation(entity, BunnyAnimation.Sit);
sleepUntil = now + 2;
- } else {
+ }
+ else {
waypoint = (waypoint + 1) % waypoints.length;
setEntityAnimation(entity, BunnyAnimation.Sit);
sleepUntil = now + random(0.2, 2, true);
}
- } else {
+ }
+ else {
const vx = reachedX ? 0 : (x < entity.x ? -bunnySpeed : bunnySpeed);
const vy = reachedY ? 0 : (y < entity.y ? -bunnySpeed : bunnySpeed);
@@ -287,7 +294,8 @@ export function createBunny(waypoints: Point[]) {
if (DEVELOPMENT && false) {
return [entity, ...waypoints.map(({ x, y }) => entities.routePole(x, y))];
- } else {
+ }
+ else {
return [entity];
}
}
diff --git a/src/ts/server/maps/caveMap.ts b/src/ts/server/maps/caveMap.ts
index 59c5dae..be0f182 100644
--- a/src/ts/server/maps/caveMap.ts
+++ b/src/ts/server/maps/caveMap.ts
@@ -43,21 +43,35 @@ export function createCaveMap(world: World): ServerMap {
const index1 = code & 0b11;
const index2 = (code >> 2) & 0b11;
const index3 = (code >> 4) & 0b11;
- index1 && index1 !== 3 && add(caveDecals[index1 - 1](x + 0.5, y - 1)); // no decal 2 here
- index2 && add(caveDecals[index2 - 1](x + 0.5, y));
- index3 && add(caveDecals[index3 - 1](x + 0.5, y + 1));
+ if (index1 && index1 !== 3) {
+ add(caveDecals[index1 - 1](x + 0.5, y - 1));
+ } // no decal 2 here
+ if (index2) {
+ add(caveDecals[index2 - 1](x + 0.5, y));
+ }
+ if (index3) {
+ add(caveDecals[index3 - 1](x + 0.5, y + 1));
+ }
}
function cracksSLeft(x: number, y: number) {
const code = (Math.random() * 1000) % 4;
- (code & 0b01) && add(entities.caveDecalL(x + 0.5, y - 1));
- (code & 0b10) && add(entities.caveDecalL(x + 0.5, y));
+ if (code & 0b01) {
+ add(entities.caveDecalL(x + 0.5, y - 1));
+ }
+ if (code & 0b10) {
+ add(entities.caveDecalL(x + 0.5, y));
+ }
}
function cracksSRight(x: number, y: number) {
const code = (Math.random() * 1000) % 4;
- (code & 0b01) && add(entities.caveDecalR(x + 0.5, y - 1));
- (code & 0b10) && add(entities.caveDecalR(x + 0.5, y));
+ if (code & 0b01) {
+ add(entities.caveDecalR(x + 0.5, y - 1));
+ }
+ if (code & 0b10) {
+ add(entities.caveDecalR(x + 0.5, y));
+ }
}
function caveSW(x: number, y: number) {
@@ -137,7 +151,8 @@ export function createCaveMap(world: World): ServerMap {
function caveTrimLeft(x: number, y: number, h: number, botTrim = true) {
if (botTrim) {
add(entities.caveBotTrimLeft(x - 0.5, y));
- } else {
+ }
+ else {
add(entities.caveMidTrimLeft(x - 0.5, y));
}
@@ -153,7 +168,8 @@ export function createCaveMap(world: World): ServerMap {
function caveTrimRight(x: number, y: number, h: number, botTrim = true) {
if (botTrim) {
add(entities.caveBotTrimRight(x + 0.5, y));
- } else {
+ }
+ else {
add(entities.caveMidTrimRight(x + 0.5, y));
}
@@ -563,7 +579,8 @@ export function createCaveMap(world: World): ServerMap {
add(createBoxOfLanterns(30.97, 49.63)).interact = (_, client) => {
if (client.pony.options!.hold === entities.crystalHeld.type) {
holdItem(client.pony, entities.crystalLantern.type);
- } else {
+ }
+ else {
holdItem(client.pony, entities.lanternOn.type);
}
};
@@ -880,14 +897,17 @@ export function createCaveMap(world: World): ServerMap {
map.controllers.push(wallController);
wallController.top = 3;
wallController.isTall = (x, y) => {
- if (y === 10 && x >= 17 && x <= 23)
+ if (y === 10 && x >= 17 && x <= 23) {
return true;
+ }
- if (x >= 31 && x <= 39 && y >= 22 && y <= 25)
+ if (x >= 31 && x <= 39 && y >= 22 && y <= 25) {
return true;
+ }
- if (y === 31 && x >= 33 && x <= 34)
+ if (y === 31 && x >= 33 && x <= 34) {
return true;
+ }
return false;
};
diff --git a/src/ts/server/maps/islandMap.ts b/src/ts/server/maps/islandMap.ts
index 3cf08b6..4b5e92b 100644
--- a/src/ts/server/maps/islandMap.ts
+++ b/src/ts/server/maps/islandMap.ts
@@ -38,7 +38,8 @@ export function createIslandMap(world: World, instanced: boolean, template = fal
if (islandMapTemplate) {
copyMapTiles(map, islandMapTemplate);
- } else {
+ }
+ else {
deserializeMap(map, islandMapData);
}
@@ -114,7 +115,8 @@ export function createIslandMap(world: World, instanced: boolean, template = fal
const ox = x === minX ? (18 / tileWidth) : (-18 / tileWidth);
const plank = sample(entities.planksShort)!;
add(plank(baseX + ox + x * plankWidth, baseY + y * plankHeight));
- } else {
+ }
+ else {
const plank = sample(entities.planks)!;
add(plank(baseX + x * plankWidth, baseY + y * plankHeight));
}
diff --git a/src/ts/server/maps/mainMap.ts b/src/ts/server/maps/mainMap.ts
index 1b5baa2..7e0e27e 100644
--- a/src/ts/server/maps/mainMap.ts
+++ b/src/ts/server/maps/mainMap.ts
@@ -115,10 +115,18 @@ function addSeasonalObjects(world: World, map: ServerMap, season: Season, holida
function addHollyDecoration(x: number, y: number, a = true, b = true, c = true, d = true) {
if (isChristmas) {
- a && addHolly(x - 2.8, y);
- b && addHolly(x - 1, y);
- c && addHolly(x + 1, y);
- d && addHolly(x + 2.8, y);
+ if (a) {
+ addHolly(x - 2.8, y);
+ }
+ if (b) {
+ addHolly(x - 1, y);
+ }
+ if (c) {
+ addHolly(x + 1, y);
+ }
+ if (d) {
+ addHolly(x + 2.8, y);
+ }
}
}
@@ -1030,7 +1038,8 @@ function addSeasonalObjects(world: World, map: ServerMap, season: Season, holida
delay = randomDelay();
reset = false;
resetDelay = 5;
- } else if (!reset && resetDelay < 0) {
+ }
+ else if (!reset && resetDelay < 0) {
setEntityAnimation(ghost, GhostAnimation.None);
setEntityAnimation(hooves, GhostAnimation.None);
reset = true;
@@ -1051,7 +1060,8 @@ function addSeasonalObjects(world: World, map: ServerMap, season: Season, holida
setEntityAnimation(entity, 1);
delay = 0.2;
open = false;
- } else {
+ }
+ else {
setEntityAnimation(entity, 0);
delay = random(5, 10, true);
open = true;
@@ -1473,15 +1483,19 @@ export function updateMainMapSeason(world: World, map: ServerMap, season: Season
if (isWinter) {
if (x > 18 && (tile === TileType.Water || tile === TileType.WalkableWater || tile === TileType.Boat)) {
setTile(map, x, y, tile === TileType.Water ? TileType.Ice : TileType.WalkableIce);
- } else {
+ }
+ else {
setTile(map, x, y, tile);
}
- } else {
+ }
+ else {
if (tile === TileType.Ice || tile === TileType.SnowOnIce) {
setTile(map, x, y, TileType.Water);
- } else if (tile === TileType.WalkableIce) {
+ }
+ else if (tile === TileType.WalkableIce) {
setTile(map, x, y, TileType.WalkableWater);
- } else {
+ }
+ else {
setTile(map, x, y, tile);
}
}
@@ -1572,21 +1586,35 @@ export function createMainMap(world: World): ServerMap {
const index1 = code & 0b11;
const index2 = (code >> 2) & 0b11;
const index3 = (code >> 4) & 0b11;
- index1 && index1 !== 3 && add(cliffDecals[index1 - 1](x + 0.5, y - 1)); // no decal 2 here
- index2 && add(cliffDecals[index2 - 1](x + 0.5, y));
- index3 && add(cliffDecals[index3 - 1](x + 0.5, y + 1));
+ if (index1 && index1 !== 3) {
+ add(cliffDecals[index1 - 1](x + 0.5, y - 1));
+ } // no decal 2 here
+ if (index2) {
+ add(cliffDecals[index2 - 1](x + 0.5, y));
+ }
+ if (index3) {
+ add(cliffDecals[index3 - 1](x + 0.5, y + 1));
+ }
}
function cracksSLeft(x: number, y: number) {
const code = (Math.random() * 1000) % 4;
- (code & 0b01) && add(entities.cliffDecalL(x + 0.5, y - 1));
- (code & 0b10) && add(entities.cliffDecalL(x + 0.5, y));
+ if (code & 0b01) {
+ add(entities.cliffDecalL(x + 0.5, y - 1));
+ }
+ if (code & 0b10) {
+ add(entities.cliffDecalL(x + 0.5, y));
+ }
}
function cracksSRight(x: number, y: number) {
const code = (Math.random() * 1000) % 4;
- (code & 0b01) && add(entities.cliffDecalR(x + 0.5, y - 1));
- (code & 0b10) && add(entities.cliffDecalR(x + 0.5, y));
+ if (code & 0b01) {
+ add(entities.cliffDecalR(x + 0.5, y - 1));
+ }
+ if (code & 0b10) {
+ add(entities.cliffDecalR(x + 0.5, y));
+ }
}
function cliffSW(x: number, y: number) {
@@ -1672,7 +1700,8 @@ export function createMainMap(world: World): ServerMap {
function cliffTrimRight(x: number, y: number, h: number, botTrim = true) {
if (botTrim) {
add(entities.cliffBotTrimRight(x + 0.5, y));
- } else {
+ }
+ else {
add(entities.cliffMidTrimRight(x + 0.5, y));
}
@@ -1946,7 +1975,8 @@ export function createMainMap(world: World): ServerMap {
if ((x === 0 && (y % 2)) || (x === (maxX - 1) && (y % 2))) {
const ox = x === 0 ? (18 / tileWidth) : (-18 / tileWidth);
add(shortPlank()(baseX + ox + x * plankWidth, baseY + y * plankHeight));
- } else {
+ }
+ else {
add(plank()(baseX + x * plankWidth, baseY + y * plankHeight));
}
}
@@ -2623,21 +2653,25 @@ export function createMainMap(world: World): ServerMap {
setEntityAnimation(entity, CatAnimation.Enter);
hideDelay = random(30, 60, true);
delay = random(2, 4, true);
- } else {
+ }
+ else {
hidden = true;
setEntityAnimation(entity, CatAnimation.Exit);
hideDelay = random(15, 30, true);
}
- } else if (!hidden && delay < 0) {
+ }
+ else if (!hidden && delay < 0) {
const rand = Math.random();
if (rand < 0.1) {
sayToAll(entity, 'meow', 'meow', MessageType.System, {});
delay = random(2, 4, true);
- } else if (rand < 0.5) {
+ }
+ else if (rand < 0.5) {
setEntityAnimation(entity, CatAnimation.Wag);
delay = random(2, 4, true);
- } else {
+ }
+ else {
setEntityAnimation(entity, CatAnimation.Blink);
delay = random(2, 4, true);
}
diff --git a/src/ts/server/move.ts b/src/ts/server/move.ts
index 0055e19..5befb51 100644
--- a/src/ts/server/move.ts
+++ b/src/ts/server/move.ts
@@ -24,8 +24,9 @@ export type Move = ReturnType;
export const createMove =
(teleportCounter: CounterService) =>
(client: IClient, now: number, a: number, b: number, c: number, d: number, e: number, settings: GameServerSettings) => {
- if (client.loading || client.fixingPosition || client.isSwitchingMap)
+ if (client.loading || client.fixingPosition || client.isSwitchingMap) {
return;
+ }
const connectionDuration = (now - client.connectedTime) >>> 0;
const pony = client.pony;
@@ -33,16 +34,19 @@ export const createMove =
const v = dirToVector(dir);
const speed = flagsToSpeed(flags);
- if (checkOutsideMap(client, x, y))
+ if (checkOutsideMap(client, x, y)) {
return;
+ }
setupCamera(client.camera, camera.x, camera.y, camera.w, camera.h, client.map);
- if (checkLagging(client, time, connectionDuration, settings))
+ if (checkLagging(client, time, connectionDuration, settings)) {
return;
+ }
- if (checkTeleporting(client, x, y, time, settings, teleportCounter))
+ if (checkTeleporting(client, x, y, time, settings, teleportCounter)) {
return;
+ }
if (!isStaticCollision(pony, client.map, true)) {
client.safeX = pony.x;
@@ -61,9 +65,12 @@ export const createMove =
client.reporter.systemLog(`Fixed colliding (${x} ${y}) -> (${pony.x} ${pony.y})`);
}
- DEVELOPMENT && !TESTS && logger.warn(`Fixing position due to collision`);
+ if (DEVELOPMENT && !TESTS) {
+ logger.warn(`Fixing position due to collision`);
+ }
fixPosition(pony, client.map, client.safeX, client.safeY, false);
- } else {
+ }
+ else {
pony.x = x;
pony.y = y;
}
@@ -142,8 +149,9 @@ function checkLagging(client: IClient, time: number, connectionTime: number, set
function checkTeleporting(
client: IClient, x: number, y: number, time: number, settings: GameServerSettings, counter: CounterService
): boolean {
- if (!client.lastTime)
+ if (!client.lastTime) {
return false;
+ }
const pony = client.pony;
const borderX = 0.5;
diff --git a/src/ts/server/oauth.ts b/src/ts/server/oauth.ts
index be161b1..0b611cc 100644
--- a/src/ts/server/oauth.ts
+++ b/src/ts/server/oauth.ts
@@ -106,15 +106,20 @@ export const providers = providerList.filter(p => !!p.auth);
export function getProfileUrl(profile: OAuthProfile): string | undefined {
if (profile.provider === 'twitter') {
return `https://twitter.com/${profile.username}`;
- } else if (profile.provider === 'tumblr') {
+ }
+ else if (profile.provider === 'tumblr') {
return `http://${profile.username}.tumblr.com/`;
- } else if (profile.provider === 'facebook') {
+ }
+ else if (profile.provider === 'facebook') {
return `http://www.facebook.com/${profile.id}`;
- } else if (profile.provider === 'discord') {
+ }
+ else if (profile.provider === 'discord') {
return undefined;
- } else if (profile._json.attributes && profile._json.attributes.url) { // patreon
+ }
+ else if (profile._json.attributes && profile._json.attributes.url) { // patreon
return profile._json.attributes.url;
- } else {
+ }
+ else {
return profile.profileUrl || profile._json.url;
}
}
@@ -124,29 +129,37 @@ export function getProfileEmails(profile: OAuthProfile): string[] {
// TODO: diagnose why we aren't receiving the email from Discord
// for now, we just won't attempt to record an email if we don't receive one
return profile.email ? [profile.email] : [];
- } else if (profile.emails && profile.emails.length) {
+ }
+ else if (profile.emails && profile.emails.length) {
return profile.emails.map(e => e.value);
- } else if (profile._json && profile._json.attributes && profile._json.attributes.email) { // patreon
+ }
+ else if (profile._json && profile._json.attributes && profile._json.attributes.email) { // patreon
return [profile._json.attributes.email];
- } else {
+ }
+ else {
return [];
}
}
export function getProfileUsername(profile: OAuthProfile): string | undefined {
- if (profile.provider === 'discord') return `${profile.username}#${profile.discriminator}`;
+ if (profile.provider === 'discord') {
+ return `${profile.username}#${profile.discriminator}`;
+ }
return profile.username || profile.displayName || getProfileNameInternal(profile.name);
}
export function getProfileName(profile: OAuthProfile): string | undefined {
- if (profile.provider === 'discord') return `${profile.username}#${profile.discriminator}`;
+ if (profile.provider === 'discord') {
+ return `${profile.username}#${profile.discriminator}`;
+ }
return profile.displayName || profile.username || getProfileNameInternal(profile.name);
}
function getProfileNameInternal(name: OAuthProfileName | undefined): string | undefined {
if (!name || isString(name)) {
return name;
- } else {
+ }
+ else {
return `${name.givenName} ${name.familyName}`.trim();
}
}
diff --git a/src/ts/server/originUtils.ts b/src/ts/server/originUtils.ts
index d566315..8648a53 100644
--- a/src/ts/server/originUtils.ts
+++ b/src/ts/server/originUtils.ts
@@ -4,6 +4,7 @@ import { config } from './config';
import { logger } from './logger';
import { OriginInfoBase } from '../common/adminInterfaces';
+// eslint-disable-next-line @typescript-eslint/no-require-imports, camelcase
const get_ip = require('ipware')().get_ip;
export function getIP(req: { headers: any; }) {
@@ -36,10 +37,12 @@ export async function addOrigin(account: IAccount, origin: IOriginInfo) {
if (existingOrigin) {
await Account.updateOne({ _id, 'origins._id': existingOrigin._id }, { $set: { 'origins.$.last': new Date() } }).exec();
- } else {
+ }
+ else {
await Account.updateOne({ _id }, { $push: { origins: origin } }).exec();
}
- } catch (e) {
+ }
+ catch (e) {
logger.error('Failed to add origin', e);
}
}
diff --git a/src/ts/server/playerUtils.ts b/src/ts/server/playerUtils.ts
index 76e9566..ab6e90c 100644
--- a/src/ts/server/playerUtils.ts
+++ b/src/ts/server/playerUtils.ts
@@ -222,18 +222,21 @@ export function removeIgnore(target: IClient, accountId: string) {
export const createIgnorePlayer =
(updateAccount: UpdateAccount, handlePromise = handlePromiseDefault) =>
(client: IClient, target: IClient, ignored: boolean) => {
- if (target.accountId === client.accountId)
+ if (target.accountId === client.accountId) {
return;
+ }
const id = client.accountId;
const is = isIgnored(client, target);
- if (ignored === is)
+ if (ignored === is) {
return;
+ }
if (ignored) {
addIgnore(target, id);
- } else {
+ }
+ else {
removeIgnore(target, id);
}
@@ -295,7 +298,8 @@ export function setEntityExpression(
if (expression && timeout) {
entity.exprTimeout = Date.now() + timeout;
- } else {
+ }
+ else {
entity.exprTimeout = undefined;
}
@@ -345,14 +349,19 @@ export function interactWith(client: IClient, target: ServerEntity | undefined)
if (target.interact && (!target.interactRange || distance(pony, target) < target.interactRange)) {
target.interact(target, client);
- } else if (target.triggerBounds && target.trigger) {
+ }
+ else if (target.triggerBounds && target.trigger) {
if (containsPointWitBorder(target.x, target.y, target.triggerBounds, pony.x, pony.y, 3)) {
target.trigger(target, client);
- } else {
- DEVELOPMENT && console.warn(`outside trigger bounds ` +
- `(bounds: ${target.x} ${target.y} ${JSON.stringify(target.triggerBounds)} point: ${pony.x} ${pony.y})`);
}
- } else if (target.interactAction) {
+ else {
+ if (DEVELOPMENT) {
+ console.warn(`outside trigger bounds ` +
+ `(bounds: ${target.x} ${target.y} ${JSON.stringify(target.triggerBounds)} point: ${pony.x} ${pony.y})`);
+ }
+ }
+ }
+ else if (target.interactAction) {
switch (target.interactAction) {
case InteractAction.Toolbox: {
switchTool(client, false);
@@ -361,7 +370,8 @@ export function interactWith(client: IClient, target: ServerEntity | undefined)
case InteractAction.GiveLantern: {
if (client.pony.options!.hold === entities.lanternOn.type) {
unholdItem(pony);
- } else {
+ }
+ else {
holdItem(pony, entities.lanternOn.type);
}
break;
@@ -438,7 +448,8 @@ function boopEntity(client: IClient, rect: Rect, isOnlyBooping: boolean) {
if (entity) {
if (entity.boop) {
entity.boop(client);
- } else if (!isOnlyBooping && entity.type === PONY_TYPE) {
+ }
+ else if (!isOnlyBooping && entity.type === PONY_TYPE) {
const clientHold = client.pony.options!.hold || 0;
if (isHoldingGrapes(entity) && clientHold !== grapeGreen.type && clientHold !== grapePurple.type) {
@@ -449,10 +460,12 @@ function boopEntity(client: IClient, rect: Rect, isOnlyBooping: boolean) {
if (index === (purpleGrapeTypes.length - 1)) {
unholdItem(entity);
- } else {
+ }
+ else {
holdItem(entity, purpleGrapeTypes[index + 1]);
}
- } else {
+ }
+ else {
let index = greenGrapeTypes.indexOf(entity.options!.hold || 0);
if (index !== -1) {
@@ -460,7 +473,8 @@ function boopEntity(client: IClient, rect: Rect, isOnlyBooping: boolean) {
if (index === (greenGrapeTypes.length - 1)) {
unholdItem(entity);
- } else {
+ }
+ else {
holdItem(entity, greenGrapeTypes[index + 1]);
}
}
@@ -525,7 +539,8 @@ function checkSuspiciousSitting(client: IClient) {
client.reporter.warn(`Suspicious sitting`);
client.sitCount = 0;
}
- } else {
+ }
+ else {
client.sitCount = 1;
}
@@ -682,7 +697,8 @@ export function getNextToyOrExtra(client: IClient) {
if (extra) {
return { extra: false, toy: 0 };
- } else {
+ }
+ else {
for (let i = toys.findIndex(t => t.type === toy) + 1; i < toys.length; i++) {
const type = toys[i].type;
@@ -821,7 +837,8 @@ export function execAction(client: IClient, action: Action, settings: GameServer
default:
if (isExpressionAction(action)) {
expressionAction(client, action);
- } else {
+ }
+ else {
throw new Error(`Invalid action (${action})`);
}
break;
@@ -835,7 +852,8 @@ export function switchTool(client: IClient, reverse: boolean) {
if (index === unholdIndex) {
unholdItem(client.pony);
- } else {
+ }
+ else {
const newIndex = reverse ? (index === -1 ? tools.length - 1 : index - 1) : ((index + 1) % tools.length);
const tool = tools[newIndex];
holdItem(client.pony, tool.type);
diff --git a/src/ts/server/polling.ts b/src/ts/server/polling.ts
index 148a234..d581bd8 100644
--- a/src/ts/server/polling.ts
+++ b/src/ts/server/polling.ts
@@ -110,7 +110,8 @@ async function updateServerState(server: InternalGameServerState | InternalLogin
try {
const state = await server.api.state();
Object.assign(server.state, state);
- } catch {
+ }
+ catch {
server.state.dead = true;
}
}
@@ -141,9 +142,11 @@ export async function poll(action: () => any, delayTime: number) {
try {
await delay(delayTime);
await action();
- } catch (e) {
+ }
+ catch (e) {
console.error(e);
- } finally {
+ }
+ finally {
poll(action, delayTime);
}
}
@@ -151,9 +154,11 @@ export async function poll(action: () => any, delayTime: number) {
export async function pollImmediate(action: () => any, delayTime: number) {
try {
await action();
- } catch (e) {
+ }
+ catch (e) {
console.error(e);
- } finally {
+ }
+ finally {
await delay(delayTime);
poll(action, delayTime);
}
diff --git a/src/ts/server/pool.ts b/src/ts/server/pool.ts
index 225bc14..f8053aa 100644
--- a/src/ts/server/pool.ts
+++ b/src/ts/server/pool.ts
@@ -12,7 +12,8 @@ export function createPool(count: number, createNew: () => T, reset: (value:
if (existing) {
reset(existing);
return existing;
- } else {
+ }
+ else {
return createNew();
}
};
@@ -21,7 +22,8 @@ export function createPool(count: number, createNew: () => T, reset: (value:
if (pool.length < count) {
pool.push(value);
return true;
- } else {
+ }
+ else {
return false;
}
};
diff --git a/src/ts/server/regionUtils.ts b/src/ts/server/regionUtils.ts
index 2029837..ea79d7d 100644
--- a/src/ts/server/regionUtils.ts
+++ b/src/ts/server/regionUtils.ts
@@ -26,8 +26,11 @@ function resizeUpdatesBuffer(e: unknown) {
updatesBuffer = new ArrayBuffer(updatesBuffer.byteLength * 2);
updatesBufferOffset = 0;
const errorMsg = isErrorAlike(e) ? e.message : `${e}`;
- DEVELOPMENT && logger.debug(`resize buffer to ${updatesBuffer.byteLength} (${errorMsg})`);
- } else {
+ if (DEVELOPMENT) {
+ logger.debug(`resize buffer to ${updatesBuffer.byteLength} (${errorMsg})`);
+ }
+ }
+ else {
throw e;
}
}
@@ -54,7 +57,8 @@ function encodeUpdate(region: ServerRegion): Uint8Array {
writeUpdate(writer, region);
result = commitUpdatesWriter(writer);
break;
- } catch (e) {
+ }
+ catch (e) {
resizeUpdatesBuffer(e);
}
}
@@ -75,7 +79,8 @@ function encodeRegion(region: ServerRegion, client: IClient): Uint8Array {
writeRegion(writer, region, client);
result = commitUpdatesWriter(writer);
break;
- } catch (e) {
+ }
+ catch (e) {
resizeUpdatesBuffer(e);
}
}
@@ -123,8 +128,11 @@ export function unsubscribeFromOutOfRangeRegions(client: IClient) {
if (!isRectVisible(client.camera, region.unsubscribeBounds)) {
if (includes(region.entities, client.pony)) {
- DEVELOPMENT && logger.warn(`Trying to unsubscribe client from region they are in`);
- } else {
+ if (DEVELOPMENT) {
+ logger.warn(`Trying to unsubscribe client from region they are in`);
+ }
+ }
+ else {
removeItem(region.clients, client);
regions.splice(i, 1);
client.unsubscribes.push(region.x, region.y);
@@ -150,7 +158,8 @@ export function unsubscribeFromAllRegions(client: IClient, silent: boolean) {
export function getExpectedRegion({ x, y, flags, region }: ServerEntity, map: ServerMap) {
if (region !== undefined && (flags & EntityFlags.Movable) !== 0 && pointInRect(x, y, region.boundsWithBorder)) {
return region;
- } else {
+ }
+ else {
const rx = clamp(Math.floor(x / REGION_SIZE), 0, map.regionsX - 1) | 0;
const ry = clamp(Math.floor(y / REGION_SIZE), 0, map.regionsY - 1) | 0;
return map.regions[(rx + ((ry * map.regionsX) | 0)) | 0];
@@ -244,7 +253,8 @@ export function addToRegion(entity: ServerEntity, region: ServerRegion, map: Ser
if (isEntityShadowed(entity)) {
pushAddEntityToClient(entity.client, entity);
- } else {
+ }
+ else {
for (const client of region.clients) {
pushAddEntityToClient(client, entity);
}
diff --git a/src/ts/server/reporter.ts b/src/ts/server/reporter.ts
index 5d5d8aa..6374358 100644
--- a/src/ts/server/reporter.ts
+++ b/src/ts/server/reporter.ts
@@ -31,7 +31,8 @@ const createLogEvent =
}
return Event.updateOne({ _id: event._id }, { desc: event.desc, count: event.count + 1 }).exec();
- } else {
+ }
+ else {
return Event.create({ server, account, pony, type, message, origin, desc }) as any;
}
})
@@ -86,7 +87,9 @@ export function createReporter(server: ServerConfig, account?: ID, pony?: ID, or
},
systemLog(message: string) {
system(accountId, message);
- DEVELOPMENT && logger.log(message);
+ if (DEVELOPMENT) {
+ logger.log(message);
+ }
},
setPony(newPony: any) {
pony = newPony;
diff --git a/src/ts/server/reporting.ts b/src/ts/server/reporting.ts
index 24256bf..c53a875 100644
--- a/src/ts/server/reporting.ts
+++ b/src/ts/server/reporting.ts
@@ -51,7 +51,8 @@ export const createReportSwears =
.then(() => {
if (timeout) {
reporter.system('Timed out for swearing', msg, !!settings.reportSwears);
- } else if (!(isMuted(account) || shadowed)) {
+ }
+ else if (!(isMuted(account) || shadowed)) {
reporter.warn('Swearing', msg);
}
}), reporter.error);
@@ -78,7 +79,8 @@ export const createReportForbidden =
if (newAccount || settings.autoBanSwearing) {
handlePromise(timeoutAccount(accountId, fromNow(duration))
.then(() => reporter.system('Timed out for forbidden messages', msg)), reporter.error);
- } else {
+ }
+ else {
reporter.warn('Forbidden messages', msg);
}
}
diff --git a/src/ts/server/requestUtils.ts b/src/ts/server/requestUtils.ts
index 00b5ab1..59148e3 100644
--- a/src/ts/server/requestUtils.ts
+++ b/src/ts/server/requestUtils.ts
@@ -33,7 +33,8 @@ export const validAccount = (server: ServerConfig): RequestHandler => (req, res,
}
//logger.warn(ACCOUNT_ERROR, `${accountName} [${accountId}] (${req.path})`);
res.status(403).json({ error: ACCOUNT_ERROR });
- } else {
+ }
+ else {
next(null);
}
};
@@ -41,7 +42,8 @@ export const validAccount = (server: ServerConfig): RequestHandler => (req, res,
export const blockMaps = (debug: boolean, local: boolean): RequestHandler => (req, res, next) => {
if (!debug && !local && /\.map$/.test(req.path) && getIP(req) !== ROLLBAR_IP) {
res.sendStatus(404);
- } else {
+ }
+ else {
next(null);
}
};
@@ -51,7 +53,8 @@ export const hash: RequestHandler = (req, res, next) => {
if (apiVersion !== HASH) {
res.status(400).json({ error: VERSION_ERROR });
- } else {
+ }
+ else {
next(null);
}
};
@@ -59,7 +62,8 @@ export const hash: RequestHandler = (req, res, next) => {
export const offline = (settings: Settings): RequestHandler => (_req, res, next) => {
if (settings.isPageOffline) {
res.status(503).send(OFFLINE_ERROR);
- } else {
+ }
+ else {
next(null);
}
};
@@ -67,7 +71,8 @@ export const offline = (settings: Settings): RequestHandler => (_req, res, next)
export const internal = (config: AppConfig, server: ServerConfig): RequestHandler => (req, res, next) => {
if (req.get('api-token') === config.token) {
next(null);
- } else {
+ }
+ else {
createFromRequest(server, req).warn('Unauthorized internal api call', req.originalUrl);
res.sendStatus(403);
}
@@ -76,7 +81,8 @@ export const internal = (config: AppConfig, server: ServerConfig): RequestHandle
export const auth: RequestHandler = (req, res, next) => {
if (req.isAuthenticated()) {
next(null);
- } else {
+ }
+ else {
//createFromRequest(req).warn('Unauthorized access', req.originalUrl);
res.setHeader('X-Robots-Tag', 'noindex');
res.sendStatus(403);
@@ -86,7 +92,8 @@ export const auth: RequestHandler = (req, res, next) => {
export const admin = (server: ServerConfig): RequestHandler => (req, res, next) => {
if (req.isAuthenticated() && req.user && isAdmin(req.user)) {
next(null);
- } else {
+ }
+ else {
if (!/Googlebot/.test(req.get('User-Agent')!)) {
createFromRequest(server, req).warn(`Unauthorized access (admin)`, req.originalUrl);
}
@@ -122,7 +129,8 @@ export function handleError(server: ServerConfig, req: Request, res: Response) {
if (isUserError(e)) {
reportUserError(e, server, req);
res.status(422).json({ error: e.message, userError: true });
- } else {
+ }
+ else {
reportError(e, server, req);
res.status(500).json({ error: 'Error occurred' });
}
@@ -154,7 +162,8 @@ export function wrapApi(server: ServerConfig, api: any) {
return wrap(server, ({ body: { method, args = [] } }) => {
if (api[method]) {
return api[method](...args);
- } else {
+ }
+ else {
return Promise.reject(new Error(`Invalid method (${method})`));
}
});
@@ -179,7 +188,8 @@ function readFiles(files: Map, dir: string, url: string) {
if (stat.isDirectory()) {
readFiles(files, filePath, `${url}/${file}`);
- } else {
+ }
+ else {
const ext = path.extname(file);
const mimeType = mimeTypes[ext];
@@ -211,7 +221,8 @@ export function inMemoryStaticFiles(assetsPath: string, assetsUrl: string, maxAg
res.setHeader('Content-Type', staticFile.mimeType);
res.setHeader('Cache-Control', cacheControl);
res.status(200).end(staticFile.buffer);
- } catch (e) {
+ }
+ catch (e) {
next(e);
}
};
diff --git a/src/ts/server/routes/api-game.ts b/src/ts/server/routes/api-game.ts
index 009b6d0..4660fc4 100644
--- a/src/ts/server/routes/api-game.ts
+++ b/src/ts/server/routes/api-game.ts
@@ -20,12 +20,14 @@ export default function (server: ServerConfig, settings: Settings, config: Confi
app.post('/game/join', offline, limit(60, 5 * 60), hash, validAccount, wrap(server, async req => {
if (inQueue > 100) {
return {};
- } else {
+ }
+ else {
try {
inQueue++;
const { ponyId, serverId, version, url, alert } = req.body;
return await joinGame(req.user as IAccount, ponyId, serverId, version, url, alert, getOrigin(req));
- } finally {
+ }
+ finally {
inQueue--;
}
}
diff --git a/src/ts/server/routes/api-tools.ts b/src/ts/server/routes/api-tools.ts
index efc8f81..e4b1823 100644
--- a/src/ts/server/routes/api-tools.ts
+++ b/src/ts/server/routes/api-tools.ts
@@ -62,7 +62,8 @@ export default function (server: ServerConfig, settings: Settings, world: World
app.get('/maps', offline, (_, res) => {
if (world) {
res.json(world.maps.map(m => m.id));
- } else {
+ }
+ else {
res.sendStatus(400);
}
});
diff --git a/src/ts/server/routes/api1.ts b/src/ts/server/routes/api1.ts
index 562f5b0..03c0c5e 100644
--- a/src/ts/server/routes/api1.ts
+++ b/src/ts/server/routes/api1.ts
@@ -30,10 +30,12 @@ export default function (server: ServerConfig, settings: Settings) {
}
return await getAccountData(account);
- } finally {
+ }
+ finally {
requests--;
}
- } else {
+ }
+ else {
return { limit: true };
}
}
@@ -50,7 +52,8 @@ export default function (server: ServerConfig, settings: Settings) {
if (!account || (settings.blockWebView && isWebView && includes(blockApps, requestedWith))) {
handleJSON(server, req, res, null);
- } else {
+ }
+ else {
handleJSON(server, req, res, handleAccountRequest(account, userAgent, browserId));
}
});
diff --git a/src/ts/server/routes/auth.ts b/src/ts/server/routes/auth.ts
index 322a9fc..d4b5dc9 100644
--- a/src/ts/server/routes/auth.ts
+++ b/src/ts/server/routes/auth.ts
@@ -1,3 +1,4 @@
+/* eslint-disable max-len */
import { Router, Request, Response, RequestHandler } from 'express';
import passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';
@@ -33,7 +34,7 @@ type PassportAuth = passport.Authenticator writeObject(writer, options));
const buffer = Buffer.from(data);
return buffer.toString('base64');
- } else {
+ }
+ else {
return '';
}
}
@@ -137,7 +139,8 @@ export function createIndex(assetsPath: string, adminAssetsPath: string) {
try {
const token = socket.token({ account: req.user } as TokenData);
res.send(renderPage({ production, base, style, script, scriptES, noindex: true, socketOptions, token }));
- } catch (e) {
+ }
+ catch (e) {
logger.error(e);
res.sendStatus(500);
}
diff --git a/src/ts/server/server.ts b/src/ts/server/server.ts
index 806ad8b..57d1266 100644
--- a/src/ts/server/server.ts
+++ b/src/ts/server/server.ts
@@ -11,6 +11,8 @@ import Rollbar from 'rollbar';
import { Passport } from 'passport';
import MongoStore from 'connect-mongo';
import express from 'express';
+import frameguard from 'frameguard';
+import cookieParser from 'cookie-parser';
import { WebSocketServer } from '@encharm/cws';
import { compact, once } from 'lodash';
import { copySync, removeSync, ensureDirSync } from 'fs-extra';
@@ -62,7 +64,8 @@ import { ClientAdminActionsTemplate } from '../common/clientAdminActionsTemplate
function getServiceWorker() {
try {
return fs.readFileSync(pathTo('dist', 'browser', 'sw.js'));
- } catch {
+ }
+ catch {
return '';
}
}
@@ -121,8 +124,9 @@ if (config.proxy) {
}
if (production) {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
app.use(require('hsts')({ maxAge }));
- app.use(require('frameguard')({ action: 'sameorigin' }));
+ app.use(frameguard({ action: 'sameorigin' }));
// app.use(require('shrink-ray-current')());
}
@@ -140,7 +144,8 @@ if (serviceWorker) {
res.setHeader('Cache-Control', 'public, max-age=0');
res.send(serviceWorker);
});
-} else {
+}
+else {
app.get('/sw.js', notFound);
}
@@ -156,7 +161,7 @@ if (args.login || args.admin) {
app.use(bodyParser.json({ type: ['json', 'application/csp-report'], limit }));
app.use(bodyParser.urlencoded({ extended: true, limit }));
-app.use(require('cookie-parser')());
+app.use(cookieParser());
if (args.login || args.admin) {
passport.serializeUser((account, done) => done(null, (account as IAccount)._id.toString()));
@@ -164,7 +169,8 @@ if (args.login || args.admin) {
try {
const account = await Account.findById(id).exec();
done(undefined, account && !isBanned(account) ? account : false);
- } catch (error) {
+ }
+ catch (error) {
done(error);
}
});
@@ -189,6 +195,7 @@ if (!production) {
app.use('/assets-admin', express.static(pathTo('src')));
app.use('/assets', express.static(pathTo('assets')));
app.use('/assets', express.static(pathTo('src')));
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
app.use(require('errorhandler')());
}
@@ -353,7 +360,8 @@ if (args.login) {
app.use((req, res) => {
if (settings.isPageOffline) {
res.send(offlinePage);
- } else {
+ }
+ else {
if (production && !args.local) {
res.setHeader('Content-Security-Policy', csp);
res.setHeader('Link', linkPreloads);
@@ -373,7 +381,8 @@ if (args.login) {
app.use((err: any, req: any, res: express.Response, next: any) => {
if (err instanceof URIError) {
res.redirect(config.host);
- } else {
+ }
+ else {
return next(err, req, res);
}
});
diff --git a/src/ts/server/serverActions.ts b/src/ts/server/serverActions.ts
index 59bf6bf..30143a2 100644
--- a/src/ts/server/serverActions.ts
+++ b/src/ts/server/serverActions.ts
@@ -109,7 +109,8 @@ export class ServerActions implements IServerActions, SocketServer {
if (DEVELOPMENT && /slow/.test(this.client.characterName)) {
setTimeout(() => this.world.joinClientToQueue(this.client), 5000);
- } else {
+ }
+ else {
this.world.joinClientToQueue(this.client);
}
}
@@ -142,8 +143,9 @@ export class ServerActions implements IServerActions, SocketServer {
validateNumber(chatType, 'chatType');
this.updateLastAction();
- if (this.client.isSwitchingMap)
+ if (this.client.isSwitchingMap) {
return;
+ }
const target = entityId ? this.world.getEntityById(entityId) : undefined;
this.chatSay(this.client, text, chatType, target && target.client, this.getSettings());
@@ -153,8 +155,9 @@ export class ServerActions implements IServerActions, SocketServer {
validateNumber(entityId, 'entityId');
this.updateLastAction();
- if (this.client.isSwitchingMap)
+ if (this.client.isSwitchingMap) {
return;
+ }
const entity = entityId === 0 ? undefined : (this.world.getEntityById(entityId) || this.getEntityFromClients(entityId));
const mod = this.client.isMod;
@@ -169,11 +172,13 @@ export class ServerActions implements IServerActions, SocketServer {
const playerState = getPlayerState(this.client, entity);
const flags = UpdateFlags.Options | UpdateFlags.Name | UpdateFlags.Info | UpdateFlags.PlayerState;
pushUpdateEntityToClient(this.client, { entity, flags, options, playerState });
- } else if (hasFlag(flags, SelectFlags.FetchEx) || mod) {
+ }
+ else if (hasFlag(flags, SelectFlags.FetchEx) || mod) {
pushUpdateEntityToClient(this.client, { entity, flags: UpdateFlags.Options, options });
}
}
- } else if (entityId) {
+ }
+ else if (entityId) {
this.client.updateSelection(entityId, 0);
}
}
@@ -182,8 +187,9 @@ export class ServerActions implements IServerActions, SocketServer {
validateNumber(entityId, 'entityId');
this.updateLastAction();
- if (this.client.isSwitchingMap)
+ if (this.client.isSwitchingMap) {
return;
+ }
interactWith(this.client, this.world.getEntityById(entityId));
}
@@ -191,8 +197,9 @@ export class ServerActions implements IServerActions, SocketServer {
use() {
this.updateLastAction();
- if (this.client.isSwitchingMap)
+ if (this.client.isSwitchingMap) {
return;
+ }
useHeldItem(this.client);
}
@@ -208,8 +215,9 @@ export class ServerActions implements IServerActions, SocketServer {
this.hiding.requestUnhideAll(this.client);
break;
default:
- if (this.client.isSwitchingMap)
+ if (this.client.isSwitchingMap) {
return;
+ }
execAction(this.client, action, this.getSettings());
break;
@@ -242,7 +250,8 @@ export class ServerActions implements IServerActions, SocketServer {
if (target) {
this.friends.remove(this.client, target);
- } else {
+ }
+ else {
this.friends.removeByAccountId(this.client, param);
}
@@ -289,7 +298,8 @@ export class ServerActions implements IServerActions, SocketServer {
) {
if (this.isHouseLocked()) {
saySystem(this.client, `House is locked`);
- } else {
+ }
+ else {
this.world.removeEntity(entity, this.map);
}
}
@@ -388,7 +398,8 @@ export class ServerActions implements IServerActions, SocketServer {
if (cancellable) {
setEntityExpression(this.pony, expr, 0, true);
- } else {
+ }
+ else {
this.pony.exprPermanent = expr;
setEntityExpression(this.pony, undefined, 0);
}
@@ -424,7 +435,8 @@ export class ServerActions implements IServerActions, SocketServer {
const hideFor = toInt(param);
if (hideFor === 0) {
this.hiding.requestHide(this.client, target, 0);
- } else {
+ }
+ else {
this.hiding.requestHide(this.client, target, clamp(hideFor, MIN_HIDE_TIME, MAX_HIDE_TIME));
}
break;
@@ -445,8 +457,9 @@ export class ServerActions implements IServerActions, SocketServer {
leaveParty() {
this.updateLastAction();
- if (this.client.isSwitchingMap)
+ if (this.client.isSwitchingMap) {
return;
+ }
if (this.client.party) {
this.partyService.remove(this.client.party.leader, this.client);
@@ -509,7 +522,8 @@ export class ServerActions implements IServerActions, SocketServer {
for (const friend of findAllOnlineFriends(this.world, this.client)) {
if (isHidden) {
friend.updateFriends([{ accountId: this.client.accountId, status: FriendStatusFlags.None }], false);
- } else {
+ }
+ else {
friend.updateFriends([toFriendOnline(this.client)], false);
}
@@ -590,37 +604,46 @@ export class ServerActions implements IServerActions, SocketServer {
validateNumber(type, 'type');
this.updateLastAction();
- if (this.client.isSwitchingMap)
+ if (this.client.isSwitchingMap) {
return;
+ }
const wallTile = type === TileType.WallH || type === TileType.WallV;
if (hasFlag(this.map.flags, MapFlags.EditableWalls) && wallTile) {
if (this.isHouseLocked()) {
saySystem(this.client, `House is locked`);
- } else {
+ }
+ else {
this.world.toggleWall(this.map, x, y, type);
}
- } else if (BETA && this.client.isMod && wallTile) {
+ }
+ else if (BETA && this.client.isMod && wallTile) {
this.world.toggleWall(this.map, x, y, type);
- } else if (hasFlag(this.map.flags, MapFlags.EditableTiles) && this.pony.options!.hold === entities.shovel.type) {
- if (!houseTiles.some(t => t.type === type))
+ }
+ else if (hasFlag(this.map.flags, MapFlags.EditableTiles) && this.pony.options!.hold === entities.shovel.type) {
+ if (!houseTiles.some(t => t.type === type)) {
return;
+ }
- if (this.isHouseLocked())
+ if (this.isHouseLocked()) {
return saySystem(this.client, `House is locked`);
+ }
this.world.setTile(this.map, x, y, type);
- } else if (BETA && this.client.isMod && isValidModTile(type)) {
+ }
+ else if (BETA && this.client.isMod && isValidModTile(type)) {
this.world.setTile(this.map, x, y, type);
- } else if (isValidTile(type)) {
+ }
+ else if (isValidTile(type)) {
if ((BETA || distanceXY(x, y, this.pony.x, this.pony.y) < TILE_CHANGE_RANGE)) {
const tile = getTile(this.map, x, y);
if (tile === TileType.Dirt || tile === TileType.Grass) {
if (this.client.shadowed) {
pushUpdateTileToClient(this.client, x, y, type);
- } else {
+ }
+ else {
this.world.setTile(this.map, x, y, type);
}
}
@@ -646,7 +669,8 @@ export class ServerActions implements IServerActions, SocketServer {
const toAdd = Array.isArray(entity) ? entity : [entity];
toAdd.forEach(e => this.world.addEntity(e, this.map));
added.push({ name, entities: toAdd });
- } else {
+ }
+ else {
saySystem(this.client, 'Invalid entity');
}
break;
@@ -665,7 +689,9 @@ export class ServerActions implements IServerActions, SocketServer {
break;
case 'undo':
const remove = added.pop();
- remove && remove.entities.forEach(e => this.world.removeEntityFromSomeMap(e));
+ if (remove) {
+ remove.entities.forEach(e => this.world.removeEntityFromSomeMap(e));
+ }
break;
case 'clear':
added.forEach(x => x.entities.forEach(e => this.world.removeEntityFromSomeMap(e)));
diff --git a/src/ts/server/serverActionsManager.ts b/src/ts/server/serverActionsManager.ts
index 517135c..d8df317 100644
--- a/src/ts/server/serverActionsManager.ts
+++ b/src/ts/server/serverActionsManager.ts
@@ -70,7 +70,8 @@ export function createServerActionsFactory(
if (hidingData) {
hiding.deserialize(hidingData);
}
- } catch { }
+ }
+ catch { }
pollHidingDataSave(hiding, server.id);
diff --git a/src/ts/server/serverMap.ts b/src/ts/server/serverMap.ts
index 4fea7b8..b111ac1 100644
--- a/src/ts/server/serverMap.ts
+++ b/src/ts/server/serverMap.ts
@@ -217,8 +217,9 @@ export function saveMap(map: ServerMap, saveOptions: MapSaveOptions): MapData {
for (const region of map.regions) {
for (const entity of region.entities) {
if (!hasFlag(entity.serverFlags, ServerFlags.DoNotSave) && !hasFlag(entity.flags, EntityFlags.Debug)) {
- if (saveOptions.saveOnlyEditableEntities && !hasFlag(entity.state, EntityState.Editable))
+ if (saveOptions.saveOnlyEditableEntities && !hasFlag(entity.state, EntityState.Editable)) {
continue;
+ }
const options = entity.options && Object.keys(entity.options).length > 0 ? entity.options : undefined;
const name = entity.name;
@@ -286,8 +287,9 @@ export function loadMap(world: World, map: ServerMap, data: MapData, loadOptions
deserializeMap(map, data, loadOptions);
}
- if (loadOptions.loadOnlyTiles)
+ if (loadOptions.loadOnlyTiles) {
return;
+ }
if (loadOptions.loadEntitiesAsEditable) {
const entitiesToRemove: ServerEntity[] = [];
diff --git a/src/ts/server/serverRegion.ts b/src/ts/server/serverRegion.ts
index b5c9025..f0e327e 100644
--- a/src/ts/server/serverRegion.ts
+++ b/src/ts/server/serverRegion.ts
@@ -129,7 +129,8 @@ export function pushUpdateEntityToRegion(region: ServerRegion, update: EntityUpd
if (index === -1) {
region.entityUpdates.push({ x: 0, y: 0, vx: 0, vy: 0, action: 0, playerState: 0, options: undefined, ...update });
- } else {
+ }
+ else {
region.reusedUpdates++;
const existing = region.entityUpdates[index];
existing.flags |= update.flags;
@@ -163,8 +164,9 @@ export function pushRemoveEntityToRegion(region: ServerRegion, entity: ServerEnt
export function setRegionTile(map: ServerMap, region: ServerRegion, x: number, y: number, type: TileType, skipRestore = false) {
const old = getRegionTile(region, x, y);
- if (type === old)
+ if (type === old) {
return;
+ }
const index = x | (y << 3);
region.tiles[index] = type;
diff --git a/src/ts/server/serverUtils.ts b/src/ts/server/serverUtils.ts
index 2991be1..dedb90d 100644
--- a/src/ts/server/serverUtils.ts
+++ b/src/ts/server/serverUtils.ts
@@ -80,7 +80,8 @@ export function execAsync(command: string, options?: ExecOptions) {
exec(command, options || {}, (error, stdout, stderr) => {
if (error) {
reject(error);
- } else {
+ }
+ else {
resolve({ stdout: stdout.toString(), stderr: stderr.toString() });
}
});
@@ -118,7 +119,7 @@ export function handlePromiseDefault(promise: Promise, errorHandler: any =
Promise.resolve(promise).catch(errorHandler);
}
-export function cached(func: T, cacheTimeout = 1000): T & { clear(...args: any[]): void; } {
+export function cached any>(func: T, cacheTimeout = 1000): T & { clear(...args: any[]): void; } {
const cacheMap = new Map();
const cachedFunc: any = (...args: any[]) => {
@@ -129,7 +130,8 @@ export function cached(func: T, cacheTimeout = 1000
clearTimeout(cache.timeout);
cache.timeout = setTimeout(() => cacheMap.delete(cacheKey), cacheTimeout);
return cache.result;
- } else {
+ }
+ else {
const result = func(...args);
const timeout = setTimeout(() => cacheMap.delete(cacheKey), cacheTimeout);
cacheMap.set(cacheKey, { result, timeout });
diff --git a/src/ts/server/services/actionLimiter.ts b/src/ts/server/services/actionLimiter.ts
index 970432d..388750a 100644
--- a/src/ts/server/services/actionLimiter.ts
+++ b/src/ts/server/services/actionLimiter.ts
@@ -18,20 +18,25 @@ export class ActionLimiter {
this.counters.start();
}
canExecute(requester: IClient, target: IClient): LimiterResult {
- if (requester === target || requester.accountId === target.accountId)
+ if (requester === target || requester.accountId === target.accountId) {
return LimiterResult.SameAccount;
+ }
- if (target.offline)
+ if (target.offline) {
return LimiterResult.TargetOffline;
+ }
- if (isMutedOrShadowed(requester))
+ if (isMutedOrShadowed(requester)) {
return LimiterResult.MutedOrShadowed;
+ }
- if (isIgnored(requester, target) || isIgnored(target, requester))
+ if (isIgnored(requester, target) || isIgnored(target, requester)) {
return LimiterResult.Ignored;
+ }
- if (this.counters.get(requester.accountId).count >= this.countLimit)
+ if (this.counters.get(requester.accountId).count >= this.countLimit) {
return LimiterResult.LimitReached;
+ }
return LimiterResult.Yes;
}
diff --git a/src/ts/server/services/adminService.ts b/src/ts/server/services/adminService.ts
index 90751f3..c2f5fe4 100644
--- a/src/ts/server/services/adminService.ts
+++ b/src/ts/server/services/adminService.ts
@@ -21,7 +21,8 @@ function addAuthToAccount(account: Account, auth: Auth, log: string) {
if (existingAuth) { // TODO: remove
console.log('duplicate auth', auth._id, 'to', account._id, log);
- } else {
+ }
+ else {
account.authsList!.pushOrdered(auth, compareAuths);
}
}
@@ -45,7 +46,8 @@ function addPonyToAccount(account: Account, pony: Character) {
function removePonyFromAccount(account: Account, pony: Character) {
if (account.poniesList) {
return account.poniesList.remove(pony);
- } else {
+ }
+ else {
return false;
}
}
@@ -136,8 +138,12 @@ export class AdminService {
}
if (oldAccount.lastBrowserId !== newAccount.lastBrowserId) {
- oldAccount.lastBrowserId && this.removeBrowserIdFromMap(oldAccount.lastBrowserId, oldAccount);
- newAccount.lastBrowserId && this.addBrowserIdToMap(newAccount.lastBrowserId, oldAccount);
+ if (oldAccount.lastBrowserId) {
+ this.removeBrowserIdFromMap(oldAccount.lastBrowserId, oldAccount);
+ }
+ if (newAccount.lastBrowserId) {
+ this.addBrowserIdToMap(newAccount.lastBrowserId, oldAccount);
+ }
}
Object.assign(oldAccount, newAccount);
@@ -175,7 +181,9 @@ export class AdminService {
}
}
- account.lastBrowserId && this.removeBrowserIdFromMap(account.lastBrowserId, account);
+ if (account.lastBrowserId) {
+ this.removeBrowserIdFromMap(account.lastBrowserId, account);
+ }
this.removeNoteRefsFromMap(account.note, account);
this.accountDeleted.next(account);
},
@@ -266,13 +274,17 @@ export class AdminService {
removedItem(type: 'events' | 'ponies' | 'accounts' | 'auths' | 'origins', id: string) {
if (type === 'accounts') {
this.accounts.removed(id);
- } else if (type === 'origins') {
+ }
+ else if (type === 'origins') {
this.origins.removed(id);
- } else if (type === 'auths') {
+ }
+ else if (type === 'auths') {
this.auths.removed(id);
- } else if (type === 'ponies') {
+ }
+ else if (type === 'ponies') {
this.ponies.removed(id);
- } else {
+ }
+ else {
console.warn(`Unhandled removedItem for type: ${type}`);
}
}
@@ -293,7 +305,8 @@ export class AdminService {
if (remove(account.origins, o => includes(ips, o.ip)).length) {
this.updateOriginRefs(account);
}
- } else if (account.origins.length) {
+ }
+ else if (account.origins.length) {
account.origins = [];
this.updateOriginRefs(account);
}
@@ -304,7 +317,8 @@ export class AdminService {
if (account) {
return account.authsList!.subscribe(listener);
- } else {
+ }
+ else {
return undefined;
}
}
@@ -445,7 +459,8 @@ export class AdminService {
if (account) {
action(account);
- } else {
+ }
+ else {
pushUnique(unassigned, item);
}
}
@@ -471,7 +486,8 @@ export class AdminService {
for (const o of oldOriginRefs) {
if (!o.origin._id && o.origin.accounts!.length === 0) {
this.origins.removed(o.origin.ip);
- } else {
+ }
+ else {
this.origins.trigger(o.origin.ip, o.origin);
}
}
@@ -488,7 +504,8 @@ export class AdminService {
if (account) {
push(account, item);
return true;
- } else {
+ }
+ else {
return false;
}
});
@@ -536,7 +553,8 @@ function removeById(items: T[], id: U): T | undefined {
const item = items[index];
items.splice(index, 1);
return item;
- } else {
+ }
+ else {
return undefined;
}
}
diff --git a/src/ts/server/services/friends.ts b/src/ts/server/services/friends.ts
index 30ce0dd..7cdbd48 100644
--- a/src/ts/server/services/friends.ts
+++ b/src/ts/server/services/friends.ts
@@ -55,7 +55,8 @@ export function toFriendRemove(client: IClient): FriendStatusData {
export function toFriend(client: IClient): FriendStatusData {
if (client.isConnected()) {
return toFriendOnline(client);
- } else {
+ }
+ else {
return toFriendOffline(client);
}
}
@@ -105,32 +106,40 @@ export class FriendsService {
if (can === LimiterResult.LimitReached) {
return saySystem(client, 'Reached request rejection limit');
- } else if (can !== LimiterResult.Yes) {
+ }
+ else if (can !== LimiterResult.Yes) {
return saySystem(client, 'Cannot send request');
}
const pending = this.pending.get(client.accountId) || new Set();
- if (pending.has(target.accountId))
+ if (pending.has(target.accountId)) {
return saySystem(client, 'Already sent request');
+ }
- if (isFriend(client, target))
+ if (isFriend(client, target)) {
return saySystem(client, 'Already on friends list');
+ }
- if (client.friends.size >= FRIENDS_LIMIT)
+ if (client.friends.size >= FRIENDS_LIMIT) {
return saySystem(client, 'Your friend list is full');
+ }
- if (target.friends.size >= FRIENDS_LIMIT)
+ if (target.friends.size >= FRIENDS_LIMIT) {
return saySystem(client, 'Target player friend list is full');
+ }
- if (hasFlag(client.account.flags, AccountFlags.BlockFriendRequests))
+ if (hasFlag(client.account.flags, AccountFlags.BlockFriendRequests)) {
return saySystem(client, 'Cannot send request');
+ }
- if (target.accountSettings.ignoreFriendInvites)
+ if (target.accountSettings.ignoreFriendInvites) {
return saySystem(client, 'Cannot send request');
+ }
- if (pending.size >= PENDING_LIMIT)
+ if (pending.size >= PENDING_LIMIT) {
return saySystem(client, 'Too many pending requests');
+ }
const notificationId = this.addInviteNotification(client, target);
diff --git a/src/ts/server/services/hiding.ts b/src/ts/server/services/hiding.ts
index dc8be3d..36fa77a 100644
--- a/src/ts/server/services/hiding.ts
+++ b/src/ts/server/services/hiding.ts
@@ -41,7 +41,8 @@ export async function saveHidingData(hiding: HidingService, serverId: string) {
try {
const data = hiding.serialize();
await fs.writeFileAsync(hidingDataPath(serverId), data, 'utf8');
- } catch (e) {
+ }
+ catch (e) {
logger.error(e);
}
}
@@ -97,7 +98,8 @@ export class HidingService {
}
this.cleanup();
- } catch (e) {
+ }
+ catch (e) {
logger.error(e);
}
}
@@ -129,13 +131,17 @@ export class HidingService {
if (requester.accountId === target.accountId) {
saySystem(requester, `Cannot hide yourself`);
- } else if (requester.party && includes(requester.party.clients, target)) {
+ }
+ else if (requester.party && includes(requester.party.clients, target)) {
this.notifications.addNotification(requester, simpleNotification(cannotHidePlayerInParty));
- } else if (isFriend(requester, target)) {
+ }
+ else if (isFriend(requester, target)) {
this.notifications.addNotification(requester, simpleNotification(cannotHideFriends));
- } else if (count >= HIDE_LIMIT) {
+ }
+ else if (count >= HIDE_LIMIT) {
this.notifications.addNotification(requester, simpleNotification(hidePlayerLimit));
- } else {
+ }
+ else {
this.notifications.addNotification(requester, {
id: 0,
name: target.pony.name || '',
@@ -151,7 +157,8 @@ export class HidingService {
if (unhideTimestamp > Date.now()) {
this.notifications.addNotification(requester, simpleNotification(unhideAllLimit, unhideAllLimitNote));
- } else {
+ }
+ else {
this.notifications.addNotification(requester, {
id: 0,
name: '',
@@ -195,13 +202,16 @@ export class HidingService {
})
.catch(e => logger.error(e));
return true;
- } else {
+ }
+ else {
- if (by === who)
+ if (by === who) {
return false;
+ }
- if (this.isHiddenInner(by, who))
+ if (this.isHiddenInner(by, who)) {
return false;
+ }
const hides = this.hides.get(by) || new Map();
hides.set(who, Date.now() + timeout);
@@ -234,8 +244,9 @@ export class HidingService {
unhideAll(byClient: IClient) {
const by = byClient.accountId;
- if (this.unhides.has(by))
+ if (this.unhides.has(by)) {
return;
+ }
const hides = this.hides.get(by);
@@ -268,18 +279,23 @@ export class HidingService {
for (const id of Array.from(mergeHides.keys())) {
const who = targetHides.get(id);
targetHides.set(id, Math.max(who || 0, mergeHides.get(id)!));
- targetClient && targetClient.hides.add(id);
+ if (targetClient) {
+ targetClient.hides.add(id);
+ }
if (!who) {
notify.push({ by: target, who: id });
notify.push({ by: merge, who: id });
}
}
- } else {
+ }
+ else {
this.hides.set(target, mergeHides);
for (const id of Array.from(mergeHides.keys())) {
- targetClient && targetClient.hides.add(id);
+ if (targetClient) {
+ targetClient.hides.add(id);
+ }
notify.push({ by: target, who: id });
notify.push({ by: merge, who: id });
}
@@ -309,7 +325,9 @@ export class HidingService {
client.hides.delete(merge);
if (target !== by) {
- client && client.hides.add(target);
+ if (client) {
+ client.hides.add(target);
+ }
}
}
@@ -331,7 +349,9 @@ export class HidingService {
if (hides.get(who)! < now) {
hides.delete(who);
const client = this.findClient(by);
- client && client.hides.delete(who);
+ if (client) {
+ client.hides.delete(who);
+ }
notify.push({ by, who });
}
}
diff --git a/src/ts/server/services/liveList.ts b/src/ts/server/services/liveList.ts
index e14299d..746e69a 100644
--- a/src/ts/server/services/liveList.ts
+++ b/src/ts/server/services/liveList.ts
@@ -65,7 +65,9 @@ export class LiveList {
}
for(id: string | undefined, callback: (item: T) => void) {
const item = id ? this.get(id) : undefined;
- item && callback(item);
+ if (item) {
+ callback(item);
+ }
}
add(item: T) {
const id = this.getId(item);
@@ -91,7 +93,9 @@ export class LiveList {
this.trigger(id, undefined);
this.itemsMap.delete(id);
removeItem(this.items, item);
- this.config.onDelete && this.config.onDelete(item);
+ if (this.config.onDelete) {
+ this.config.onDelete(item);
+ }
}
}
discard(id: string) {
@@ -119,7 +123,8 @@ export class LiveList {
if (item) {
listener(id, this.config.clean(item));
- } else if (this.config.onSubscribeToMissing) {
+ }
+ else if (this.config.onSubscribeToMissing) {
this.add(this.config.onSubscribeToMissing(id));
}
@@ -143,9 +148,11 @@ export class LiveList {
try {
await this.update();
- } catch (e) {
+ }
+ catch (e) {
this.logger.error(e);
- } finally {
+ }
+ finally {
this.timeout = setTimeout(() => this.tick(), tickInterval);
}
}
@@ -178,12 +185,14 @@ export class LiveList {
if (doc !== undefined) {
applyUpdate(doc, update);
this.trigger(this.getId(doc), doc);
- } else if (fetching || !(this.config.ignore && this.config.ignore(update))) {
+ }
+ else if (fetching || !(this.config.ignore && this.config.ignore(update))) {
this.add(update);
}
addedOrUpdated = true;
- } catch (e) {
+ }
+ catch (e) {
console.error(e);
}
});
@@ -194,7 +203,9 @@ export class LiveList {
if (!this.finished) {
this.finished = true;
- this.config.onFinished && this.config.onFinished();
+ if (this.config.onFinished) {
+ this.config.onFinished();
+ }
}
}
}
diff --git a/src/ts/server/services/notification.ts b/src/ts/server/services/notification.ts
index 095f3af..41127a7 100644
--- a/src/ts/server/services/notification.ts
+++ b/src/ts/server/services/notification.ts
@@ -27,7 +27,8 @@ export class NotificationService {
addNotification(client: IClient, notification: ServerNotification) {
if (client.notifications.length >= NOTIFICATION_LIMIT || hasNotification(client, notification)) {
return 0;
- } else {
+ }
+ else {
notification.id = getId(client.notifications);
client.notifications.push(notification);
const { id, entityId = 0, name, message, note = '', flags = 0 } = notification;
@@ -39,7 +40,8 @@ export class NotificationService {
if (removeById(client.notifications, id)) {
client.removeNotification(id);
return true;
- } else {
+ }
+ else {
return false;
}
}
diff --git a/src/ts/server/services/party.ts b/src/ts/server/services/party.ts
index 3465e88..0a78816 100644
--- a/src/ts/server/services/party.ts
+++ b/src/ts/server/services/party.ts
@@ -78,11 +78,13 @@ export class PartyService {
if (newLeader) {
this.promoteLeader(client, newLeader);
- } else {
+ }
+ else {
this.destroyParty(party);
}
}, LEADER_TIMEOUT);
- } else {
+ }
+ else {
const pendingParty = this.parties.find(p => p.pending.some(x => x.client === client));
if (pendingParty) {
@@ -94,8 +96,9 @@ export class PartyService {
remove(leader: IClient, client: IClient) {
const party = leader.party;
- if (!party || party.leader !== leader)
+ if (!party || party.leader !== leader) {
return;
+ }
if (includes(party.clients, client)) {
removeItem(party.clients, client);
@@ -108,7 +111,8 @@ export class PartyService {
client.updateParty(undefined);
this.sendPartyUpdateToAll(party);
this.partyChanged.next(client);
- } else {
+ }
+ else {
const pending = party.pending.find(p => p.client === client);
if (pending) {
@@ -129,33 +133,42 @@ export class PartyService {
if (can === LimiterResult.LimitReached) {
return saySystem(leader, 'Reached invite rejection limit');
- } else if (can !== LimiterResult.Yes) {
+ }
+ else if (can !== LimiterResult.Yes) {
return saySystem(leader, 'Cannot invite');
}
- if (client.shadowed)
+ if (client.shadowed) {
return saySystem(leader, 'Cannot invite');
+ }
- if (hasFlag(leader.account.flags, AccountFlags.BlockPartyInvites))
+ if (hasFlag(leader.account.flags, AccountFlags.BlockPartyInvites)) {
return saySystem(leader, 'Cannot invite');
+ }
- if (party && party.leader !== leader)
+ if (party && party.leader !== leader) {
return saySystem(leader, 'You need to be party leader');
+ }
- if (party && (party.clients.length + party.pending.length) >= PARTY_LIMIT)
+ if (party && (party.clients.length + party.pending.length) >= PARTY_LIMIT) {
return saySystem(leader, 'Party is full');
+ }
- if (client.party)
+ if (client.party) {
return saySystem(leader, 'Already in a party');
+ }
- if (party && party.pending.some(p => p.client === client))
+ if (party && party.pending.some(p => p.client === client)) {
return saySystem(leader, 'Already invited');
+ }
- if (client.accountSettings.ignorePartyInvites && !isFriend(client, leader))
+ if (client.accountSettings.ignorePartyInvites && !isFriend(client, leader)) {
return saySystem(leader, 'Cannot invite');
+ }
- if (this.parties.reduce((sum, p) => sum + p.pending.filter(x => x.client === client).length, 0) >= INVITE_LIMIT)
+ if (this.parties.reduce((sum, p) => sum + p.pending.filter(x => x.client === client).length, 0) >= INVITE_LIMIT) {
return saySystem(leader, 'Too many pending invites');
+ }
const partyExisted = !!leader.party;
@@ -164,8 +177,9 @@ export class PartyService {
}
/* istanbul ignore next */
- if (!party)
+ if (!party) {
throw new Error(`Party not created`);
+ }
const notificationId = this.addInviteNotification(client, leader, party);
@@ -194,20 +208,25 @@ export class PartyService {
promoteLeader(leader: IClient, client: IClient) {
const party = leader.party;
- if (!party)
+ if (!party) {
return;
+ }
- if (leader === client)
+ if (leader === client) {
return;
+ }
- if (client.offline)
+ if (client.offline) {
return saySystem(leader, 'Player is offline');
+ }
- if (party.leader !== leader)
+ if (party.leader !== leader) {
return saySystem(leader, 'You need to be party leader');
+ }
- if (!includes(party.clients, client))
+ if (!includes(party.clients, client)) {
return saySystem(leader, 'Not in the party');
+ }
party.leader = client;
this.sendPartyUpdateToAll(party);
@@ -224,7 +243,8 @@ export class PartyService {
if ((now - party.cleanup) > (10 * SECOND)) {
this.destroyParty(party);
}
- } else if (party.cleanup !== undefined) {
+ }
+ else if (party.cleanup !== undefined) {
party.cleanup = undefined;
}
}
diff --git a/src/ts/server/services/supporterInvites.ts b/src/ts/server/services/supporterInvites.ts
index df27f89..b7cfdc7 100644
--- a/src/ts/server/services/supporterInvites.ts
+++ b/src/ts/server/services/supporterInvites.ts
@@ -44,11 +44,13 @@ export class SupporterInvitesService {
const items = await this.getInvites(requester);
const limit = getSupporterInviteLimit(requester.account);
- if (items.length >= limit)
+ if (items.length >= limit) {
return saySystem(requester, 'Invite limit reached');
+ }
- if (this.limiter.canExecute(requester, target) !== LimiterResult.Yes)
+ if (this.limiter.canExecute(requester, target) !== LimiterResult.Yes) {
return saySystem(requester, 'Cannot invite');
+ }
this.log(formatMessage(requester, target, 'invited to supporter server'));
diff --git a/src/ts/server/settings.ts b/src/ts/server/settings.ts
index 2ab3c1d..537e8c8 100644
--- a/src/ts/server/settings.ts
+++ b/src/ts/server/settings.ts
@@ -17,14 +17,19 @@ export async function loadSettings() {
try {
const json = await readFileAsync(settingsPath, 'utf8');
return JSON.parse(json) as Settings;
- } catch (e) {
+ }
+ catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ENOENT') {
try {
await mkdirAsync(paths.pathTo('settings'));
- } catch (e2) {
- if ((e2 as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
}
- } else {
+ catch (e2) {
+ if ((e2 as NodeJS.ErrnoException).code !== 'EEXIST') {
+ throw e;
+ }
+ }
+ }
+ else {
console.error('Error reading settings file: ' + e);
}
@@ -44,7 +49,8 @@ export async function updateSettings(update: Partial) {
try {
settings = await loadSettings();
- } catch { }
+ }
+ catch { }
Object.assign(settings, update);
await saveSettings(settings);
@@ -55,5 +61,6 @@ export async function reloadSettings() {
try {
const current = await loadSettings();
Object.assign(settings, current);
- } catch { }
+ }
+ catch { }
}
diff --git a/src/ts/server/spamChecker.ts b/src/ts/server/spamChecker.ts
index 35772d2..dbe5139 100644
--- a/src/ts/server/spamChecker.ts
+++ b/src/ts/server/spamChecker.ts
@@ -40,10 +40,12 @@ export const createSpamChecker =
if (settings.reportSpam) {
client.reporter.system('Timed out for spamming', items.join('\n'));
- } else {
+ }
+ else {
client.reporter.systemLog('Timed out for spamming');
}
- } else if (settings.reportSpam && !ignoreReporting(message)) {
+ }
+ else if (settings.reportSpam && !ignoreReporting(message)) {
client.reporter.warn('Spam', message);
}
}
@@ -57,11 +59,13 @@ export const createSpamChecker =
}
return (client, message, settings) => {
- if (client.isMod)
+ if (client.isMod) {
return;
+ }
- if (message === '.')
+ if (message === '.') {
return;
+ }
const lastSays = client.lastSays;
const lastMatch = findLastSayByPartialString(lastSays, message);
@@ -76,10 +80,12 @@ export const createSpamChecker =
lastMatch.count = 0;
handlePromise(countAndTimeoutForSpam(client, message, settings), client.reporter.error);
}
- } else {
+ }
+ else {
if (lastSays.length < MULTIPLE_MATCH_COUNT) {
lastSays.push({ message, count: 1, age: 0 });
- } else {
+ }
+ else {
lastSays.sort(byAge);
const lastSay = lastSays[lastSays.length - 1];
lastSay.message = message;
@@ -129,7 +135,8 @@ function ignoreReporting(message: string) {
function partialString(a: string, b: string): boolean {
if (a === b) {
return true;
- } else {
+ }
+ else {
const length = Math.floor(Math.min(a.length, b.length) * 0.75);
return length > 8 && a.substr(0, length) === b.substr(0, length);
}
@@ -138,11 +145,14 @@ function partialString(a: string, b: string): boolean {
function getLengthMultiplier(message: string) {
if (message.length >= LONG_MESSAGE_LENGTH) {
return LONG_MESSAGE_MUL;
- } else if (message.length <= TINY_MESSAGE_LENGTH) {
+ }
+ else if (message.length <= TINY_MESSAGE_LENGTH) {
return TINY_MESSAGE_MUL;
- } else if (message.length <= SHORT_MESSAGE_LENGTH) {
+ }
+ else if (message.length <= SHORT_MESSAGE_LENGTH) {
return SHORT_MESSAGE_MUL;
- } else {
+ }
+ else {
return 1;
}
}
diff --git a/src/ts/server/start.ts b/src/ts/server/start.ts
index d2a0fb2..c196316 100644
--- a/src/ts/server/start.ts
+++ b/src/ts/server/start.ts
@@ -94,7 +94,8 @@ export function start(world: World, server: ServerConfig) {
frames = 0;
world.sparseUpdate(now);
}
- } catch (e) {
+ }
+ catch (e) {
if (isErrorAlike(e)) {
createReporter(server).danger(e.message);
}
diff --git a/src/ts/server/stats.ts b/src/ts/server/stats.ts
index 7ee87a1..48654f8 100644
--- a/src/ts/server/stats.ts
+++ b/src/ts/server/stats.ts
@@ -47,9 +47,11 @@ function getDate() {
function getAverage({ bytes, mbytes }: ByteSize, count: number): string {
if (!count) {
return '0';
- } else if (mbytes >= 1) {
+ }
+ else if (mbytes >= 1) {
return `${Math.floor((mbytes / count) * MB)} b`;
- } else {
+ }
+ else {
return `${Math.floor(bytes / count)} b`;
}
}
@@ -114,7 +116,8 @@ export class StatsTracker {
if (binary) {
entry.countBin++;
- } else {
+ }
+ else {
entry.countStr++;
}
@@ -160,7 +163,8 @@ export class StatsTracker {
if (entry) {
entry.count++;
entry.size.addBytes(bytes);
- } else {
+ }
+ else {
this.stats.set(path, {
count: 1,
size: new ByteSize(bytes),
@@ -190,8 +194,11 @@ export class StatsTracker {
if (!fs.existsSync(this.statsPath)) {
try {
fs.mkdirSync(path.dirname(this.statsPath), { recursive: true });
- } catch (e) {
- if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
+ }
+ catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') {
+ throw e;
+ }
}
fs.writeFileSync(this.statsPath, encodeCSV(statsHeaders), { encoding: 'utf8' });
}
diff --git a/src/ts/server/timing.ts b/src/ts/server/timing.ts
index 5289c4a..13662dd 100644
--- a/src/ts/server/timing.ts
+++ b/src/ts/server/timing.ts
@@ -38,7 +38,8 @@ export function timingStart(name: string) {
entry.time = counterNow();
entry.name = name;
entriesCount++;
- } else {
+ }
+ else {
console.warn(`exceeded timing entry limit`);
}
}
@@ -52,7 +53,8 @@ export function timingEnd() {
entry.time = counterNow();
entry.name = undefined;
entriesCount++;
- } else {
+ }
+ else {
console.warn(`exceeded timing entry limit`);
}
}
diff --git a/src/ts/server/userError.ts b/src/ts/server/userError.ts
index f8137e1..38f1423 100644
--- a/src/ts/server/userError.ts
+++ b/src/ts/server/userError.ts
@@ -31,7 +31,8 @@ function report(message: string, info: UserErrorInfo, reporter: Reporter | undef
if (keys.length === 1 && keys[0] === 'log') {
logger.log(info.log);
- } else {
+ }
+ else {
if (reporter) {
reporter.warn((info.error && info.error.message) || info.message || message || '', info.desc);
}
diff --git a/src/ts/server/utils/socketErrorHandler.ts b/src/ts/server/utils/socketErrorHandler.ts
index f7c0ae1..8c67c04 100644
--- a/src/ts/server/utils/socketErrorHandler.ts
+++ b/src/ts/server/utils/socketErrorHandler.ts
@@ -35,13 +35,17 @@ let lastErrorTime = 0;
function formatMessage(message: string | Uint8Array | null | undefined) {
if (message === null) {
return '';
- } else if (message === undefined) {
+ }
+ else if (message === undefined) {
return '';
- } else if (typeof message === 'string') {
+ }
+ else if (typeof message === 'string') {
return message;
- } else if (message instanceof Uint8Array) {
+ }
+ else if (message instanceof Uint8Array) {
return `<${Array.from(message).toString()}>`;
- } else {
+ }
+ else {
return `<${JSON.stringify(message)}>`;
}
}
@@ -57,18 +61,23 @@ function reportError(rollbar: Rollbar | undefined, e: Error, client: IClient | u
if (isUserError(e)) {
reportUserError2(e, client);
return e;
- } else {
+ }
+ else {
if (client && client.reporter && !reporterIgnore.test(e.message)) {
client.reporter.error(e);
- } else if (client && client.originalRequest) {
+ }
+ else if (client && client.originalRequest) {
const origin = client.originalRequest && getOriginFromHTTP(client.originalRequest);
createReporter(config, undefined, undefined, origin).error(e);
- } else {
+ }
+ else {
createReporter(config).error(e);
}
if (!rollbarIgnore.test(e.message)) {
- rollbar && rollbar.error(e, null as any, { person: getPerson(client) });
+ if (rollbar) {
+ rollbar.error(e, null as any, { person: getPerson(client) });
+ }
}
return new Error('Error occurred');
@@ -82,10 +91,12 @@ function getMethodNameFromPacket(packet: string | Uint8Array) {
if (typeof packet === 'string') {
const values = JSON.parse(packet);
return serverMethods[values[0]].name;
- } else {
+ }
+ else {
return serverMethods[packet[0]].name;
}
- } catch {
+ }
+ catch {
return '???';
}
}
@@ -100,7 +111,8 @@ function reportRateLimit(client: IClient, e: Error, message: string) {
client.rateLimitCount = 1;
client.disconnect(true, true);
}
- } else {
+ }
+ else {
client.rateLimitMessage = e.message;
client.rateLimitCount = 1;
}
@@ -120,13 +132,15 @@ export class SocketErrorHandler implements ErrorHandler {
if (/^rate limit exceeded/i.test(e.message)) {
reportRateLimit(client, e, 'rejection');
return new Error('Error occurred');
- } else {
+ }
+ else {
return reportError(this.rollbar, e, client, this.config);
}
}
handleRecvError(client: IClient, e: Error, socketMessage: string | Uint8Array) {
- if (lastError === e.message && Date.now() < (lastErrorTime + 5000))
+ if (lastError === e.message && Date.now() < (lastErrorTime + 5000)) {
return;
+ }
const message = formatMessage(socketMessage);
const method = getMethodNameFromPacket(socketMessage);
@@ -135,11 +149,13 @@ export class SocketErrorHandler implements ErrorHandler {
if (client.reporter) {
if (/^rate limit exceeded/i.test(e.message)) {
reported = reportRateLimit(client, e, message);
- } else if (/^transfer limit exceeded/i.test(e.message)) {
+ }
+ else if (/^transfer limit exceeded/i.test(e.message)) {
reported = true;
const desc = e.message.replace(/transfer limit exceeded /i, '');
client.reporter.warn('Transfer limit exceeded', `${desc} - (${method}) ${message}`);
- } else if (!includes(ignoreErrors, e.message)) {
+ }
+ else if (!includes(ignoreErrors, e.message)) {
reported = true;
client.reporter.error(e, `(${method}) ${message}`);
}
@@ -150,7 +166,9 @@ export class SocketErrorHandler implements ErrorHandler {
if (!reported && !rollbarIgnore.test(e.message || '')) {
logger.error(`recv error: ${e.stack || e}\n\n message: ${message}`);
- this.rollbar && this.rollbar.error(e, null as any, { custom: { message }, person: getPerson(client) });
+ if (this.rollbar) {
+ this.rollbar.error(e, null as any, { custom: { message }, person: getPerson(client) });
+ }
}
}
}
diff --git a/src/ts/server/utils/taskQueue.ts b/src/ts/server/utils/taskQueue.ts
index 8bd47b4..55af1ab 100644
--- a/src/ts/server/utils/taskQueue.ts
+++ b/src/ts/server/utils/taskQueue.ts
@@ -20,7 +20,8 @@ export function taskQueue(): TaskQueue {
if (task) {
exec(task);
- } else {
+ }
+ else {
working = false;
}
}
@@ -41,7 +42,8 @@ export function taskQueue(): TaskQueue {
if (working) {
queue.push(task);
- } else {
+ }
+ else {
exec(task);
}
});
diff --git a/src/ts/server/world.ts b/src/ts/server/world.ts
index 4a2e953..00c796b 100644
--- a/src/ts/server/world.ts
+++ b/src/ts/server/world.ts
@@ -101,7 +101,8 @@ export class World {
!this.maps.some(m => m.id === client.map.id && m.instance === client.party!.id)
) {
client.map.instance = client.party.id;
- } else {
+ }
+ else {
refreshMap(this, client);
}
}
@@ -125,8 +126,9 @@ export class World {
this.updateWorldState();
}
setTile(map: ServerMap, x: number, y: number, type: TileType) {
- if (!BETA && map.tilesLocked)
+ if (!BETA && map.tilesLocked) {
return;
+ }
if (x >= 0 && y >= 0 && x < map.width && y < map.height && !isTileLocked(map, x, y) && type !== getTile(map, x, y)) {
setTile(map, x, y, type);
@@ -212,8 +214,11 @@ export class World {
if (map) {
this.removeEntity(entity, map);
- } else {
- DEVELOPMENT && logger.error(`Missing map for entity`);
+ }
+ else {
+ if (DEVELOPMENT) {
+ logger.error(`Missing map for entity`);
+ }
}
}
// map
@@ -222,12 +227,16 @@ export class World {
}
switchToMap(client: IClient, map: ServerMap, x: number, y: number) {
if (client.map === map) {
- DEVELOPMENT && logger.error(`Switching to the same map`);
+ if (DEVELOPMENT) {
+ logger.error(`Switching to the same map`);
+ }
return;
}
if (this.mapSwitchQueue.some(x => x.client === client)) {
- DEVELOPMENT && logger.error(`Already in map switch queue`);
+ if (DEVELOPMENT) {
+ logger.error(`Already in map switch queue`);
+ }
return;
}
@@ -413,12 +422,15 @@ export class World {
const total = updateQueue.offset + regionUpdates.length + saysQueue.length + unsubscribes.length + subscribes.length;
if (total !== 0) {
- if (updateQueue.offset > 0)
+ if (updateQueue.offset > 0) {
clientsWithAdds++;
- if (regionUpdates.length > 0)
+ }
+ if (regionUpdates.length > 0) {
clientsWithUpdates++;
- if (saysQueue.length > 0)
+ }
+ if (saysQueue.length > 0) {
clientsWithSays++;
+ }
totalSays += saysQueue.length;
setupTiming(client);
@@ -613,7 +625,8 @@ export class World {
client.pony.id = reserved.id;
this.reservedIdsByKey.delete(client.accountId);
this.reservedIds.delete(reserved.id);
- } else {
+ }
+ else {
client.pony.id = this.getNewEntityId();
}
@@ -679,7 +692,8 @@ export class World {
if (!c.friends.has(client.accountId)) {
reloadFriends(c).catch(e => logger.error(e));
}
- } else if (c.friends.has(client.accountId)) {
+ }
+ else if (c.friends.has(client.accountId)) {
reloadFriends(c).catch(e => logger.error(e));
}
}
@@ -711,7 +725,8 @@ export class World {
getClientByEntityId(entityId: number) {
if (entityId === 0) {
return undefined;
- } else {
+ }
+ else {
const byPonyId = (c: IClient) => c.pony.id === entityId;
return this.clients.find(byPonyId) || this.offlineClients.find(byPonyId);
}
@@ -783,7 +798,8 @@ export class World {
if (force) {
client.disconnect(true);
- } else {
+ }
+ else {
setTimeout(() => {
if (client.isConnected()) {
client.disconnect(true);
@@ -832,7 +848,8 @@ export class World {
if (oldAccount.shadow !== newAccount.shadow) {
if (isShadowed(newAccount)) {
this.shadow(client);
- } else if (isShadowed(oldAccount)) {
+ }
+ else if (isShadowed(oldAccount)) {
sendAcl(client);
this.kick(client, 'kick (unshadow)');
return;
@@ -894,7 +911,8 @@ export function refreshMap(world: World, client: IClient) {
if (map) {
world.switchToMap(client, map, client.pony.x, client.pony.y);
- } else {
+ }
+ else {
logger.warn(`Missing map: ${client.map.id}`);
}
}
@@ -906,7 +924,8 @@ export function goToMap(world: World, client: IClient, id: string, spawn?: strin
const area = spawn && map.spawns.get(spawn) || map.spawnArea;
const { x, y } = randomPoint(area);
world.switchToMap(client, map, x, y);
- } else {
+ }
+ else {
logger.warn(`Missing map: ${id}`);
}
}
@@ -947,10 +966,12 @@ function findOrCreateMapForClient(world: World, id: string, client: IClient) {
if (map) {
return map;
- } else {
+ }
+ else {
if (client.party) {
return findOrCreateMapInstance(world, id, client.party.id);
- } else {
+ }
+ else {
return findOrCreateMapInstance(world, id, client.accountId);
}
}
@@ -970,7 +991,8 @@ function updateClientCamera(client: IClient) {
client.lastCameraW = camera.w;
client.lastCameraH = camera.h;
return true;
- } else {
+ }
+ else {
return false;
}
}
diff --git a/src/ts/tests/client/clientActions.spec.ts b/src/ts/tests/client/clientActions.spec.ts
index e00a935..8b49a1b 100644
--- a/src/ts/tests/client/clientActions.spec.ts
+++ b/src/ts/tests/client/clientActions.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import { stubClass, resetStubMethods } from '../lib';
import { NgZone } from '@angular/core';
import { Subject } from 'rxjs';
diff --git a/src/ts/tests/client/clientUtils.spec.ts b/src/ts/tests/client/clientUtils.spec.ts
index b858407..c912bb4 100644
--- a/src/ts/tests/client/clientUtils.spec.ts
+++ b/src/ts/tests/client/clientUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import {
diff --git a/src/ts/tests/client/emoji.spec.ts b/src/ts/tests/client/emoji.spec.ts
index f8cf6f3..2760e7a 100644
--- a/src/ts/tests/client/emoji.spec.ts
+++ b/src/ts/tests/client/emoji.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { splitEmojis, findEmoji, replaceEmojis, emojis, hasEmojis, autocompleteMesssage } from '../../common/emoji';
diff --git a/src/ts/tests/client/paletteManager.spec.ts b/src/ts/tests/client/paletteManager.spec.ts
index d634489..20bfa2c 100644
--- a/src/ts/tests/client/paletteManager.spec.ts
+++ b/src/ts/tests/client/paletteManager.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { Palette } from '../../common/interfaces';
diff --git a/src/ts/tests/client/partyUtils.spec.ts b/src/ts/tests/client/partyUtils.spec.ts
index 6b793b2..3ba7686 100644
--- a/src/ts/tests/client/partyUtils.spec.ts
+++ b/src/ts/tests/client/partyUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { PartyInfo, PartyMember } from '../../common/interfaces';
diff --git a/src/ts/tests/client/ponyDraw.spec.ts b/src/ts/tests/client/ponyDraw.spec.ts
index f5a9a1f..f4ec4e2 100644
--- a/src/ts/tests/client/ponyDraw.spec.ts
+++ b/src/ts/tests/client/ponyDraw.spec.ts
@@ -1,4 +1,5 @@
-/* tslint:disable:max-line-length */
+/* eslint-disable max-len */
+
import { compareCanvases, loadSprites, loadImageAsCanvas, clearCompareResults } from '../lib';
import * as path from 'path';
import { TRANSPARENT, blushColor, WHITE } from '../../common/colors';
@@ -147,7 +148,8 @@ function drawPonyCanvas(bg: number, info: PalettePonyInfo, state: PonyState, opt
context.scale(-1, 1);
context.drawImage(canvas, -canvas.width, 0);
return flipped;
- } else {
+ }
+ else {
return canvas;
}
}
diff --git a/src/ts/tests/client/ponyStates.spec.ts b/src/ts/tests/client/ponyStates.spec.ts
index a20ac1d..187bb29 100644
--- a/src/ts/tests/client/ponyStates.spec.ts
+++ b/src/ts/tests/client/ponyStates.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import {
diff --git a/src/ts/tests/client/webglUtils.spec.ts b/src/ts/tests/client/webglUtils.spec.ts
index f4d6bed..6bd5dd6 100644
--- a/src/ts/tests/client/webglUtils.spec.ts
+++ b/src/ts/tests/client/webglUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { stub } from 'sinon';
diff --git a/src/ts/tests/client/worldMap.spec.ts b/src/ts/tests/client/worldMap.spec.ts
index 8b0dccd..acbe047 100644
--- a/src/ts/tests/client/worldMap.spec.ts
+++ b/src/ts/tests/client/worldMap.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { Subject } from 'rxjs';
import { expect } from 'chai';
diff --git a/src/ts/tests/common/accountUtils.spec.ts b/src/ts/tests/common/accountUtils.spec.ts
index 4295751..0bec796 100644
--- a/src/ts/tests/common/accountUtils.spec.ts
+++ b/src/ts/tests/common/accountUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { isAdmin, isMod, isDev, meetsRequirement, getSupporterInviteLimit } from '../../common/accountUtils';
diff --git a/src/ts/tests/common/adminUtils.spec.ts b/src/ts/tests/common/adminUtils.spec.ts
index 1fc039f..51cce9f 100644
--- a/src/ts/tests/common/adminUtils.spec.ts
+++ b/src/ts/tests/common/adminUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { SinonFakeTimers, useFakeTimers } from 'sinon';
diff --git a/src/ts/tests/common/animator.spec.ts b/src/ts/tests/common/animator.spec.ts
index f16edd3..70b948a 100644
--- a/src/ts/tests/common/animator.spec.ts
+++ b/src/ts/tests/common/animator.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import {
diff --git a/src/ts/tests/common/camera.spec.ts b/src/ts/tests/common/camera.spec.ts
index 6135f8b..7f20bea 100644
--- a/src/ts/tests/common/camera.spec.ts
+++ b/src/ts/tests/common/camera.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import {
diff --git a/src/ts/tests/common/colors.spec.ts b/src/ts/tests/common/colors.spec.ts
index 4d6aaa2..52feeff 100644
--- a/src/ts/tests/common/colors.spec.ts
+++ b/src/ts/tests/common/colors.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import {
diff --git a/src/ts/tests/common/compressPony.spec.ts b/src/ts/tests/common/compressPony.spec.ts
index 33ff3f9..8ca6251 100644
--- a/src/ts/tests/common/compressPony.spec.ts
+++ b/src/ts/tests/common/compressPony.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import * as fs from 'fs';
import { expect } from 'chai';
diff --git a/src/ts/tests/common/encoders/updateEncoder.spec.ts b/src/ts/tests/common/encoders/updateEncoder.spec.ts
index f7f1def..a076703 100644
--- a/src/ts/tests/common/encoders/updateEncoder.spec.ts
+++ b/src/ts/tests/common/encoders/updateEncoder.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../../lib';
import { expect } from 'chai';
import { encodeUpdateSimple, encodeRegionSimple } from '../../../common/encoders/updateEncoder';
diff --git a/src/ts/tests/common/expressionUtils.spec.ts b/src/ts/tests/common/expressionUtils.spec.ts
index 8d513d7..4827491 100644
--- a/src/ts/tests/common/expressionUtils.spec.ts
+++ b/src/ts/tests/common/expressionUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { parseExpression, expression } from '../../common/expressionUtils';
@@ -16,7 +17,8 @@ describe('expressionUtils', () => {
it(JSON.stringify(input), () => {
if (expected) {
expect(parseExpression(input)).eql(toExpression(expected));
- } else {
+ }
+ else {
expect(parseExpression(input)).undefined;
}
});
diff --git a/src/ts/tests/common/movementUtils.spec.ts b/src/ts/tests/common/movementUtils.spec.ts
index 5db1590..013dece 100644
--- a/src/ts/tests/common/movementUtils.spec.ts
+++ b/src/ts/tests/common/movementUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { EntityState } from '../../common/interfaces';
@@ -82,7 +83,7 @@ describe('movementUtils', () => {
const [a, b, c, d, e] = encodeMovement(100001, 100001, 1, EntityState.None, 123, rect(100000 * 32, 100000 * 24, 100, 100));
expect(decodeMovement(a, b, c, d, e)).eql({
- x: 100000.015625, y: 100000.020833333333334, dir: 1, flags: EntityState.None, time: 123,
+ x: 100000.015625, y: 100000.02083333333, dir: 1, flags: EntityState.None, time: 123,
camera: rect(100000 * 32, 100000 * 24, 100, 100)
});
});
diff --git a/src/ts/tests/common/ponyHelpers.spec.ts b/src/ts/tests/common/ponyHelpers.spec.ts
index fd6e375..251991a 100644
--- a/src/ts/tests/common/ponyHelpers.spec.ts
+++ b/src/ts/tests/common/ponyHelpers.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { defaultPonyState, isStateEqual } from '../../common/ponyHelpers';
diff --git a/src/ts/tests/common/timeUtils.spec.ts b/src/ts/tests/common/timeUtils.spec.ts
index 58f2559..1a5d351 100644
--- a/src/ts/tests/common/timeUtils.spec.ts
+++ b/src/ts/tests/common/timeUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import {
diff --git a/src/ts/tests/common/utils.spec.ts b/src/ts/tests/common/utils.spec.ts
index 0525a4a..3613dac 100644
--- a/src/ts/tests/common/utils.spec.ts
+++ b/src/ts/tests/common/utils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { spy, assert, SinonFakeTimers, useFakeTimers } from 'sinon';
@@ -374,7 +375,9 @@ describe('utils', () => {
});
it('returns undefined', () => {
- expect(dispose({ dispose() { return 5; } })).undefined;
+ expect(dispose({ dispose() {
+ return 5;
+ } })).undefined;
});
it('does nothing for undefined', () => {
diff --git a/src/ts/tests/generated/sprites.spec.ts b/src/ts/tests/generated/sprites.spec.ts
index f236f62..d88e7a3 100644
--- a/src/ts/tests/generated/sprites.spec.ts
+++ b/src/ts/tests/generated/sprites.spec.ts
@@ -1,9 +1,9 @@
+/* eslint-disable */
import '../lib';
import { expect } from 'chai';
import { map } from 'lodash';
import * as sprites from '../../generated/sprites';
-/* tslint:disable */
const sets: [keyof typeof sprites, number, number, (number[] | null)[]][] = [
// name, index, frames, expected patterns colors counts
// ['topManes', -1, 1, [null, [3, 13, 13, 7, 5, 5], [3, 11, 11, 7, 5, 5], [3, 13, 13, 5, 5, 7], [3, 11, 11, 7, 5, 5], [3, 9, 9, 7, 5], [3, 11, 9, 7, 5, 5], [3, 9, 9, 7, 5, 5], [3, 11, 11, 7, 5, 5], [3, 13, 13, 7, 5], [3, 13, 13, 7, 5, 5, 13], [3, 9, 11, 5, 5], [3, 9, 9, 7, 5, 5], [3, 9, 7, 5, 5], [3, 11, 9, 7, 5], [3, 11, 7, 5, 5], [3, 7], [3, 11, 9, 7, 5, 5], [3, 13, 13, 7, 5, 5], [3, 9, 13, 7, 5, 5], [3, 11, 11, 7, 5, 5], [3, 13, 13, 7, 5, 5], [3, 13, 13, 7, 5, 5, 9], [3, 11, 13, 7, 5, 5], [3, 13, 11, 7, 5, 5], [3, 7, 5, 13, 5]]],
diff --git a/src/ts/tests/lib.ts b/src/ts/tests/lib.ts
index fed4d58..b56a7d9 100644
--- a/src/ts/tests/lib.ts
+++ b/src/ts/tests/lib.ts
@@ -20,6 +20,7 @@ import { loadImage, loadImageSync, createCanvas } from '../server/canvasUtilsNod
import { loadAndInitSheets } from '../client/loadSprites';
import * as chai from 'chai';
+// eslint-disable-next-line @typescript-eslint/no-require-imports
const chaiAsPromised = require('chai-as-promised') as any;
chai.use(chaiAsPromised.default ?? chaiAsPromised);
@@ -54,7 +55,8 @@ export function loadImageAsCanvas(filePath: string): HTMLCanvasElement {
const expected = createCanvas(image.width, image.height);
expected.getContext('2d')!.drawImage(image, 0, 0);
return expected;
- } catch (e) {
+ }
+ catch (e) {
console.error(e);
}
@@ -75,14 +77,18 @@ export function compareCanvases(
filePath: string, group: string, diff = true
) {
try {
- if (expected === actual)
+ if (expected === actual) {
return;
- if (!expected)
+ }
+ if (!expected) {
throw new Error(`Expected canvas is null`);
- if (!actual)
+ }
+ if (!actual) {
throw new Error(`Actual canvas is null`);
- if (expected.width !== actual.width || expected.height !== actual.height)
+ }
+ if (expected.width !== actual.width || expected.height !== actual.height) {
throw new Error(`Canvas size is different than expected`);
+ }
const expectedData = expected.getContext('2d')!.getImageData(0, 0, expected.width, expected.height);
const actualData = actual.getContext('2d')!.getImageData(0, 0, actual.width, actual.height);
@@ -95,7 +101,8 @@ export function compareCanvases(
throw new Error(`Actual canvas different than expected at (${x}, ${y})`);
}
}
- } catch (e) {
+ }
+ catch (e) {
if (actual && diff) {
const tempRoot = pathTo('tools', 'temp', group);
const tempPath = path.join(tempRoot, filePath ? path.basename(filePath) : `${Date.now()}-failed-test.png`);
diff --git a/src/ts/tests/mocks.ts b/src/ts/tests/mocks.ts
index 3365ba2..214cb49 100644
--- a/src/ts/tests/mocks.ts
+++ b/src/ts/tests/mocks.ts
@@ -103,7 +103,9 @@ export function mockClient(fields: any = {}): IClient {
camera: createCamera(),
reportInviteLimit() { },
disconnect() { },
- isConnected() { return true; },
+ isConnected() {
+ return true;
+ },
...fields,
};
diff --git a/src/ts/tests/server/accountUtils.spec.ts b/src/ts/tests/server/accountUtils.spec.ts
index 161f032..11adeaa 100644
--- a/src/ts/tests/server/accountUtils.spec.ts
+++ b/src/ts/tests/server/accountUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { stub, assert, SinonStub } from 'sinon';
diff --git a/src/ts/tests/server/api/account.spec.ts b/src/ts/tests/server/api/account.spec.ts
index a9af116..f822064 100644
--- a/src/ts/tests/server/api/account.spec.ts
+++ b/src/ts/tests/server/api/account.spec.ts
@@ -232,7 +232,8 @@ describe('api account', () => {
await updateAccount(account, { name: 'bar', birthdate: '2000-02-03' });
assert.calledWith(log, account._id, 'Changed birthdate 1970-01-01 (49yo) => 2000-02-03 (19yo)');
- } finally {
+ }
+ finally {
clock.restore();
}
});
diff --git a/src/ts/tests/server/api/internal.spec.ts b/src/ts/tests/server/api/internal.spec.ts
index c1673d9..8e45c18 100644
--- a/src/ts/tests/server/api/internal.spec.ts
+++ b/src/ts/tests/server/api/internal.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import { stubClass, resetStubMethods } from '../../lib';
import { expect } from 'chai';
import { stub, assert, SinonStub, SinonFakeTimers, useFakeTimers, SinonStubbedInstance, createStubInstance } from 'sinon';
diff --git a/src/ts/tests/server/api/pony.spec.ts b/src/ts/tests/server/api/pony.spec.ts
index 7908e38..ec39dea 100644
--- a/src/ts/tests/server/api/pony.spec.ts
+++ b/src/ts/tests/server/api/pony.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../../lib';
import { SinonStub, stub, useFakeTimers, SinonFakeTimers, assert, SinonStubbedInstance } from 'sinon';
import { expect } from 'chai';
@@ -63,7 +64,9 @@ describe('api pony', () => {
name: 'oldname',
_id: characterObjectId,
createdAt: new Date(10),
- save() { return this; }
+ save() {
+ return this;
+ }
} as any;
findCharacter.withArgs(characterId, 'accid').resolves(character);
@@ -213,7 +216,9 @@ describe('api pony', () => {
beforeEach(() => {
character = {
_id: new Types.ObjectId(characterId),
- save() { return this; }
+ save() {
+ return this;
+ }
} as any;
createCharacter.withArgs(acc).returns(character);
diff --git a/src/ts/tests/server/characterUtils.spec.ts b/src/ts/tests/server/characterUtils.spec.ts
index 1672960..17fb7a9 100644
--- a/src/ts/tests/server/characterUtils.spec.ts
+++ b/src/ts/tests/server/characterUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { createExtraOptions, updatePony, encryptInfo, createPony, getAndFixCharacterState } from '../../server/characterUtils';
diff --git a/src/ts/tests/server/chat.spec.ts b/src/ts/tests/server/chat.spec.ts
index c07fe81..81151d6 100644
--- a/src/ts/tests/server/chat.spec.ts
+++ b/src/ts/tests/server/chat.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { stub, assert, SinonStub } from 'sinon';
diff --git a/src/ts/tests/server/cmUtils.spec.ts b/src/ts/tests/server/cmUtils.spec.ts
index c9ca783..81dcee6 100644
--- a/src/ts/tests/server/cmUtils.spec.ts
+++ b/src/ts/tests/server/cmUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import * as fs from 'fs';
import { expect } from 'chai';
diff --git a/src/ts/tests/server/commands.spec.ts b/src/ts/tests/server/commands.spec.ts
index e0587a3..9a30dfb 100644
--- a/src/ts/tests/server/commands.spec.ts
+++ b/src/ts/tests/server/commands.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { assert, stub, SinonStub } from 'sinon';
diff --git a/src/ts/tests/server/entityUtils.spec.ts b/src/ts/tests/server/entityUtils.spec.ts
index 6fa00c9..b66695f 100644
--- a/src/ts/tests/server/entityUtils.spec.ts
+++ b/src/ts/tests/server/entityUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { getWriterBuffer } from 'ag-sockets';
import { expect } from 'chai';
diff --git a/src/ts/tests/server/mapUtils.spec.ts b/src/ts/tests/server/mapUtils.spec.ts
index cb2929d..f6a8508 100644
--- a/src/ts/tests/server/mapUtils.spec.ts
+++ b/src/ts/tests/server/mapUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { createServerMap, findEntities, findClosestEntity } from '../../server/serverMap';
diff --git a/src/ts/tests/server/move.spec.ts b/src/ts/tests/server/move.spec.ts
index c72f2bb..90b1e5a 100644
--- a/src/ts/tests/server/move.spec.ts
+++ b/src/ts/tests/server/move.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { stub, assert, SinonStub } from 'sinon';
diff --git a/src/ts/tests/server/other.spec.ts b/src/ts/tests/server/other.spec.ts
index 007ca5c..4e4f167 100644
--- a/src/ts/tests/server/other.spec.ts
+++ b/src/ts/tests/server/other.spec.ts
@@ -4,6 +4,7 @@ import { CHANGELOG } from '../../generated/changelog';
describe('other', () => {
it('package version is the same as latest changelog version entry', () => {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
const packageJson: any = require('../../../../package.json');
const packageVersion = packageJson.version.replace(/-alpha$/, '');
const changelogVersion = CHANGELOG[0].version.replace(/^v/, '');
diff --git a/src/ts/tests/server/playerUtils.spec.ts b/src/ts/tests/server/playerUtils.spec.ts
index a5c2cfa..fc5d0b9 100644
--- a/src/ts/tests/server/playerUtils.spec.ts
+++ b/src/ts/tests/server/playerUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import { expect } from 'chai';
import { useFakeTimers, SinonFakeTimers, SinonStub, stub, assert } from 'sinon';
import {
diff --git a/src/ts/tests/server/regionUtils.spec.ts b/src/ts/tests/server/regionUtils.spec.ts
index bea7c8d..500732b 100644
--- a/src/ts/tests/server/regionUtils.spec.ts
+++ b/src/ts/tests/server/regionUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { stub, assert } from 'sinon';
diff --git a/src/ts/tests/server/serverActions.spec.ts b/src/ts/tests/server/serverActions.spec.ts
index f52af0f..e5cf88f 100644
--- a/src/ts/tests/server/serverActions.spec.ts
+++ b/src/ts/tests/server/serverActions.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import { stubClass, stubFromInstance, resetStubMethods } from '../lib';
import { expect } from 'chai';
import { stub, assert, spy, SinonSpy, SinonFakeTimers, useFakeTimers, SinonStub } from 'sinon';
@@ -616,7 +617,8 @@ describe('ServerActions', () => {
try {
await serverActions.otherAction(111, ModAction.Report, 0);
- } catch { }
+ }
+ catch { }
assert.calledWith(disconnect, true, true);
});
diff --git a/src/ts/tests/server/serverUtils.spec.ts b/src/ts/tests/server/serverUtils.spec.ts
index f288241..12b8fc9 100644
--- a/src/ts/tests/server/serverUtils.spec.ts
+++ b/src/ts/tests/server/serverUtils.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { stub, assert, SinonStub } from 'sinon';
import { expect } from 'chai';
diff --git a/src/ts/tests/server/services/hiding.spec.ts b/src/ts/tests/server/services/hiding.spec.ts
index 5da9406..69c68bc 100644
--- a/src/ts/tests/server/services/hiding.spec.ts
+++ b/src/ts/tests/server/services/hiding.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import { stubClass, resetStubMethods } from '../../lib';
import { bufferCount, first } from 'rxjs/operators';
import { expect } from 'chai';
diff --git a/src/ts/tests/server/services/notification.spec.ts b/src/ts/tests/server/services/notification.spec.ts
index 227df60..00a0b89 100644
--- a/src/ts/tests/server/services/notification.spec.ts
+++ b/src/ts/tests/server/services/notification.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../../lib';
import { uniqueId } from 'lodash';
import { expect } from 'chai';
diff --git a/src/ts/tests/server/services/party.spec.ts b/src/ts/tests/server/services/party.spec.ts
index 12cd457..e0f98a1 100644
--- a/src/ts/tests/server/services/party.spec.ts
+++ b/src/ts/tests/server/services/party.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../../lib';
import { range } from 'lodash';
import { expect } from 'chai';
diff --git a/src/ts/tests/server/services/supporterInvites.spec.ts b/src/ts/tests/server/services/supporterInvites.spec.ts
index 158506d..923caac 100644
--- a/src/ts/tests/server/services/supporterInvites.spec.ts
+++ b/src/ts/tests/server/services/supporterInvites.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import { stubClass, resetStubMethods } from '../../lib';
import { assert, SinonStub, stub, SinonStubbedInstance, SinonFakeTimers, useFakeTimers, match } from 'sinon';
import { Model } from 'mongoose';
diff --git a/src/ts/tests/server/world.spec.ts b/src/ts/tests/server/world.spec.ts
index dd4d5ad..d03acf0 100644
--- a/src/ts/tests/server/world.spec.ts
+++ b/src/ts/tests/server/world.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import { stubClass, resetStubMethods } from '../lib';
import { Subject } from 'rxjs';
import { expect } from 'chai';
@@ -34,7 +35,9 @@ describe('World', () => {
client = mockClient();
world = new World(
{ flags: {} } as any, partyService as any, friendsService as any, hidingService as any,
- notifications, getSettings, liveSettings, { stats() { return {}; } } as any);
+ notifications, getSettings, liveSettings, { stats() {
+ return {};
+ } } as any);
world.maps.push(map = createServerMap('', 0, 1, 1));
client.map = world.getMainMap();
});
diff --git a/src/ts/tests/services/liveCollection.spec.ts b/src/ts/tests/services/liveCollection.spec.ts
index 09d7ddf..86ad220 100644
--- a/src/ts/tests/services/liveCollection.spec.ts
+++ b/src/ts/tests/services/liveCollection.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { SocketService } from 'ag-sockets';
import { expect } from 'chai';
diff --git a/src/ts/tests/services/liveList.spec.ts b/src/ts/tests/services/liveList.spec.ts
index 5f432d1..7720c13 100644
--- a/src/ts/tests/services/liveList.spec.ts
+++ b/src/ts/tests/services/liveList.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import '../lib';
import { expect } from 'chai';
import { stub, SinonStub, assert, SinonFakeTimers, useFakeTimers } from 'sinon';
@@ -322,7 +323,8 @@ describe('LiveList', () => {
on(event: string, callback: any) {
if (event === 'data') {
items.forEach(callback);
- } else if (event === 'end') {
+ }
+ else if (event === 'end') {
callback();
}
return this;
diff --git a/src/ts/tests/services/model.spec.ts b/src/ts/tests/services/model.spec.ts
index 8cd78d1..7ffce8c 100644
--- a/src/ts/tests/services/model.spec.ts
+++ b/src/ts/tests/services/model.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import { stubClass, resetStubMethods } from '../lib';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
diff --git a/src/ts/tests/services/settingsService.spec.ts b/src/ts/tests/services/settingsService.spec.ts
index 39da976..3398cd0 100644
--- a/src/ts/tests/services/settingsService.spec.ts
+++ b/src/ts/tests/services/settingsService.spec.ts
@@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions */
import { stubClass, resetStubMethods } from '../lib';
import { expect } from 'chai';
import { assert, stub } from 'sinon';
diff --git a/src/ts/tools/canvas-utils.ts b/src/ts/tools/canvas-utils.ts
index 8967b71..7d8d63b 100644
--- a/src/ts/tools/canvas-utils.ts
+++ b/src/ts/tools/canvas-utils.ts
@@ -51,8 +51,9 @@ export function mirrorCanvas(canvas: ExtCanvas, offsetX = 0) {
}
export function padCanvas(canvas: ExtCanvas, left: number, top: number, right = 0, bottom = 0, bg?: string) {
- if (left === 0 && top === 0 && right === 0 && bottom === 0)
+ if (left === 0 && top === 0 && right === 0 && bottom === 0) {
return canvas;
+ }
const result = createExtCanvas(
canvas.width + left + right, canvas.height + top + bottom, `${canvas.info} (pad ${left} ${top} ${right} ${bottom})`);
@@ -83,8 +84,9 @@ export function mergeCanvases(...canvases: (ExtCanvas | undefined)[]): ExtCanvas
export function reverseMaskCanvas(canvas: ExtCanvas): ExtCanvas;
export function reverseMaskCanvas(canvas: ExtCanvas | undefined): ExtCanvas | undefined;
export function reverseMaskCanvas(canvas: ExtCanvas | undefined) {
- if (!canvas)
+ if (!canvas) {
return undefined;
+ }
const result = createExtCanvas(canvas.width, canvas.height, `${canvas.info} reversed mask`);
const context = result.getContext('2d')!;
@@ -98,8 +100,9 @@ export function reverseMaskCanvas(canvas: ExtCanvas | undefined) {
export function maskCanvas(canvas: ExtCanvas, mask: ExtCanvas): ExtCanvas;
export function maskCanvas(canvas: ExtCanvas | undefined, mask: ExtCanvas | undefined): ExtCanvas | undefined;
export function maskCanvas(canvas: ExtCanvas | undefined, mask: ExtCanvas | undefined) {
- if (!canvas || !mask)
+ if (!canvas || !mask) {
return undefined;
+ }
const result = createExtCanvas(canvas.width, canvas.height, `${canvas.info} masked by ${mask.info}`);
const context = result.getContext('2d')!;
@@ -127,8 +130,9 @@ export function colorCanvas(canvas: ExtCanvas | undefined, color: string): ExtCa
export function copyCanvas(canvas: ExtCanvas): ExtCanvas;
export function copyCanvas(canvas: ExtCanvas | undefined): ExtCanvas | undefined;
export function copyCanvas(canvas: ExtCanvas | undefined): ExtCanvas | undefined {
- if (!canvas)
+ if (!canvas) {
return undefined;
+ }
const newCanvas = createExtCanvas(canvas.width, canvas.height, `${canvas.info} (copy)`);
newCanvas.getContext('2d')!.drawImage(canvas, 0, 0);
@@ -172,8 +176,11 @@ export function isCanvasEmpty(canvas: ExtCanvas | undefined): boolean {
export function saveCanvas(filePath: string, canvas: HTMLCanvasElement) {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
- } catch (e) {
- if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
+ }
+ catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') {
+ throw e;
+ }
}
fs.writeFileSync(filePath, canvas.toBuffer());
diff --git a/src/ts/tools/common.ts b/src/ts/tools/common.ts
index a3063df..61b1a26 100644
--- a/src/ts/tools/common.ts
+++ b/src/ts/tools/common.ts
@@ -44,7 +44,8 @@ export function cartesian(...args: any[]) {
export function mkdir(dirpath: string) {
try {
fs.mkdirSync(dirpath);
- } catch { }
+ }
+ catch { }
}
const isDirectory = (dir: string) => fs.lstatSync(dir).isDirectory();
@@ -105,8 +106,9 @@ export function spawnAsync(command: string, args?: string[]) {
// canvas
export function getCanvas(layer: Layer | undefined): ExtCanvas | undefined {
- if (!layer)
+ if (!layer) {
return undefined;
+ }
const canvas = layer.canvas;
@@ -158,7 +160,8 @@ export function addImage(images: HTMLCanvasElement[], canvas: HTMLCanvasElement)
// TODO: remove duplicated
images.push(canvas);
return images.length - 1;
- } else {
+ }
+ else {
return 0;
}
}
diff --git a/src/ts/tools/create-font.ts b/src/ts/tools/create-font.ts
index 641576c..92feb9f 100644
--- a/src/ts/tools/create-font.ts
+++ b/src/ts/tools/create-font.ts
@@ -293,10 +293,12 @@ export function createFont(
if (!width) {
return undefined;
- } else if (added.has(actualCode)) {
+ }
+ else if (added.has(actualCode)) {
// console.log('skipping character', actualCode);
return undefined;
- } else {
+ }
+ else {
const sprite = addImage(cropCanvas(canvas, x * w + left, y * h, width - left, h));
added.add(actualCode);
return { code: actualCode, sprite };
@@ -343,8 +345,9 @@ function compareFontSprite(a: FontSprite, b: FontSprite) {
function isColEmpty(data: ImageData, x: number, y: number, h: number) {
for (let yy = 0; yy < h; yy++) {
- if (data.data[((y + yy) * data.width + x) * 4 + 3])
+ if (data.data[((y + yy) * data.width + x) * 4 + 3]) {
return false;
+ }
}
return true;
@@ -377,8 +380,9 @@ function lengthChecker(expected: number) {
return function (line: string) {
const length = charsToCodes(line).length;
- if (length !== expected)
+ if (length !== expected) {
throw new Error(`Invalid line length (${length}/${expected}) in "${line}"`);
+ }
return line;
};
diff --git a/src/ts/tools/create-sprites.ts b/src/ts/tools/create-sprites.ts
index 8a521be..a848391 100644
--- a/src/ts/tools/create-sprites.ts
+++ b/src/ts/tools/create-sprites.ts
@@ -1,5 +1,4 @@
-/* tslint:disable */
-
+// eslint-disable-next-line @typescript-eslint/no-require-imports
require('source-map-support').install();
(global as any).BETA = false;
@@ -38,6 +37,7 @@ const head0Indices = [0, 1, 2, 4, 7, 8, 9, 10, 12, 13, 14, 16, 18, 19]; // regul
const head1Indices = [0, 1, 3, 5, 6, 8, 9, 11, 12, 13, 15, 17, 18, 19]; // clipped (left facing, displayed in char creator)
const MAX_PALETTE_SIZE = 128;
+// eslint-disable-next-line @typescript-eslint/no-require-imports
const { assetsPath } = require('../../../config.json');
const rootPath = path.join(__dirname, '..', '..', '..');
const sourcePath = path.join(assetsPath);
@@ -179,11 +179,14 @@ function splitMuzzleMouth(canvas: ExtCanvas) {
const mouthCanvas = mapColors(canvas, c => {
if (c === MOUTH_COLOR || c === TONGUE_COLOR) {
return c;
- } else if (c === TEETH_COLOR) {
+ }
+ else if (c === TEETH_COLOR) {
return WHITE;
- } else if (c === TEETH_SHADE_COLOR) {
+ }
+ else if (c === TEETH_SHADE_COLOR) {
return LIGHT_SHADE_COLOR;
- } else {
+ }
+ else {
return 0;
}
});
@@ -226,7 +229,8 @@ function getMuzzlesFromPsd({ sprites, objects2 }: Result, psd: Psd) {
const color = getImage(noseMuzzleCanvas, x, y);
const pattern = getImage(nosePatternCanvas, x, y);
return [{ ...addSpriteWithColors(sprites, color, pattern), mouth, fangs }];
- } else {
+ }
+ else {
return [{ color: addSprite(sprites, getImage(muzzleCanvas, x, y)), colors: 3, mouth, fangs }];
}
}));
@@ -273,7 +277,8 @@ function importSprites({ sprites, objects2 }: Result, sheet: Sheet) {
frameCount = 1;
const oldGet = getImage;
getImage = (canvas, _, type) => oldGet(canvas, type % wrap, Math.floor(type / wrap));
- } else if (sheet.single) {
+ }
+ else if (sheet.single) {
typeCount = typeCount * frameCount;
frameCount = 1;
const oldGet = getImage;
@@ -327,7 +332,8 @@ function importSprites({ sprites, objects2 }: Result, sheet: Sheet) {
if (isCanvasEmpty(accessoryFrame)) {
return null;
- } else {
+ }
+ else {
let extraProps: any = {};
if (extraFrame) {
@@ -413,7 +419,8 @@ function importSprites({ sprites, objects2 }: Result, sheet: Sheet) {
if (sheet.single) {
objects2[`${name}: StaticSprites${hasExtra ? 'Extra' : ''}`] = frames[0] || [];
- } else {
+ }
+ else {
objects2[`${name}: AnimatedSprites`] = frames;
}
});
@@ -474,7 +481,8 @@ function getTreesOrObjectFromPsd(result: Result, psd: Psd, name: string, palette
const color = getLayerCanvas('color', psd);
const shadow = getLayerCanvas('shadow', psd);
addColorShadow(result, name, color, shadow, palettes);
- } else {
+ }
+ else {
getTreesFromPsd(result, psd, name, palettes);
}
}
@@ -730,11 +738,14 @@ function addPalettes(palettes: number[][]) {
function obj(value: any, name: string, indent = false): string {
if (value == null) {
return 'undefined';
- } else if (typeof value === 'string') {
+ }
+ else if (typeof value === 'string') {
return value;
- } else if (typeof value === 'number') {
+ }
+ else if (typeof value === 'number') {
return `sprites[${value.toString()}]`;
- } else if (Array.isArray(value)) {
+ }
+ else if (Array.isArray(value)) {
if (/: StaticSprites(Extra)?$/.test(name)) {
// [type][pattern]
const types = value as (({ color: number; colors: number; extra?: number; palette?: number[]; } | null)[] | null)[];
@@ -770,17 +781,19 @@ function obj(value: any, name: string, indent = false): string {
`createColorPalette(${x!.extra}, [${addPalette(x!.palette!)}])` :
'emptyColorPalette()').join(', ')}],` :
'\tundefined,'
- ).join('\n')}\n];`);
+ ).join('\n')}\n]`);
}
const items = `\n${value.map((x, i) => '\t' + obj(x, `${name}[${i}]`)).join(',\n')}\n`;
- return `[${indent ? items : items.replace(/\t/g, '').replace(/\n/g, ' ').trim()}];` +
- '\n' + lines.join('\n') + '\n';
- } else {
+ return `[${indent ? items : items.replace(/\t/g, '').replace(/\n/g, ' ').trim()}]` +
+ (lines.length ? '\n' + lines.join('\n') : '');
+ }
+ else {
const items = `\n${value.map((x, i) => '\t' + obj(x, `${name}[${i}]`)).join(',\n')}\n`;
return `[${indent ? items : items.replace(/\t/g, '').replace(/\n/g, ' ').trim()}]`;
}
- } else {
+ }
+ else {
return createObj(value, name);
}
}
@@ -790,9 +803,11 @@ function encodeColor(value: number) {
if (alpha === 0) {
return '0';
- } else if (alpha !== 0xff) {
+ }
+ else if (alpha !== 0xff) {
return value.toString(16).padStart(8, '0');
- } else {
+ }
+ else {
return (value >>> 8).toString(16).padStart(6, '0');
}
}
@@ -802,38 +817,54 @@ function createObj(
) {
if (s.frames && s.palette && s.shadow) {
return `createAnimationShadow(${encodeArray(s.frames)}, ${s.shadow}, ${addPalette(s.palette)})`;
- } else if (s.frames && s.palette) {
+ }
+ else if (s.frames && s.palette) {
return `createAnimationPalette(${encodeArray(s.frames)}, ${addPalette(s.palette)})`;
- } else if (s.frames) {
+ }
+ else if (s.frames) {
return `createAnimation(${encodeArray(s.frames)})`;
- } else if (s.fangs != null) {
+ }
+ else if (s.fangs != null) {
return `createNose(${s.color}, ${s.colors}, ${s.mouth}, ${s.fangs})`;
- } else if (s.color && s.colors && s.extra && s.palette) {
+ }
+ else if (s.color && s.colors && s.extra && s.palette) {
return `createColorExtraPal(${s.color}, ${s.colors}, ${s.extra}, [${addPalette(s.palette)}])`;
- } else if (s.color && s.colors) {
+ }
+ else if (s.color && s.colors) {
return `colorPal${s.colors}(${s.color})`;
- } else if (s.base && s.irises != null) {
+ }
+ else if (s.base && s.irises != null) {
return `createEye(${s.base}, ${encodeArray(s.irises)}, ${s.shadow}, ${s.shine})`;
- } else if (s.color && s.shadow && s.palettes) {
+ }
+ else if (s.color && s.shadow && s.palettes) {
return `createColorShadowPalette(${s.color}, ${s.shadow}, ${addPalettes(s.palettes)})`;
- } else if (s.color && s.palettes) {
+ }
+ else if (s.color && s.palettes) {
return `createColorPalette(${s.color}, ${addPalettes(s.palettes)})`;
- } else if (s.sprites && s.palettes) {
+ }
+ else if (s.sprites && s.palettes) {
return `createSpritesPalette(${encodeArray(s.sprites)}, ${addPalettes(s.palettes)})`;
- } else if (s.color && s.palette) {
+ }
+ else if (s.color && s.palette) {
return `/* no palettes */ createColorPalette(${s.color}, [${addPalette(s.palette)}])`;
- } else if (s.color && s.shadow) {
+ }
+ else if (s.color && s.shadow) {
return `createColorShadow(${s.color}, ${s.shadow})`;
- } else if (s.color) {
+ }
+ else if (s.color) {
return `createColor(${s.color})`;
- } else if (s.shadow) {
+ }
+ else if (s.shadow) {
return `createShadow(${s.shadow})`;
- } else if (s.topLeft) {
+ }
+ else if (s.topLeft) {
return `createButton(${s.border}, ${s.topLeft}, ${s.top}, ${s.topRight}, ${s.left}, ${s.bg},`
+ ` ${s.right}, ${s.bottomLeft}, ${s.bottom}, ${s.bottomRight})`;
- } else if (s.name && s.sprite) {
+ }
+ else if (s.name && s.sprite) {
return `createEmote('${s.name}', ${s.sprite})`;
- } else {
+ }
+ else {
throw new Error(`Failed '${name}' createSprite(${JSON.stringify(s)})`);
}
}
@@ -953,7 +984,7 @@ function createSpritesTS(dest: string, config: SpriteTSConfig) {
const { objects, objects2 } = config.result;
let ts = fs.readFileSync(path.join(rootPath, 'src', 'ts', 'tools', 'sprites-template.ts'), 'utf8');
- ts = ts.replace(/export \{.+?\r\n/, '');
+ ts = ts.replace(/export \{[\s\S]*?\};\r?\n?/, '');
ts = ts.replace('/*SPRITE_SHEET*/', `images/${config.spriteFileName}`);
ts = ts.replace('/*SPRITE_SHEET_PALETTE*/', `images/${config.paletteFileName}`);
ts = ts.replace('/*SPRITE_SHEET_PALETTE_ALPHA*/', `images/${config.paletteAlphaFileName}`);
diff --git a/src/ts/tools/name-tester.ts b/src/ts/tools/name-tester.ts
index f58ba03..43fc6b1 100644
--- a/src/ts/tools/name-tester.ts
+++ b/src/ts/tools/name-tester.ts
@@ -32,8 +32,9 @@ charsToCodes(CHARS + ROMAJI + EMOJI).forEach(code => existing.add(code));
items.forEach(({ name }) => {
const codes = charsToCodes(name);
const missingChars = codes.reduce((count, code) => {
- if (existing.has(code) || isNonPrintableCharacter(code))
+ if (existing.has(code) || isNonPrintableCharacter(code)) {
return count;
+ }
const current = missing.get(code) || 0;
missing.set(code, current + 1);
diff --git a/src/ts/tools/palette-utils.ts b/src/ts/tools/palette-utils.ts
index 50acbb2..a3b67fa 100644
--- a/src/ts/tools/palette-utils.ts
+++ b/src/ts/tools/palette-utils.ts
@@ -31,17 +31,23 @@ function getShade(shade: number) {
if (shade > 130 && shade < 140) { // dark outline
return 135;
- } else if (shade > 150 && shade < 165) { // outline
+ }
+ else if (shade > 150 && shade < 165) { // outline
return 159;
- } else if (shade > 165 && shade < 180) { // dark shade
+ }
+ else if (shade > 165 && shade < 180) { // dark shade
return 174;
- } else if (shade > 190 && shade < 210) { // shade
+ }
+ else if (shade > 190 && shade < 210) { // shade
return 204;
- } else if (shade > 210 && shade < 220) { // dark fill
+ }
+ else if (shade > 210 && shade < 220) { // dark fill
return 217;
- } else if (shade > 245) { // fill
+ }
+ else if (shade > 245) { // fill
return 255;
- } else {
+ }
+ else {
return -1;
}
}
@@ -49,9 +55,11 @@ function getShade(shade: number) {
function getShadeForShading(shade: number) {
if (shade === 135) { // dark outline
return 204;
- } else if (shade === 159) { // outline
+ }
+ else if (shade === 159) { // outline
return 255;
- } else {
+ }
+ else {
return shade;
}
}
@@ -95,15 +103,18 @@ export function imageToPalette(
data[i] = index;
data[i + 1] = 255;
- } else {
+ }
+ else {
const alpha = getAlpha(data[i + 3]);
const shade = getShade(data[i]);
const index = findValidPatternColor(pdata[i], pdata[i + 1], pdata[i + 2]);
- if (index === -1)
+ if (index === -1) {
throw new Error(`Invalid color (pattern) [${pixel(pdata, i)}] (${x} ${y}) (${pat.info})`);
- if (alpha == null)
+ }
+ if (alpha == null) {
throw new Error(`Invalid color [${pixel(data, i)}] (${x} ${y}) (${image.info})`);
+ }
const actualIndex = (index * 2) + (isOutline(shade) ? 2 : 1);
const shadeForShading = getShadeForShading(shade);
diff --git a/src/ts/tools/psd-utils.ts b/src/ts/tools/psd-utils.ts
index ce9b72d..5a593fd 100644
--- a/src/ts/tools/psd-utils.ts
+++ b/src/ts/tools/psd-utils.ts
@@ -20,10 +20,12 @@ export function openPsd(filePath: string) {
logMissingFeatures: true,
});
return toPsd(psd, name, dir);
- } catch (e) {
+ }
+ catch (e) {
if (isErrorAlike(e)) {
console.error(`Failed to load: ${filePath}: ${e.message}`);
- } else {
+ }
+ else {
console.error(e);
}
throw e;
@@ -52,8 +54,9 @@ function toLayer({ name, canvas, left, top, children }: PsdLayer, width: number,
function fixCanvas(
canvas: HTMLCanvasElement | undefined, width: number, height: number, left: number, top: number, info: string
) {
- if (!canvas)
+ if (!canvas) {
return undefined;
+ }
const result = createExtCanvas(width, height, info);
result.getContext('2d')!.drawImage(canvas, left, top);
diff --git a/src/ts/tools/sprite-sheet.ts b/src/ts/tools/sprite-sheet.ts
index 7c86f43..53a1a55 100644
--- a/src/ts/tools/sprite-sheet.ts
+++ b/src/ts/tools/sprite-sheet.ts
@@ -20,8 +20,9 @@ function isIdenticalSprite(a: ExtSprite | undefined, b: ExtSprite | undefined):
}
function isIdenticalData(a: ImageData, b: ImageData) {
- if (a.width !== b.width || a.height !== b.height)
+ if (a.width !== b.width || a.height !== b.height) {
return false;
+ }
const length = (a.width * a.height * 4) | 0;
const adat = a.data;
@@ -37,8 +38,9 @@ function isIdenticalData(a: ImageData, b: ImageData) {
}
function isIdenticalChannel(a: Sprite | undefined, b: Sprite | undefined, channel: number) {
- if (!a || !b || a.w !== b.w || a.h !== b.h)
+ if (!a || !b || a.w !== b.w || a.h !== b.h) {
return false;
+ }
const adata = a.image.getContext('2d')!.getImageData(a.ox, a.oy, a.w, a.h);
const bdata = b.image.getContext('2d')!.getImageData(b.ox, b.oy, b.w, b.h);
@@ -88,14 +90,18 @@ function trimImageData(data: ImageData): Rect {
return true;
}
- while (bottom > top && isRowEmpty(bottom - 1))
+ while (bottom > top && isRowEmpty(bottom - 1)) {
bottom--;
- while (right > left && isColEmpty(right - 1))
+ }
+ while (right > left && isColEmpty(right - 1)) {
right--;
- while (top < bottom && isRowEmpty(top))
+ }
+ while (top < bottom && isRowEmpty(top)) {
top++;
- while (left < right && isColEmpty(left))
+ }
+ while (left < right && isColEmpty(left)) {
left++;
+ }
return { y: top, x: left, w: right - left, h: bottom - top };
}
@@ -222,23 +228,28 @@ function positionSprite(sprite: ExtSprite, outputWidth: number, taken: Taken[],
const length = span.length;
const end = start + length;
- if (start >= right) // right of span
+ if (start >= right) { // right of span
break;
+ }
- if (end <= right) // left of span
+ if (end <= right) { // left of span
continue;
+ }
if (start === x) {
if (length === w) { // entire span
spans.splice(i, 1);
- } else { // at the start of span
+ }
+ else { // at the start of span
span.start += w;
span.length -= w;
}
- } else {
+ }
+ else {
if (end === right) { // at the end of span
span.length -= w;
- } else { // in the middle of span
+ }
+ else { // in the middle of span
span.length = x - start;
spans.splice(i + 1, 0, { start: right, length: end - right });
}
@@ -285,8 +296,9 @@ function hasShading(s: Sprite) {
}
function getSpriteImageData(s: ExtSprite): ImageData | undefined {
- if (!s.w || !s.h)
+ if (!s.w || !s.h) {
return undefined;
+ }
const context = s.image.getContext('2d')!;
const { width, height, data } = context.getImageData(s.ox, s.oy, s.w, s.h);
@@ -350,7 +362,8 @@ export function createSpriteSheet(name: string, images: ExtSprite[], log: boolea
}
layered++;
- } else {
+ }
+ else {
pool.push(sprite);
}
@@ -375,7 +388,8 @@ export function createSpriteSheet(name: string, images: ExtSprite[], log: boolea
positionSprite(s, outputWidth, taken, pack);
maxY = Math.max(maxY, s.y + s.h);
areaTaken += s.w * s.h;
- } catch (e) {
+ }
+ catch (e) {
console.error(e);
}
});
@@ -429,7 +443,8 @@ export function createSpriteSheet(name: string, images: ExtSprite[], log: boolea
.forEach(s => {
if (s.layer === 3) {
drawChannel(s.image, alphaData, 0, 0, s.ox, s.oy, s.x, s.y, s.w, s.h);
- } else {
+ }
+ else {
drawChannel(s.image, data, 0, s.layer || 0, s.ox, s.oy, s.x, s.y, s.w, s.h);
}
@@ -440,7 +455,8 @@ export function createSpriteSheet(name: string, images: ExtSprite[], log: boolea
context.putImageData(data, 0, 0);
alphaContext.putImageData(alphaData, 0, 0);
- } else {
+ }
+ else {
sprites
.filter(s => !s.duplicateOf && s.w && s.h)
.forEach(s => context.drawImage(s.image, s.ox, s.oy, s.w, s.h, s.x, s.y, s.w, s.h));
diff --git a/src/ts/tools/sprites-template.ts b/src/ts/tools/sprites-template.ts
index e34e43b..6e44b6f 100644
--- a/src/ts/tools/sprites-template.ts
+++ b/src/ts/tools/sprites-template.ts
@@ -1,5 +1,5 @@
// generated file
-/* tslint:disable */
+/* eslint:disable */
import {
Sprite, SpriteBorder, PonyNose, PonyEye, ColorExtra, ColorExtraSets, Shadow, ColorShadow, TileSprites, SpriteSheet