dokumentation 12 seiten

This commit is contained in:
Hikyu
2026-07-07 16:59:54 +02:00
parent 13154fbb53
commit 3a09a7285e
68 changed files with 7690 additions and 279 deletions
+110
View File
@@ -0,0 +1,110 @@
Default to using Bun instead of Node.js.
- Use `bun <file>` instead of `node <file>` or `ts-node <file>`
- Use `bun test` instead of `jest` or `vitest`
- Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
- Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
- Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
- Bun automatically loads .env, so don't use dotenv.
## APIs
- `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
- `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
- `Bun.redis` for Redis. Don't use `ioredis`.
- `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
- `WebSocket` is built-in. Don't use `ws`.
- Prefer `Bun.file` over `node:fs`'s readFile/writeFile
- Bun.$`ls` instead of execa.
## Testing
Use `bun test` to run tests.
```ts#index.test.ts
import { test, expect } from "bun:test";
test("hello world", () => {
expect(1).toBe(1);
});
```
## Frontend
Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
Server:
```ts#index.ts
import index from "./index.html"
Bun.serve({
routes: {
"/": index,
"/api/users/:id": {
GET: (req) => {
return new Response(JSON.stringify({ id: req.params.id }));
},
},
},
// optional websocket support
websocket: {
open: (ws) => {
ws.send("Hello, world!");
},
message: (ws, message) => {
ws.send(message);
},
close: (ws) => {
// handle close
}
},
development: {
hmr: true,
console: true,
}
})
```
HTML files can import .tsx, .jsx or .js files directly and Bun's bundler will transpile & bundle automatically. `<link>` tags can point to stylesheets and Bun's CSS bundler will bundle.
```html#index.html
<html>
<body>
<h1>Hello, world!</h1>
<script type="module" src="./frontend.tsx"></script>
</body>
</html>
```
With the following `frontend.tsx`:
```tsx#frontend.tsx
import React from "react";
// import .css files directly and it works
import './index.css';
import { createRoot } from "react-dom/client";
const root = createRoot(document.body);
export default function Frontend() {
return <h1>Hello, world!</h1>;
}
root.render(<Frontend />);
```
Then, run index.ts
```sh
bun --hot ./index.ts
```
For more information, read the Bun API docs in `node_modules/bun-types/docs/**.md`.
## Coding Style Preferences
- Write everything WITHOUT comments.
+8
View File
@@ -0,0 +1,8 @@
# Projekt-Dokumentation: Entwicklungsreihenfolge
1. Projekt init
2. Docker compose mit redis
3. Einfache verbindung
4. Redis getestet (mit set, get und incr)
5. Init-Skript (db/init.ts) mit ~100 statischen Entitäten erstellt (für reproduzierbare Tests)
6. Client (index.ts) aktualisiert Player-Daten live und liest statische Gegner-Daten
+15
View File
@@ -0,0 +1,15 @@
# client-redit
To install dependencies:
```bash
bun install
```
To run:
```bash
bun run index.ts
```
This project was created using `bun init` in bun v1.3.3. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
+81
View File
@@ -0,0 +1,81 @@
import { RedisClient } from "bun";
const redis = new RedisClient("redis://localhost:40379");
const DB_NAME = "Redis";
const N1 = 2000;
const N2 = 300;
const region1Enemies = ["1", "2", "3", "11", "12", "13", "14"];
const region1Items = ["1", "8", "21", "26"];
const playerObj = (i: number) => ({
id: 1,
name: "Jonas",
health: 50 + (i % 50),
stamina: 50 + (i % 50),
level: 1 + (i % 20),
region_id: 1,
});
const enemyObj = { id: 0, name: "Benchmark Enemy", health: 1000, level: 20, damage: 50 };
const itemObj = { id: 0, name: "Benchmark Item", gear_type: "weapon", gear_id: 1 };
const regionObj = { id: 1, name: "Limgrave" };
async function writeSingle(i: number) {
await redis.hset("bench:player:1", playerObj(i));
}
async function readSingle(_i: number) {
await redis.hgetall("bench:player:1");
}
async function readRegion(_i: number) {
await redis.hget("region:1", "name");
const enemyIds = await redis.smembers("region:1:enemies");
const itemIds = await redis.smembers("region:1:items");
for (const id of enemyIds) await redis.hgetall(`enemy:${id}`);
for (const id of itemIds) await redis.hgetall(`item:${id}`);
}
async function writeRegion(_i: number) {
await redis.hset("bench:region:1", regionObj);
await redis.sadd("bench:region:1:enemies", ...region1Enemies);
await redis.sadd("bench:region:1:items", ...region1Items);
for (const id of region1Enemies) await redis.hset(`bench:enemy:${id}`, { ...enemyObj, id });
for (const id of region1Items) await redis.hset(`bench:item:${id}`, { ...itemObj, id });
}
async function timed(label: string, group: string, iters: number, opsPerIter: number, fn: (i: number) => Promise<void>) {
const warmup = Math.min(50, iters);
for (let i = 0; i < warmup; i++) await fn(i);
const start = performance.now();
for (let i = 0; i < iters; i++) await fn(i);
const ms = performance.now() - start;
const totalOps = iters * opsPerIter;
const opsPerSec = totalOps / (ms / 1000);
const avgMs = ms / totalOps;
return { label, group, iters, opsPerIter, totalOps, ms, opsPerSec, avgMs };
}
function fmt(r: any) {
return ` ${r.label.padEnd(11)} | ${String(r.totalOps).padStart(6)} Ops | ${r.ms.toFixed(1).padStart(9)} ms | ${Math.round(r.opsPerSec).toString().padStart(9)} Ops/s | ${r.avgMs.toFixed(4)} ms/Op`;
}
await redis.ping();
const w1 = await timed("Schreiben", "Anwendungsfall 1: Live-Player-Sync (1 Schluessel)", N1, 1, writeSingle);
const r1 = await timed("Lesen", "Anwendungsfall 1: Live-Player-Sync (1 Schluessel)", N1, 1, readSingle);
const r2 = await timed("Lesen", "Anwendungsfall 2: Region laden / Fast Travel (14 Schluessel)", N2, 14, readRegion);
const w2 = await timed("Schreiben", "Anwendungsfall 2: Region laden / Fast Travel (14 Schluessel)", N2, 14, writeRegion);
console.log(`\n===== Benchmark: ${DB_NAME} =====`);
console.log(w1.group);
console.log(fmt(w1));
console.log(fmt(r1));
console.log(r2.group);
console.log(fmt(r2));
console.log(fmt(w2));
console.log("##RESULT## " + JSON.stringify({ db: DB_NAME, tests: [w1, r1, r2, w2] }));
process.exit(0);
+26
View File
@@ -0,0 +1,26 @@
{
"lockfileVersion": 1,
"configVersion": 1,
"workspaces": {
"": {
"name": "client-redit",
"devDependencies": {
"@types/bun": "latest",
},
"peerDependencies": {
"typescript": "^5",
},
},
},
"packages": {
"@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
"@types/node": ["@types/node@26.1.0", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-O0A1G3xPGy4w7AgQdAQYUlQ+BKk2Oovw8eRpofyp5KdBZULnbe+WqaOVNrm705SHphCiG4XHsACrSmPu1f+Kgw=="],
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
}
}
File diff suppressed because it is too large Load Diff
+125
View File
@@ -0,0 +1,125 @@
import { write } from "bun";
const API_BASE = "https://eldenring.fanapis.com/api";
async function fetchAll(endpoint: string) {
let allData: any[] = [];
let page = 0;
const limit = 100;
while (true) {
const res = await fetch(`${API_BASE}/${endpoint}?limit=${limit}&page=${page}`);
if (!res.ok) {
console.error(`Error fetching ${endpoint}:`, res.status);
break;
}
const data = await res.json();
if (!data.data || data.data.length === 0) {
break;
}
allData = allData.concat(data.data);
console.log(`Fetched ${allData.length} ${endpoint}...`);
if (data.data.length < limit) {
break;
}
page++;
}
return allData;
}
function extractRegion(entityRegion: string | null | undefined, locationStr: string | null | undefined, locationLookup: Map<string, string>, uniqueRegions: Set<string>): string | null {
// 1. If the entity has a region, use it (and clean up typos from API)
if (entityRegion) {
let r = entityRegion;
if (r === "Liunia of the Lakes") r = "Liurnia of the Lakes";
if (r === "Mountaintop of the Giants") r = "Mountaintops of the Giants";
if (r === "Altus Pleateau") r = "Altus Plateau";
uniqueRegions.add(r);
return r;
}
// 2. Lookup via locations map
if (locationStr) {
for (const [locName, regionName] of locationLookup.entries()) {
if (locationStr.toLowerCase().includes(locName.toLowerCase())) {
return regionName;
}
}
// 3. Fallback: check if the location string itself contains a known dynamic region
for (const region of uniqueRegions) {
if (locationStr.toLowerCase().includes(region.toLowerCase())) {
return region;
}
}
}
return null;
}
async function main() {
console.log("Fetching locations...");
const locations = await fetchAll("locations");
const uniqueRegions = new Set<string>();
const locationLookup = new Map<string, string>();
// Normalize regions and build a lookup map: LocationName -> Region
for (const loc of locations) {
if (loc.region) {
let r = loc.region;
if (r === "Liunia of the Lakes" || r === "Liurnia") r = "Liurnia of the Lakes";
if (r === "Mountaintop of the Giants") r = "Mountaintops of the Giants";
if (r === "Altus Pleateau") r = "Altus Plateau";
uniqueRegions.add(r);
locationLookup.set(loc.name, r);
}
}
console.log("Fetching bosses...");
const bosses = await fetchAll("bosses");
console.log("Fetching creatures...");
const creatures = await fetchAll("creatures");
console.log("Fetching npcs...");
const npcs = await fetchAll("npcs");
const livingEntities = [
...bosses.map(b => ({ ...b, _type: "boss" })),
...creatures.map(c => ({ ...c, _type: "creature" })),
...npcs.map(n => ({ ...n, _type: "npc" }))
];
const cleanedEntities = livingEntities.map(entity => {
// combine all possible location info
const cleanRegion = extractRegion(entity.region, entity.location, locationLookup, uniqueRegions);
return {
id: entity.id,
name: entity.name,
type: entity._type,
cleanRegion: cleanRegion || "Unknown",
originalLocation: entity.location,
drops: entity.drops || []
};
});
// Save regions based on what was dynamically found in the API
const regionsData = Array.from(uniqueRegions).map((r, i) => ({ id: i + 1, name: r }));
console.log("Fetching items...");
const items = await fetchAll("items");
// you might also want weapons, armors etc depending on what "items" means to the user.
// The fan API separates items, weapons, armors, etc. Let's just fetch items for now.
const output = {
regions: regionsData,
entities: cleanedEntities,
items: items.map(i => ({ id: i.id, name: i.name, type: i.type, effect: i.effect }))
};
await write("./db/fanapi_data.json", JSON.stringify(output, null, 2));
console.log("Saved to db/fanapi_data.json");
}
main().catch(console.error);
+34
View File
@@ -0,0 +1,34 @@
import { RedisClient } from "bun";
import { effects, types, weapons, armors, shields, talismans, items, regions, enemies } from "../../data";
const redis = new RedisClient("redis://localhost:40379");
console.log("Populating database with ~100 static Ringstats entries...");
// Helper for hset
const setHash = async (prefix: string, list: any[]) => {
for (const obj of list) {
// extract items/enemies sets if they exist
const { items, enemies, ...hashData } = obj;
await redis.hset(`${prefix}:${obj.id}`, hashData);
if (items && items.length > 0) {
await redis.sadd(`${prefix}:${obj.id}:items`, ...items);
}
if (enemies && enemies.length > 0) {
await redis.sadd(`${prefix}:${obj.id}:enemies`, ...enemies);
}
}
};
await setHash("item_effect", effects);
await setHash("item_type", types);
await setHash("weapon", weapons);
await setHash("armor", armors);
await setHash("shield", shields);
await setHash("talisman", talismans);
await setHash("item", items);
await setHash("region", regions);
await setHash("enemy", enemies);
console.log(`Inserted ${effects.length + types.length + weapons.length + armors.length + shields.length + talismans.length + items.length + regions.length + enemies.length} primary entities into Redis.`);
console.log("Database successfully seeded.");
process.exit(0);
@@ -0,0 +1,6 @@
services:
redis:
image: redis:alpine
ports:
- "40379:6379"
restart: always
+144
View File
@@ -0,0 +1,144 @@
import { RedisClient } from "bun";
const redis = new RedisClient("redis://localhost:40379");
const colors = {
reset: "\x1b[0m",
cyan: "\x1b[36m",
green: "\x1b[32m",
yellow: "\x1b[33m",
magenta: "\x1b[35m",
red: "\x1b[31m",
gray: "\x1b[90m",
bold: "\x1b[1m",
};
let totalRequests = 0;
function log(msg: string, color: string = colors.reset) {
const timestamp = new Date().toISOString().split('T')[1].slice(0, -1);
console.log(`${colors.gray}[${timestamp}]${colors.reset} ${color}${msg}${colors.reset}`);
}
const introMessage = "Starting Ringstats Desktop Application...";
log(introMessage, colors.cyan);
const pingStart = performance.now();
await redis.ping();
totalRequests++;
log(`Connected to Ringstats Database successfully. (Reqs: 1 | Total: ${totalRequests} | Time: ${(performance.now() - pingStart).toFixed(2)}ms)`, colors.green);
log("Looking for Elden Ring process...", colors.gray);
await Bun.sleep(1500);
log("Found Elden Ring process!", colors.green);
log("Equipping initial gear...", colors.gray);
await redis.del("player:1:weapon", "player:1:armor", "player:1:talisman");
await redis.sadd("player:1:weapon", "1");
await redis.sadd("player:1:armor", "11");
await redis.sadd("player:1:talisman", "26");
totalRequests += 4;
let playerHealth = 100;
let playerStamina = 100;
let playerLevel = 1;
let currentRegionId = 1;
log("Entering live sync loop (press Ctrl+C to exit)...", colors.gray);
while (true) {
playerHealth = Math.floor(Math.max(10, playerHealth - (Math.random() * 10) + 5));
playerStamina = Math.floor(Math.max(10, playerStamina - (Math.random() * 20) + 10));
if (Math.random() > 0.9) {
playerLevel += 1;
}
if (Math.random() > 0.85) {
currentRegionId = Math.floor(Math.random() * 16) + 1;
const startTravel = performance.now();
const regionName = await redis.hget(`region:${currentRegionId}`, "name");
const regionEnemiesIds = await redis.smembers(`region:${currentRegionId}:enemies`);
const regionItemsIds = await redis.smembers(`region:${currentRegionId}:items`);
const enemyNames = await Promise.all(regionEnemiesIds.map(id => redis.hget(`enemy:${id}`, "name")));
const itemNames = await Promise.all(regionItemsIds.map(id => redis.hget(`item:${id}`, "name")));
const queries = 3 + regionEnemiesIds.length + regionItemsIds.length;
totalRequests += queries;
const travelTime = (performance.now() - startTravel).toFixed(2);
console.log();
log(`>>> Fast Traveled to: [ID: ${currentRegionId}] ${regionName} <<<`, colors.magenta + colors.bold);
log(`[Region Data] Enemies nearby: ${enemyNames.join(", ") || "None"}`, colors.magenta);
log(`[Region Data] Items nearby: ${itemNames.join(", ") || "None"}`, colors.magenta);
log(`[Stats] Query Time: ${travelTime}ms | Reqs in Block: ${queries} | Total Reqs: ${totalRequests}`, colors.gray);
console.log();
}
if (Math.random() > 0.90) { // 10% chance to swap gear
const newWeaponId = Math.floor(Math.random() * 10) + 1; // 1 to 10
const newArmorId = Math.floor(Math.random() * 10) + 11; // 11 to 20
const newTalismanId = Math.floor(Math.random() * 5) + 26; // 26 to 30
const startSwap = performance.now();
await redis.del("player:1:weapon", "player:1:armor", "player:1:talisman");
await redis.sadd("player:1:weapon", newWeaponId.toString());
await redis.sadd("player:1:armor", newArmorId.toString());
await redis.sadd("player:1:talisman", newTalismanId.toString());
const weaponName = await redis.hget(`item:${newWeaponId}`, "name");
const armorName = await redis.hget(`item:${newArmorId}`, "name");
const talismanName = await redis.hget(`item:${newTalismanId}`, "name");
totalRequests += 7; // 1 del + 3 sadd + 3 hget
const swapTime = (performance.now() - startSwap).toFixed(2);
console.log();
log(`>>> Gear Swapped <<<`, colors.cyan + colors.bold);
log(`Equipped: ${weaponName} | ${armorName} | ${talismanName}`, colors.cyan);
log(`[Stats] Query Time: ${swapTime}ms | Reqs in Block: 7 | Total Reqs: ${totalRequests}`, colors.gray);
console.log();
}
const startSync = performance.now();
await redis.hset("player:1", {
id: 1,
name: "Jonas",
health: playerHealth,
stamina: playerStamina,
level: playerLevel,
region_id: currentRegionId
});
totalRequests += 1;
const syncTime = (performance.now() - startSync).toFixed(2);
log(`[Live Sync] [ID: 1] Jonas - Lvl: ${playerLevel} | HP: ${playerHealth} | Stamina: ${playerStamina}`, colors.green);
log(`[Stats] Query Time: ${syncTime}ms | Reqs in Block: 1 | Total Reqs: ${totalRequests}`, colors.gray);
if (Math.random() > 0.7) {
const startLock = performance.now();
const randomEnemyId = await redis.srandmember(`region:${currentRegionId}:enemies`);
totalRequests += 1;
if (randomEnemyId) {
console.log();
log("--- Target Lock Detected ---", colors.red + colors.bold);
const enemyInfo = await redis.hgetall(`enemy:${randomEnemyId}`);
const dropItemIds = await redis.smembers(`enemy:${randomEnemyId}:items`);
const dropItemNames = await Promise.all(dropItemIds.map(id => redis.hget(`item:${id}`, "name")));
const queries = 2 + dropItemIds.length;
totalRequests += queries;
const lockTime = (performance.now() - startLock).toFixed(2);
log(`Overlay -> [ID: ${enemyInfo.id}] ${enemyInfo.name} | Lvl: ${enemyInfo.level} | HP: ${enemyInfo.health} | DMG: ${enemyInfo.damage}`, colors.yellow);
log(`Drops -> ${dropItemNames.length > 0 ? dropItemNames.join(", ") : "None"}`, colors.yellow);
log(`[Stats] Query Time: ${lockTime}ms | Reqs in Block: ${queries + 1} | Total Reqs: ${totalRequests}`, colors.gray);
console.log();
}
}
await Bun.sleep(2000);
}
+12
View File
@@ -0,0 +1,12 @@
{
"name": "client-redit",
"module": "index.ts",
"type": "module",
"private": true,
"devDependencies": {
"@types/bun": "latest"
},
"peerDependencies": {
"typescript": "^5"
}
}
+29
View File
@@ -0,0 +1,29 @@
{
"compilerOptions": {
// Environment setup & latest features
"lib": ["ESNext"],
"target": "ESNext",
"module": "Preserve",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
}
}