From cf31a33dbe03d0326ea7b082e8a7cb5621c8c941 Mon Sep 17 00:00:00 2001 From: Owen Date: Fri, 20 Oct 2023 20:47:30 +0100 Subject: [PATCH] stuff ig? --- .eslintrc.json | 3 ++- .npmignore | 1 + package.json | 8 +++----- src/Map.ts | 22 ++++++++++------------ src/api/GPS.ts | 11 +++++++---- src/api/Nations.ts | 16 +++++++--------- src/api/Players.ts | 3 ++- src/types/gps.ts | 6 +++--- src/types/oapi_v2.ts | 18 +++++++++--------- src/types/util.ts | 6 +++++- src/utils/endpoint.ts | 1 + src/utils/functions.ts | 23 ++++++++++++++++++----- tests/nations.test.ts | 2 +- tests/towns.test.ts | 4 +++- tsconfig.json | 3 ++- 15 files changed, 74 insertions(+), 53 deletions(-) create mode 100644 .npmignore diff --git a/.eslintrc.json b/.eslintrc.json index 3a5b6f6..1603b00 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -30,7 +30,8 @@ "markers": [ "#region", "#endregion", - "@ts-expect-error" + "@ts-expect-error", + "@ts-ignore" ] }], "comma-spacing": 2, diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..a447a46 --- /dev/null +++ b/.npmignore @@ -0,0 +1 @@ +**/*.tsbuildinfo \ No newline at end of file diff --git a/package.json b/package.json index ff31ff7..533c6a1 100644 --- a/package.json +++ b/package.json @@ -10,11 +10,11 @@ "default": "./dist/main.cjs" }, "scripts": { - "prepublishOnly": "npm run ci", + "prepublishOnly": "npm run ci && npm run docs", "ci": "pnpm run lint && pnpm run test && pnpm run build", "lint": "npx eslint .", "clean": "rimraf dist", - "build": "npm run clean && rollup -c && tsc --declaration true --emitDeclarationOnly true --declarationMap && npm run docs", + "build": "npm run clean && rollup -c && tsc --declaration true --emitDeclarationOnly true --declarationMap", "docs": "npx typedoc --options typedoc.json", "test": "vitest run --config ./vitest.config.ts", "test-browser": "vitest run --browser.name=chrome --browser.headless --config ./vitest.config.ts" @@ -22,10 +22,8 @@ "files": [ "dist", "src", - "LICENSE", "README.md", - "package.json", - "endpoints.json" + "package.json" ], "keywords": [ "earth", diff --git a/src/Map.ts b/src/Map.ts index 61e93c3..afc3700 100644 --- a/src/Map.ts +++ b/src/Map.ts @@ -1,10 +1,10 @@ import DataHandler from './helpers/DataHandler.js' -import Towns from './classes/Towns.js' -import Nations from './classes/Nations.js' -import Players from './classes/Players.js' -import Residents from './classes/Residents.js' -import GPS from './classes/GPS.js' +import Towns from './api/Towns.js' +import Nations from './api/Nations.js' +import Players from './api/Players.js' +import Residents from './api/Residents.js' +import GPS from './api/GPS.js' import * as fn from './utils/functions.js' import { Point2D, TownBounds, ValidMapName } from './types.js' @@ -59,9 +59,7 @@ class Map extends DataHandler { return inBounds } - readonly isWilderness = async (location: Point2D) => { - return !(await this.withinTown(location)) - } + readonly isWilderness = async (location: Point2D) => !(await this.withinTown(location)) readonly withinBounds = (location: Point2D, bounds: TownBounds) => { if (fn.strictFalsy(location.x) || fn.strictFalsy(location.z)) { @@ -69,12 +67,12 @@ class Map extends DataHandler { throw new ReferenceError(`(withinBounds) - Invalid location:\n${obj}`) } - const xLoc = parseInt(String(location.x)) - const zLoc = parseInt(String(location.z)) + const locX = fn.safeParseInt(location.x) + const locZ = fn.safeParseInt(location.z) // Check if the given coordinates are within the bounds or on the bounds - const withinX = xLoc >= Math.min(...bounds.x) && xLoc <= Math.max(...bounds.x) - const withinZ = zLoc >= Math.min(...bounds.z) && zLoc <= Math.max(...bounds.z) + const withinX = locX >= Math.min(...bounds.x) && locX <= Math.max(...bounds.x) + const withinZ = locZ >= Math.min(...bounds.z) && locZ <= Math.max(...bounds.z) return withinX && withinZ } diff --git a/src/api/GPS.ts b/src/api/GPS.ts index 2fe38ff..9449ceb 100644 --- a/src/api/GPS.ts +++ b/src/api/GPS.ts @@ -70,7 +70,10 @@ class GPS extends Mitt { } } else { - this.lastLoc = { x: player.x, z: player.z } + this.lastLoc = { + x: fn.safeParseInt(player.x), + z: fn.safeParseInt(player.z) + } try { const routeInfo = await this.findRoute({ @@ -126,7 +129,7 @@ class GPS extends Mitt { // Use reduce to find the minimum distance and corresponding nation const { distance, nation } = filtered.reduce((acc: any, nation: Nation) => { const capital = nation.capital - const dist = fn.manhattan(capital.x, capital.z, loc.x, loc.z) + const dist = fn.manhattan(capital.x, capital.z, fn.safeParseInt(loc.x), fn.safeParseInt(loc.z)) // Update acc if this nation is closer const closer = !acc.distance || dist < acc.distance @@ -145,8 +148,8 @@ class GPS extends Mitt { static cardinalDirection(loc1: Location, loc2: Location) { // Calculate the differences in x and z coordinates - const deltaX = loc2.x - loc1.x - const deltaZ = loc2.z - loc1.z + const deltaX = fn.safeParseInt(loc2.x) - fn.safeParseInt(loc1.x) + const deltaZ = fn.safeParseInt(loc2.z) - fn.safeParseInt(loc1.z) const angleRad = Math.atan2(deltaZ, deltaX) // Calculate the angle in radians const angleDeg = (angleRad * 180) / Math.PI // Convert the angle from radians to degrees diff --git a/src/api/Nations.ts b/src/api/Nations.ts index 588efe7..f130a95 100644 --- a/src/api/Nations.ts +++ b/src/api/Nations.ts @@ -40,12 +40,10 @@ class Nations implements Base { len = towns.length for (let i = 0; i < len; i++) { - const town = towns[i], - nationName = town.nation - - if (nationName == "No Nation") { - continue - } + const town = towns[i] + + const nationName = town.nation + if (nationName == "No Nation") continue // Doesn't already exist, create new. if (!raw[nationName]) { @@ -101,11 +99,11 @@ class Nations implements Base { } readonly joinable = async (townName: string, nationless = true): Promise => { - let town = null + let town: Town = null try { - town = await this.map.Towns.get(townName) + town = await this.map.Towns.get(townName) as Town } catch (_) { - return new FetchError(`Specified town '${townName}' does not exist!`) + throw new FetchError(`Specified town '${townName}' does not exist!`) } const nations = await this.all(this.map.getFromCache('towns')) diff --git a/src/api/Players.ts b/src/api/Players.ts index a44b510..bdbc8b9 100644 --- a/src/api/Players.ts +++ b/src/api/Players.ts @@ -100,7 +100,8 @@ class Players implements Base { return players.filter(p => { if (p.x == 0 && p.z == 0) return - return fn.hypot(p.x, [xInput, xRadius]) && fn.hypot(p.z, [zInput, zRadius]) + return fn.hypot(fn.safeParseInt(p.x), [xInput, xRadius]) && + fn.hypot(fn.safeParseInt(p.z), [zInput, zRadius]) }) } } diff --git a/src/types/gps.ts b/src/types/gps.ts index fe9e5ac..8345829 100644 --- a/src/types/gps.ts +++ b/src/types/gps.ts @@ -16,12 +16,12 @@ export type RouteKey = keyof RouteType export type Route = RouteType[RouteKey] export type Location = Point2D & { - y?: number + y?: number | string } export type Point2D = { - x: number - z: number + x: number | string + z: number | string } export type RouteInfo = { diff --git a/src/types/oapi_v2.ts b/src/types/oapi_v2.ts index 788b8d8..5665bb5 100644 --- a/src/types/oapi_v2.ts +++ b/src/types/oapi_v2.ts @@ -1,5 +1,5 @@ import { Location } from '../types.js' -import { NestedOmit } from './util.js' +import { NestedOmit, Prettify } from './util.js' //#region Parsed export type OAPITown = NestedOmit = { } } -export type RawEntitySpawn = Location & { +export type RawEntitySpawn = Prettify export type RawTownCoordinates = { spawn: RawEntitySpawn @@ -125,7 +125,7 @@ export type RawTownCoordinates = { } } -export type RawTown = RawEntity & { +export type RawTown = Prettify -export type RawNation = RawEntity & { +export type RawNation = Prettify export type Timestamps = { joinedNationAt?: number @@ -160,7 +160,7 @@ export type Timestamps = { lastOnline?: number } -export type RawResident = RawEntity & { +export type RawResident = Prettify friends?: string[] -} +}> export type RawServerInfo = { world: { diff --git a/src/types/util.ts b/src/types/util.ts index 7109698..89f8aed 100644 --- a/src/types/util.ts +++ b/src/types/util.ts @@ -3,4 +3,8 @@ export type NestedOmit = { NestedOmit}.${infer R}` ? R : never> } extends infer O ? { [P in keyof O]: O[P] } : never; -export type ValidateShape = T extends Shape ? Exclude extends never ? T : never : never; \ No newline at end of file +export type ValidateShape = T extends Shape ? Exclude extends never ? T : never : never; + +export type Prettify = { + [K in keyof T]: T[K] +} & unknown \ No newline at end of file diff --git a/src/utils/endpoint.ts b/src/utils/endpoint.ts index a4e7e1b..b9c0071 100644 --- a/src/utils/endpoint.ts +++ b/src/utils/endpoint.ts @@ -11,6 +11,7 @@ if (useDefaultAgent) useDefaultAgent() * Gets the appropriate endpoint from the given keys. */ const get = (dataType: keyof typeof endpoints, map: ValidMapName) => { + //@ts-ignore return (endpoints[dataType][map.toLowerCase()]) as string } diff --git a/src/utils/functions.ts b/src/utils/functions.ts index 171f503..cdb9285 100644 --- a/src/utils/functions.ts +++ b/src/utils/functions.ts @@ -58,10 +58,22 @@ function getAveragePos(arr: Point2D[]) { } } -const asBool = (str: string) => str == "true", - range = (args: number[]) => Math.round((Math.max(...args) + Math.min(...args)) / 2), - average = (arr: Point2D[], key: keyof Point2D) => arr.map(obj => obj[key]).reduce((a, b) => a + b) / arr.length, - sqr = (a: Point2D, b: Point2D, range: number) => Math.hypot(a.x - b.x, a.z - b.z) <= range +const asBool = (str: string) => str == "true" +const range = (args: number[]) => Math.round((Math.max(...args) + Math.min(...args)) / 2) + +const sqr = (a: Point2D, b: Point2D, range: number) => Math.hypot( + safeParseInt(a.x) - safeParseInt(b.x), + safeParseInt(a.z) - safeParseInt(b.z) +) <= range + +const average = (nums: Point2D[], key: keyof Point2D) => { + const sum = nums.map(obj => obj[key]).reduce((a, b) => safeParseInt(a) + safeParseInt(b)) + return safeParseInt(sum) / nums.length +} + +const safeParseInt = (num: number | string) => { + return typeof num === "number" ? num : parseInt(num) +} const getExisting = (a1: any[], a2: string[], key: keyof T) => { const filter = (x: string) => a1.find(e => x?.toLowerCase() == e[key]?.toLowerCase()) ?? NotFound(x), @@ -114,5 +126,6 @@ export { euclidean, manhattan, strictFalsy, - genRandomString + genRandomString, + safeParseInt } \ No newline at end of file diff --git a/tests/nations.test.ts b/tests/nations.test.ts index c1f290e..2e2ee30 100644 --- a/tests/nations.test.ts +++ b/tests/nations.test.ts @@ -17,7 +17,7 @@ describe('Nations', () => { assertType(nation) expect(nation.name).toBe('Venice') - console.log(nation) + //console.log(nation) }) it('should return different nation info on Aurora and Nova', async () => { diff --git a/tests/towns.test.ts b/tests/towns.test.ts index 47254e0..aaca9a9 100644 --- a/tests/towns.test.ts +++ b/tests/towns.test.ts @@ -18,6 +18,8 @@ describe('Towns', () => { expect(town).toBeDefined() expectTypeOf(town).not.toEqualTypeOf() assertType(town) + + console.log(town) }) it('can get towns invitable to specified nation', async () => { @@ -36,7 +38,7 @@ describe('Towns', () => { ]) expect(novaTown).not.toEqual(auroraTown) - expect(novaTown.stats).toBeUndefined() + expect(novaTown['stats']).toBeUndefined() expect(auroraTown.stats).toBeDefined() expect(auroraTown.wiki).toBeDefined() diff --git a/tsconfig.json b/tsconfig.json index 9c961c5..7e2d102 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,6 +5,7 @@ "moduleDetection": "force", "target": "ES2017", "outDir": "dist", + "noImplicitAny": true, "noUnusedLocals": true, "noUnusedParameters": true, "removeComments": true, @@ -20,6 +21,6 @@ "tslib": ["node_modules/tslib/tslib.d.ts"] } }, - "include": ["src", "endpoints.json"], + "include": ["src"], "exclude": ["node_modules", "docs", "tests", "dist"] } \ No newline at end of file