1
0
mirror of https://github.com/tobspr/shapez.io.git synced 2026-03-02 03:39:21 +00:00

Fix tslint errors

This commit is contained in:
tobspr
2020-05-14 08:56:18 +02:00
parent cf5d776270
commit 85951615a9
17 changed files with 41 additions and 200 deletions

View File

@@ -22,17 +22,10 @@ export class AtlasDefinition {
}
}
// @ts-ignore
export const atlasFiles = require
// @ts-ignore
.context("../../../res_built/atlas/", false, /.*\.json/i)
.keys()
.map(f => f.replace(/^\.\//gi, ""))
.map(f => require("../../../res_built/atlas/" + f))
.map(data => new AtlasDefinition(data));
// export const atlasDefinitions = {
// qualityPreload: atlasFiles.filter((atlas) => atlas.meta.image.indexOf("_preload") >= 0),
// qualityLow: atlasFiles.filter((atlas) => atlas.meta.image.indexOf("_low") >= 0),
// qualityMedium: atlasFiles.filter((atlas) => atlas.meta.image.indexOf("_medium") >= 0),
// qualityHigh: atlasFiles.filter((atlas) => atlas.meta.image.indexOf("_high") >= 0),
// };

View File

@@ -1,13 +1,7 @@
import { GameRoot } from "../game/root";
import {
makeOffscreenBuffer,
freeCanvas,
getBufferVramUsageBytes,
getBufferStats,
clearBufferBacklog,
} from "./buffer_utils";
import { clearBufferBacklog, freeCanvas, getBufferStats, makeOffscreenBuffer } from "./buffer_utils";
import { createLogger } from "./logging";
import { round2Digits, round1Digit } from "./utils";
import { round1Digit } from "./utils";
/**
* @typedef {{

View File

@@ -1,11 +1,21 @@
import { createLogger } from "./logging";
const logger = createLogger("singleton_factory");
// simple factory pattern
export class SingletonFactory {
constructor() {
constructor(id) {
this.id = id;
// Store array as well as dictionary, to speed up lookups
this.entries = [];
this.idToEntry = {};
}
getId() {
return this.id;
}
register(classHandle) {
// First, construct instance
const instance = new classHandle();
@@ -39,6 +49,7 @@ export class SingletonFactory {
findById(id) {
const entry = this.idToEntry[id];
if (!entry) {
logger.error("Object with id", id, "is not registered!");
assert(false, "Factory: Object with id '" + id + "' is not registered!");
return null;
}
@@ -68,6 +79,14 @@ export class SingletonFactory {
return this.entries;
}
/**
* Returns all registered ids
* @returns {Array<string>}
*/
getAllIds() {
return Object.keys(this.idToEntry);
}
/**
* Returns amount of stored entries
* @returns {number}

View File

@@ -436,26 +436,6 @@ export function formatBigNumber(num, divider = ".") {
return sign + "" + num;
}
// if (num > 1e51) return sign + T.common.number_format.sedecillion.replace("%amount%", "" + roundSmart(num / 1e51));
// if (num > 1e48)
// return sign + T.common.number_format.quinquadecillion.replace("%amount%", "" + roundSmart(num / 1e48));
// if (num > 1e45)
// return sign + T.common.number_format.quattuordecillion.replace("%amount%", "" + roundSmart(num / 1e45));
// if (num > 1e42) return sign + T.common.number_format.tredecillion.replace("%amount%", "" + roundSmart(num / 1e42));
// if (num > 1e39) return sign + T.common.number_format.duodecillions.replace("%amount%", "" + roundSmart(num / 1e39));
// if (num > 1e36) return sign + T.common.number_format.undecillions.replace("%amount%", "" + roundSmart(num / 1e36));
// if (num > 1e33) return sign + T.common.number_format.decillions.replace("%amount%", "" + roundSmart(num / 1e33));
// if (num > 1e30) return sign + T.common.number_format.nonillions.replace("%amount%", "" + roundSmart(num / 1e30));
// if (num > 1e27) return sign + T.common.number_format.octillions.replace("%amount%", "" + roundSmart(num / 1e27));
// if (num >= 1e24) return sign + T.common.number_format.septillions.replace("%amount%", "" + roundSmart(num / 1e24));
// if (num >= 1e21) return sign + T.common.number_format.sextillions.replace("%amount%", "" + roundSmart(num / 1e21));
// if (num >= 1e18) return sign + T.common.number_format.quintillions.replace("%amount%", "" + roundSmart(num / 1e18));
// if (num >= 1e15) return sign + T.common.number_format.quantillions.replace("%amount%", "" + roundSmart(num / 1e15));
// if (num >= 1e12) return sign + T.common.number_format.trillions.replace("%amount%", "" + roundSmart(num / 1e12));
// if (num >= 1e9) return sign + T.common.number_format.billions.replace("%amount%", "" + roundSmart(num / 1e9));
// if (num >= 1e6) return sign + T.common.number_format.millions.replace("%amount%", "" + roundSmart(num / 1e6));
// if (num > 99999) return sign + T.common.number_format.thousands.replace("%amount%", "" + roundSmart(num / 1e3));
let rest = num;
let out = "";
@@ -474,7 +454,7 @@ export function formatBigNumber(num, divider = ".") {
* @param {string=} divider THe divider for numbers like 50,000 (divider=',')
* @returns {string}
*/
export function formatBigNumberFull(num, divider = T.common.number_format.divider_thousands || " ") {
export function formatBigNumberFull(num, divider = ",") {
if (num < 1000) {
return num + "";
}
@@ -492,65 +472,6 @@ export function formatBigNumberFull(num, divider = T.common.number_format.divide
return out.substring(0, out.length - 1);
}
/**
* Formats an amount of seconds into something like "5s ago"
* @param {number} secs Seconds
* @returns {string}
*/
export function formatSecondsToTimeAgo(secs) {
const seconds = Math_floor(secs);
const minutes = Math_floor(seconds / 60);
const hours = Math_floor(minutes / 60);
const days = Math_floor(hours / 24);
const trans = T.common.time;
if (seconds <= 60) {
if (seconds <= 1) {
return trans.one_second_before;
}
return trans.seconds_before.replace("%amount%", "" + seconds);
} else if (minutes <= 60) {
if (minutes <= 1) {
return trans.one_minute_before;
}
return trans.minutes_before.replace("%amount%", "" + minutes);
} else if (hours <= 60) {
if (hours <= 1) {
return trans.one_hour_before;
}
return trans.hours_before.replace("%amount%", "" + hours);
} else {
if (days <= 1) {
return trans.one_day_before;
}
return trans.days_before.replace("%amount%", "" + days);
}
}
/**
* Formats seconds into a readable string like "5h 23m"
* @param {number} secs Seconds
* @returns {string}
*/
export function formatSeconds(secs) {
const trans = T.common.time;
secs = Math_ceil(secs);
if (secs < 60) {
return trans.seconds_short.replace("%seconds%", "" + secs);
} else if (secs < 60 * 60) {
const minutes = Math_floor(secs / 60);
const seconds = secs % 60;
return trans.minutes_seconds_short
.replace("%seconds%", "" + seconds)
.replace("%minutes%", "" + minutes);
} else {
const hours = Math_floor(secs / 3600);
const minutes = Math_floor(secs / 60) % 60;
return trans.hours_minutes_short.replace("%minutes%", "" + minutes).replace("%hours%", "" + hours);
}
}
/**
* Delayes a promise so that it will resolve after a *minimum* amount of time only
* @param {Promise<any>} promise The promise to delay

View File

@@ -143,11 +143,7 @@ export class ShapeDefinitionManager extends BasicSerializableObject {
*/
getDefinitionFromSimpleShapes(subShapes, color = enumColors.uncolored) {
const shapeLayer = /** @type {import("./shape_definition").ShapeLayer} */ (subShapes.map(
subShape => ({
subShape,
rotation: 0,
color,
})
subShape => ({ subShape, color })
));
return this.registerOrReturnHandle(new ShapeDefinition({ layers: [shapeLayer] }));

4
src/js/globals.d.ts vendored
View File

@@ -148,7 +148,7 @@ declare interface Math {
}
declare interface String {
padStart(size: number, fill: string): string;
padStart(size: number, fill?: string): string;
padEnd(size: number, fill: string): string;
}
@@ -170,6 +170,8 @@ declare interface SingletonFactoryTemplate<T> {
entries: Array<T>;
idToEntry: any;
getId(): string;
getAllIds(): Array<string>;
register(classHandle: new (...args: any[]) => T): void;
hasId(id: string): boolean;
findById(id: string): T;

7
src/js/jsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"compilerOptions": {
"target": "es6",
"checkJs": true,
}
}

View File

@@ -30,7 +30,7 @@ export class BaseSetting {
/**
* @param {Application} app
* @param {Element} element
* @param {HUDModalDialogs} dialogs
* @param {any} dialogs
*/
bind(app, element, dialogs) {
this.app = app;

View File

@@ -141,24 +141,6 @@ export class SavegameSerializer {
// entities
errorReason = errorReason || root.entityMgr.deserialize(savegame.entityMgr);
// resources
errorReason =
errorReason ||
this.internal.deserializeEntityArrayFixedType(
root,
savegame.entities.resources,
this.internal.deserializeResource
);
// buildings
errorReason =
errorReason ||
this.internal.deserializeEntityArray(
root,
savegame.entities.buildings,
this.internal.deserializeBuilding
);
// other stuff
errorReason = errorReason || root.time.deserialize(savegame.time);
errorReason = errorReason || root.camera.deserialize(savegame.camera);

View File

@@ -270,8 +270,7 @@ export function deserializeSchema(obj, schema, data, baseclassErrorResult = null
const errorStatus = schema[key].deserializeWithVerify(data[key], obj, key, obj.root);
if (errorStatus) {
error(
"serialization",
logger.error(
"Deserialization failed with error '" + errorStatus + "' on object",
obj,
"and key",
@@ -294,17 +293,17 @@ export function deserializeSchema(obj, schema, data, baseclassErrorResult = null
export function verifySchema(schema, data) {
for (const key in schema) {
if (!data.hasOwnProperty(key)) {
error("verify", "Data", data, "does not contain", key, "(schema:", schema, ")");
logger.error("Data", data, "does not contain", key, "(schema:", schema, ")");
return "verify: missing key required by schema in stored data: " + key;
}
if (!schema[key].allowNull() && (data[key] === null || data[key] === undefined)) {
error("verify", "Data", data, "has null value for", key, "(schema:", schema, ")");
logger.error("Data", data, "has null value for", key, "(schema:", schema, ")");
return "verify: non-nullable entry is null: " + key;
}
const errorStatus = schema[key].verifySerializedValue(data[key]);
if (errorStatus) {
error("verify", errorStatus);
logger.error(errorStatus);
return "verify: " + errorStatus;
}
}

View File

@@ -6,6 +6,7 @@ import { Vector } from "../core/vector";
import { createLogger } from "../core/logging";
import { gMetaBuildingRegistry } from "../core/global_registries";
import { Entity } from "../game/entity";
import { MapResourcesSystem } from "../game/systems/map_resources";
const logger = createLogger("serializer_internal");
@@ -80,61 +81,6 @@ export class SerializerInternal {
return null;
}
/**
* Deserializes a building
* @param {GameRoot} root
* @param {{ $: string, data: any }} payload
*/
deserializeBuilding(root, payload) {
const data = payload.data;
const id = payload.$;
if (!gMetaBuildingRegistry.hasId(id)) {
return "Metaclass not found for building: '" + id + "'";
}
const meta = gMetaBuildingRegistry.findById(id);
if (!meta) {
return "Metaclass not found for building: '" + id + "'";
}
const tile = new Vector(data.x, data.y).toTileSpace();
const instance = root.logic.internalPlaceBuildingLocalClientOnly({
tile: tile,
metaBuilding: meta,
uid: data.uid,
});
// Apply component specific properties
const errorStatus = this.deserializeComponents(instance, data.components);
if (errorStatus) {
return errorStatus;
}
// Apply enhancements
instance.updateEnhancements();
}
/**
* Deserializes a blueprint
* @param {GameRoot} root
* @param {any} data
* @returns {string|void}
*/
deserializeBlueprint(root, data) {
const id = data.meta;
const metaClass = gMetaBuildingRegistry.findById(id);
if (!metaClass) {
return "Metaclass not found for blueprint: '" + id + "'";
}
const tile = new Vector(data.x, data.y).toTileSpace();
const instance = root.logic.internalPlaceBlueprintLocalClientOnly({
tile: tile,
metaBuilding: metaClass,
uid: data.uid,
});
return this.deserializeComponents(instance, data.components);
}
/////// COMPONENTS ////
/**
@@ -161,20 +107,4 @@ export class SerializerInternal {
}
}
}
/**
* Deserializes a resource
* @param {GameRoot} root
* @param {object} data
* @returns {string|void}
*/
deserializeResource(root, data) {
const id = data.key;
const instance = new MapResource(root, this.neutralFaction, id);
root.logic.internalPlaceMapEntityLocalClientOnly(
new Vector(data.x, data.y).toTileSpace(),
instance,
data.uid
);
}
}

View File

@@ -198,10 +198,10 @@ export class InGameState extends GameState {
this.core.initializeRoot(this, this.savegame);
if (this.savegame.hasGameDump()) {
this.app.gameAnalytics.handleGameStarted(this.savegame);
this.app.gameAnalytics.handleGameStarted();
this.stage4bResumeGame();
} else {
this.app.gameAnalytics.handleGameStarted(this.savegame);
this.app.gameAnalytics.handleGameStarted();
this.stage4aInitEmptyGame();
}
}

62
src/js/tsconfig.json Normal file
View File

@@ -0,0 +1,62 @@
{
"compilerOptions": {
/* Basic Options */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
"allowJs": true, /* Allow javascript files to be compiled. */
"checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./typedefs_gen", /* Concatenate and emit output to single file. */
// "outDir": "./typedefs_gen", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "incremental": true, /* Enable incremental compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
"noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
// "strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
"strictFunctionTypes": true, /* Enable strict checking of function types. */
"strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
"noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
"resolveJsonModule": true
},
"exclude": [
"backend/shared/gameserver_base_impl",
"backend/shared/sentry_logger.js"
]
}

23
src/js/tslint.json Normal file
View File

@@ -0,0 +1,23 @@
{
"defaultSeverity": "error",
"extends": [
"tslint:recommended"
],
"jsRules": {
"trailing-comma": false,
"comma-dangle": [
"error",
"never"
],
"object-literal-sort-keys": false,
"member-ordering": false,
"max-line-length": false,
"no-console": false,
"forin": false,
"no-empty": false,
"space-before-function-paren": [
"always"
]
},
"rulesDirectory": []
}