From 29963fa09d816c089a81320efb30484a9979d9a9 Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:59:30 +0330 Subject: [PATCH] feat: add bilingual guild analytics with battle filters and composition insights --- .github/workflows/deploy.yml | 2 + README.md | 50 +++++++ scripts/albion-proxy.mjs | 32 +++++ scripts/build.mjs | 11 +- scripts/render-intel.mjs | 34 +++++ scripts/serve.mjs | 6 + src/intel-core.js | 127 ++++++++++++++++++ src/intel-text.js | 84 ++++++++++++ src/intel.css | 11 ++ src/intel.js | 249 +++++++++++++++++++++++++++++++++++ test/intel.test.mjs | 100 ++++++++++++++ worker.mjs | 20 +++ wrangler.jsonc | 6 + 13 files changed, 730 insertions(+), 2 deletions(-) create mode 100644 scripts/albion-proxy.mjs create mode 100644 scripts/render-intel.mjs create mode 100644 src/intel-core.js create mode 100644 src/intel-text.js create mode 100644 src/intel.css create mode 100644 src/intel.js create mode 100644 test/intel.test.mjs create mode 100644 worker.mjs create mode 100644 wrangler.jsonc diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 43c0fcf..7551e05 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -24,6 +24,8 @@ jobs: run: npm run sync:battles - name: Build static pages run: npm run build + env: + ONEUP_API_BASE_URL: ${{ vars.ONEUP_API_BASE_URL }} - uses: actions/upload-pages-artifact@v4 if: github.event_name != 'pull_request' with: diff --git a/README.md b/README.md index eefdc08..af7a689 100644 --- a/README.md +++ b/README.md @@ -56,3 +56,53 @@ The build emits canonical and language alternate links, social metadata, organiz YouTube uses thumbnails and a privacy-enhanced player loaded on request. Direct video URLs use the native video element. AlbionBB previews are cached at build time; explicit image URLs and Europe single/combined battle preview URLs also work without a local cache. Fonts are served by Google Fonts, with system fallbacks. The GitHub Actions workflow validates pull requests. Pushes to `main` or `master` also synchronize battle previews, build, and deploy the static artifact to GitHub Pages. Generated output is not tracked. + +## Guild intelligence + +Open `/intel/` or `/fa/intel/` to analyze any Europe guild by its exact full name. +The live report includes exact kill/death fame, K/D, recorded attendance and IP, +daily fame, roles, weapons, player rankings, expandable encounter compositions, +source links, and CSV export. Filters and guild name are shareable in the URL. + +- Time windows are rolling 7, 30 or 60 days. Battle times use UTC. +- Minimum players means **all players from all guilds in each original battle**. + For example, 40 includes a 40-player fight even if only four belong to the searched + guild. Filtering happens before merging and applies to every reported statistic. +- Optional grouping uses the archive's continuity criteria: a maximum 20-minute + gap, at least three and 50% overlapping guild members, at least three and 50% + overlap in other teams, and at most a 90-minute encounter span. Each new battle + must match both the first and most recent battle in the group. +- Combined groups are requested from AlbionBB's `/battles/multi` API and their + kill, death and kill-fame totals are verified against the original reports. + End timestamps are taken from the original reports because the multi response + does not reliably contain the latest finish time. +- Composition counts recorded player appearances, once per encounter. The same + member is counted again in another encounter. Zero/missing IP is excluded from + the recorded-IP average. Role/weapon snapshots are not complete movement, + equipment-switch or in-game attendance telemetry. +- Every history page in the time range is scanned. Errors stop the analysis; + partial results are never labelled as a complete report. Retry and cancellation + are available. Requests use bounded concurrency and a short in-page cache. + +### Live API hosting + +AlbionBB allows browser requests only from its own origin. Live reports therefore +require a small server-side read proxy; a GitHub Pages static artifact alone +cannot provide this endpoint. No API key is required. + +`npm run dev` provides `/api/albion/*` automatically. For production there are two options: + +1. Build with `npm run build`, then deploy `worker.mjs` and `dist/` to Cloudflare + Workers using the included `wrangler.jsonc` (e.g. `npx wrangler deploy`). This + serves both the existing site and the same-origin API. Deployment is a separate + operator action; the existing GitHub Pages workflow is unchanged. +2. Keep GitHub Pages and host the Worker separately. Set the Worker's `SITE_ORIGIN` + variable to the exact site origin (for this project, `https://oneup.megh.dad`). + Build the static site with + `ONEUP_API_BASE_URL=https://YOUR-WORKER.workers.dev/api/albion npm run build`. + For the existing CI workflow, set the repository variable `ONEUP_API_BASE_URL` + to that URL. Only the configured origin receives cross-origin access. + +The proxy permits GET requests to a fixed Europe upstream and a small allowlist +of public report routes and parameters. It does not forward cookies or credentials. +Upstream timeouts and rate limits produce a visible error with a retry option. diff --git a/scripts/albion-proxy.mjs b/scripts/albion-proxy.mjs new file mode 100644 index 0000000..a14babe --- /dev/null +++ b/scripts/albion-proxy.mjs @@ -0,0 +1,32 @@ +// Shared by the local server and the optional Cloudflare Worker. No arbitrary upstream URLs. +const API = 'https://api.albionbb.com/eu'; +export function upstreamUrl(requestUrl) { + const input = new URL(requestUrl), path = input.pathname.replace(/^\/api\/albion/, ''); + const allowed = path === '/guilds/search' || path === '/battles' || path === '/battles/multi' || /^\/battles\/\d+$/.test(path); + if (!input.pathname.startsWith('/api/albion/') || !allowed) throw Error('Unsupported API path'); + const url = new URL(API + path); + const allowedKeys = path === '/guilds/search' ? ['search'] : path === '/battles' ? ['guildId','page','minPlayers','minGuildPlayers'] : path === '/battles/multi' ? ['ids'] : []; + for (const [key, value] of input.searchParams) { + if (!allowedKeys.includes(key) || value.length > 2000) throw Error('Invalid API parameter'); + url.searchParams.set(key, value); + } + if (path === '/guilds/search' && (!url.searchParams.get('search')?.trim() || url.searchParams.get('search').length > 100)) throw Error('Invalid guild name'); + if (path === '/battles') { + if (!/^[\w-]{1,64}$/.test(url.searchParams.get('guildId') || '')) throw Error('Invalid guild ID'); + for (const key of ['page','minPlayers','minGuildPlayers']) if (url.searchParams.has(key) && !/^\d{1,5}$/.test(url.searchParams.get(key))) throw Error('Invalid numeric parameter'); + } + if (path === '/battles/multi' && !/^\d+(,\d+){1,99}$/.test(url.searchParams.get('ids') || '')) throw Error('Invalid battle IDs'); + return url; +} +export async function proxyAlbion(request, fetchImpl = fetch) { + if (request.method !== 'GET') return Response.json({ error: 'Method not allowed' }, { status: 405, headers: { Allow: 'GET' } }); + let url; + try { url = upstreamUrl(request.url); } + catch { return Response.json({ error: 'Invalid Albion API request' }, { status: 400 }); } + try { + const result = await fetchImpl(url, { headers: { Accept: 'application/json' }, redirect: 'error', signal: AbortSignal.timeout(30_000) }); + if (!result.ok) return Response.json({ error: 'AlbionBB is temporarily unavailable', upstreamStatus: result.status }, { status: result.status === 429 ? 429 : 502 }); + const body = await result.json(); + return Response.json(body, { headers: { 'Cache-Control': 'public, max-age=120', 'X-Content-Type-Options': 'nosniff' } }); + } catch { return Response.json({ error: 'Unable to reach AlbionBB' }, { status: 502 }); } +} diff --git a/scripts/build.mjs b/scripts/build.mjs index 96f7922..421f00c 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -1,6 +1,7 @@ import { readFile, writeFile, mkdir, rm, cp, access } from 'node:fs/promises'; import { escapeHtml as e, localized, youtubeId, validate } from './lib.mjs'; import { renderBattleCards } from './render-battles.mjs'; +import { renderIntel } from './render-intel.mjs'; const read = async name => JSON.parse(await readFile(new URL(`../content/${name}.json`, import.meta.url), 'utf8')); const [site, rewards, translations] = await Promise.all(['site','rewards','translations'].map(read)); @@ -12,6 +13,7 @@ const dist = new URL('../dist/', import.meta.url); await rm(dist, { recursive: true, force: true }); await mkdir(new URL('assets/', dist), { recursive: true }); for (const [from,to] of [['src/styles.css','styles.css'],['src/app.js','app.js']]) await cp(new URL(from,root),new URL(`assets/${to}`,dist)); +for (const name of ['intel.js','intel-core.js','intel-text.js','intel.css']) await cp(new URL(`src/${name}`,root),new URL(`assets/${name}`,dist)); try { await cp(new URL('public/assets/',root),new URL('assets/',dist),{ recursive:true }); } catch(err) { if(err.code !== 'ENOENT') throw err; } await rm(new URL('assets/battles/previews.json',dist),{force:true}); const faviconLogo=(await readFile(new URL('public/assets/logo.jpg',root))).toString('base64'); @@ -63,7 +65,7 @@ function render(lang) { ${glyphs}
${e(site.recruiting?t.recruiting:t.closed)}

${e(t.eyebrow)}

${e(t.hero1)}
${e(t.hero2)}

${e(t.intro)}

${e(site.members)}${e(t.memberLabel)}
${icon('shield')}
↓${e(t.scroll)}
@@ -80,12 +82,17 @@ function render(lang) { for (const lang of ['en','fa']) { const folder=lang==='en'?dist:new URL('fa/',dist); await mkdir(folder,{recursive:true}); await writeFile(new URL('index.html',folder),render(lang)); + const intelFolder=new URL('intel/',folder); + await mkdir(intelFolder,{recursive:true}); + const apiBase=process.env.ONEUP_API_BASE_URL || '/api/albion'; + if (apiBase !== '/api/albion' && (!apiBase.startsWith('https://') || new URL(apiBase).search || new URL(apiBase).hash)) throw Error('ONEUP_API_BASE_URL must be an HTTPS API base URL'); + await writeFile(new URL('index.html',intelFolder),renderIntel(lang,origin,apiBase)); } await Promise.all([ writeFile(new URL('CNAME',dist),new URL(origin).hostname+'\n'), writeFile(new URL('.nojekyll',dist),''), writeFile(new URL('robots.txt',dist),`User-agent: *\nAllow: /\nSitemap: ${origin}/sitemap.xml\n`), - writeFile(new URL('sitemap.xml',dist),`${['/','/fa/'].map(p=>`${origin}${p}`).join('')}`), + writeFile(new URL('sitemap.xml',dist),`${['/','/fa/','/intel/','/fa/intel/'].map(p=>`${origin}${p}`).join('')}`), writeFile(new URL('404.html',dist),`Lost in the Outlands | OneUP

404 / BEYOND THE FRONT LINE

Lost in the
Outlands.

The banner is this way.

Return to OneUP →بازگشت به وان‌آپ
`) ]); console.log(`Built English and Persian pages in dist/ for ${origin}`); diff --git a/scripts/render-intel.mjs b/scripts/render-intel.mjs new file mode 100644 index 0000000..c2f5a4b --- /dev/null +++ b/scripts/render-intel.mjs @@ -0,0 +1,34 @@ +import { escapeHtml as e } from './lib.mjs'; +import { textFor } from '../src/intel-text.js'; + +export function renderIntel(lang, origin, apiBase = '/api/albion') { + const fa = lang === 'fa', t = textFor(lang), base = fa ? '../../' : '../'; + return ` + +${e(t.title)} | OneUP + + + + + + +
ONEUPGUILD INTELLIGENCE +${e(t.back)} +
+
+

${e(t.eyebrow)}

${e(t.hero)}
${e(t.accent)}

${e(t.intro)}

${e(t.region)}/${e(t.live)}
+
+ +
${e(t.period)}
${[7,30,60].map(days => ``).join('')}
+
+ +

${e(t.minimumHelp)}

+
${e(t.ready)}
+

GUILD / BATTLE / COMPOSITION

${e(t.idleTitle)}

${e(t.idleCopy)}

${[t.step1,t.step2,t.step3].map((x,i) => `0${i+1}${e(x)}`).join('')}
+ + +
${e(t.methodology)}

${e(t.caveat)}

${e(t.mergeHelp)}

${e(t.minimumHelp)}

+
+ +`; +} diff --git a/scripts/serve.mjs b/scripts/serve.mjs index 02a16be..c2ea1b1 100644 --- a/scripts/serve.mjs +++ b/scripts/serve.mjs @@ -2,12 +2,18 @@ import http from 'node:http'; import { readFile, stat } from 'node:fs/promises'; import { resolve, extname, sep } from 'node:path'; import { spawnSync } from 'node:child_process'; +import { proxyAlbion } from './albion-proxy.mjs'; const built = spawnSync(process.execPath, ['scripts/build.mjs'], { stdio:'inherit' }); if (built.status) process.exit(built.status); const root=resolve('dist'); const types={'.html':'text/html; charset=utf-8','.css':'text/css','.js':'text/javascript','.jpg':'image/jpeg','.png':'image/png','.webp':'image/webp','.svg':'image/svg+xml','.xml':'application/xml','.txt':'text/plain'}; http.createServer(async(req,res)=>{ try { + if (new URL(req.url,'http://localhost').pathname.startsWith('/api/albion/')) { + const response = await proxyAlbion(new Request(new URL(req.url,'http://localhost'), { method: req.method })); + res.writeHead(response.status, Object.fromEntries(response.headers)).end(Buffer.from(await response.arrayBuffer())); + return; + } let path=resolve(root, '.'+decodeURIComponent(new URL(req.url,'http://localhost').pathname)); if(path!==root && !path.startsWith(root+sep)){res.writeHead(403).end();return;} if((await stat(path)).isDirectory()) path=resolve(path,'index.html'); diff --git a/src/intel-core.js b/src/intel-core.js new file mode 100644 index 0000000..f7efeca --- /dev/null +++ b/src/intel-core.js @@ -0,0 +1,127 @@ +// Pure report logic shared by the browser and the verification suite. +export const ROLES = ['tank', 'healer', 'support', 'range', 'melee', 'battlemount', 'unknown']; +export const normalizeName = value => String(value ?? '').normalize('NFKC').trim().toLocaleLowerCase('en-US'); +export const ownGuild = (battle, guildId) => battle.guilds?.find(g => g.albionId === guildId); +export const ownPlayers = (battle, guildId) => { + const guild = ownGuild(battle, guildId); + return (battle.players || []).filter(p => guild && normalizeName(p.guildName) === normalizeName(guild.name)); +}; +const millis = value => Date.parse(value); +const overlap = (a, b) => { + const shared = [...a].reduce((sum, [key, count]) => sum + Math.min(count, b.get(key) || 0), 0); + const smaller = Math.min(...[a, b].map(m => [...m.values()].reduce((sum, n) => sum + n, 0))); + return { shared, ratio: smaller ? shared / smaller : 0 }; +}; +function otherTeams(battle, guildId) { + const guild = ownGuild(battle, guildId), teams = new Map(); + for (const g of battle.guilds || []) { + if (g.albionId === guildId || (guild?.alliance && guild.alliance === g.alliance)) continue; + const key = g.alliance ? `alliance:${g.alliance}` : `guild:${g.albionId}`; + teams.set(key, (teams.get(key) || 0) + g.players); + } + return teams; +} +export function compatible(a, b, guildId) { + const roster = overlap(...[a, b].map(x => new Map(ownPlayers(x, guildId).map(p => [p.name, 1])))); + const teams = overlap(otherTeams(a, guildId), otherTeams(b, guildId)); + return roster.shared >= 3 && roster.ratio >= .5 && teams.shared >= 3 && teams.ratio >= .5; +} +export function groupReports(battles, guildId, merge = true) { + const sorted = [...new Map(battles.map(b => [b.albionId, b])).values()] + .sort((a, b) => millis(a.startedAt) - millis(b.startedAt) || a.albionId - b.albionId); + const groups = []; + for (const battle of sorted) { + const candidates = merge ? groups.filter(group => { + const last = group.at(-1); + const end = Math.max(...[...group, battle].map(b => millis(b.finishedAt || b.startedAt))); + return millis(battle.startedAt) - millis(last.finishedAt || last.startedAt) <= 20 * 60_000 && + end - millis(group[0].startedAt) <= 90 * 60_000 && + compatible(last, battle, guildId) && compatible(group[0], battle, guildId); + }) : []; + candidates.sort((a, b) => millis(b.at(-1).finishedAt) - millis(a.at(-1).finishedAt)); + if (candidates.length) candidates[0].push(battle); else groups.push([battle]); + } + return groups; +} +export function selectBattles(battles, guildId, { since, until, minPlayers }) { + return battles.filter(b => millis(b.startedAt) >= since && millis(b.startedAt) <= until && + ownGuild(b, guildId) && b.totalPlayers >= minPlayers); +} +export function makeReport(group, combined, guildId) { + const battle = combined || group[0]; + if (!ownGuild(battle, guildId) || !Array.isArray(battle.players)) throw Error('Invalid guild report'); + return { + ids: group.map(b => b.albionId), battle, guild: ownGuild(battle, guildId), + players: ownPlayers(battle, guildId), + startedAt: new Date(Math.min(...group.map(b => millis(b.startedAt)))).toISOString(), + // The multi API's end timestamp is not reliably the maximum end time. + finishedAt: new Date(Math.max(...group.map(b => millis(b.finishedAt || b.startedAt)))).toISOString(), + url: `https://europe.albionbb.com/battles/${group.length > 1 ? `multi?ids=${group.map(b => b.albionId).join(',')}` : group[0].albionId}`, + }; +} +export function summarize(reports) { + const summary = { kills: 0, deaths: 0, killFame: 0, deathFame: 0, attendance: 0, ip: 0, ipCount: 0, + roles: Object.fromEntries(ROLES.map(r => [r, 0])), weapons: new Map(), players: new Map(), daily: new Map() }; + for (const report of reports) { + const guild = report.guild; + summary.kills += guild.kills || 0; summary.deaths += guild.deaths || 0; + summary.killFame += guild.killFame || 0; summary.attendance += guild.players || 0; + const date = report.startedAt.slice(0, 10); + summary.daily.set(date, (summary.daily.get(date) || 0) + (guild.killFame || 0)); + for (const p of report.players) { + const role = ROLES.includes(p.role) ? p.role : 'unknown'; + summary.roles[role]++; + summary.deathFame += p.deathFame || 0; + if (p.ip > 0) { summary.ip += p.ip; summary.ipCount++; } + const equipment = role === 'battlemount' && typeof p.mount === 'string' + ? { name: p.mount, type: p.mount, quality: 1 } : p.weapon; + if (equipment?.name) { + const key = `${role}:${equipment.name}`; + const weapon = summary.weapons.get(key) || { ...equipment, role, count: 0 }; + weapon.count++; summary.weapons.set(key, weapon); + } + const player = summary.players.get(p.name) || { name: p.name, kills: 0, deaths: 0, killFame: 0, attendance: 0, heal: 0, damage: 0 }; + for (const key of ['kills', 'deaths', 'killFame', 'heal', 'damage']) player[key] += p[key] || 0; + player.attendance++; summary.players.set(p.name, player); + } + } + summary.averageAttendance = reports.length ? summary.attendance / reports.length : 0; + summary.averageIp = summary.ipCount ? summary.ip / summary.ipCount : 0; + return summary; +} + +export async function mapLimit(items, limit, task) { + const results = new Array(items.length); + let next = 0, failed = false; + await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => { + while (!failed) { + const index = next++; + if (index >= items.length) return; + try { results[index] = await task(items[index], index); } + catch (error) { failed = true; throw error; } + } + })); + return results; +} + +export async function scanListings(api, guildId, since, signal, progress = () => {}, minPlayers = 1) { + const found = new Map(); + // Fetch every page in range; do not present a fixed first-page sample as a full history. + for (let page = 1; page <= 1000; page++) { + signal?.throwIfAborted(); + const rows = await api('/battles', { guildId, minPlayers, minGuildPlayers: 1, page }, signal); + if (!Array.isArray(rows)) throw Error('Invalid battle listing'); + let added = 0; + for (const row of rows) { + if (!Number.isSafeInteger(row.albionId) || !Number.isFinite(millis(row.startedAt))) throw Error('Invalid battle listing'); + if (!found.has(row.albionId)) added++; + found.set(row.albionId, row); + } + progress(page, found.size); + if (rows.length < 20 || rows.every(b => millis(b.startedAt) < since)) { + return [...found.values()].filter(b => millis(b.startedAt) >= since); + } + if (!added) throw Error('Pagination stopped advancing'); + } + throw Error('History scan exceeded 1000 pages; narrow the date range.'); +} diff --git a/src/intel-text.js b/src/intel-text.js new file mode 100644 index 0000000..d259d49 --- /dev/null +++ b/src/intel-text.js @@ -0,0 +1,84 @@ +const messages = { + title: ['Guild intelligence', 'مرکز تحلیل گیلد'], + back: ['Back to OneUP', 'بازگشت به وان‌آپ'], + eyebrow: ['ONEUP / BATTLE INTELLIGENCE', 'ONEUP / تحلیل میدان نبرد'], + hero: ['Every battle.', 'هر نبرد،'], + accent: ['A clearer picture.', 'تصویری روشن‌تر.'], + intro: ['Read the guild behind the numbers. Explore its kill fame, fighting strength and the compositions it brings to battle.', 'پشت هر عدد، یک گیلد است. فیم به‌دست‌آمده، قدرت حضور و ترکیب نیروهایش را در نبردها بررسی کن.'], + region: ['EUROPE SERVER', 'سرور اروپا'], + live: ['LIVE REPORTS', 'گزارش‌های زنده'], + guild: ['Full guild name', 'نام کامل گیلد'], + placeholder: ['e.g. OneUP', 'مثلاً OneUP'], + period: ['Time window', 'بازهٔ زمانی'], + days: ['days', 'روز'], + minimum: ['Minimum total battle players', 'حداقل کل بازیکنان بتل'], + minimumHelp: ['All guilds combined, before merging. 40 excludes every original battle with fewer than 40 total participants.', 'مجموع بازیکنان همهٔ گیلدها، پیش از ادغام. عدد ۴۰ هر بتلی با کمتر از ۴۰ شرکت‌کننده در مجموع را حذف می‌کند.'], + merge: ['Combine related battles', 'ادغام بتل‌های مرتبط'], + mergeHelp: ['Up to 20 minutes apart, with at least 50% shared guild roster and similar other teams. Maximum combined span: 90 minutes.', 'فاصله تا ۲۰ دقیقه، حداقل ۵۰٪ اشتراک اعضای گیلد و ترکیب مشابه سایر تیم‌ها؛ طول هر درگیری حداکثر ۹۰ دقیقه.'], + analyze: ['Analyze guild', 'تحلیل گیلد'], + cancel: ['Cancel', 'لغو'], + idleTitle: ['Your next opponent. Your own guild.', 'رقیب بعدی‌ات؛ یا گیلد خودت.'], + idleCopy: ['Enter an exact guild name to build a report from real AlbionBB battle data.', 'نام کامل یک گیلد را وارد کن تا گزارش آن از داده‌های واقعی AlbionBB ساخته شود.'], + step1: ['Find the guild', 'پیدا کردن گیلد'], + step2: ['Connect the battles', 'کنار هم گذاشتن نبردها'], + step3: ['Read the composition', 'شناخت ترکیب نیروها'], + ready: ['Ready when you are', 'آمادهٔ تحلیل'], + finding: ['Finding the exact guild…', 'در حال یافتن گیلد با نام دقیق…'], + scanning: ['Scanning battle history', 'در حال خواندن تاریخچهٔ بتل‌ها'], + page: ['page', 'صفحه'], + battles: ['battles', 'بتل'], + details: ['Loading battle details', 'در حال دریافت جزئیات بتل‌ها'], + merging: ['Building combined reports', 'در حال ساخت گزارش‌های ادغام‌شده'], + notFound: ['No exact match. Check the full guild name on the Europe server.', 'گیلدی با این نام دقیق پیدا نشد. نام کامل گیلد را در سرور اروپا بررسی کن.'], + ambiguous: ['Several guilds have this name. Select the intended guild:', 'چند گیلد با این نام پیدا شد. گیلد موردنظر را انتخاب کن:'], + error: ['The report could not be completed. Check your connection and try again. No incomplete totals are shown.', 'گزارش کامل نشد. اتصال را بررسی کن و دوباره تلاش کن. آمار ناقص به‌عنوان نتیجه نمایش داده نمی‌شود.'], + proxyError: ['The report service is unavailable. On static hosting, configure the Albion API Worker described in the project README.', 'سرویس گزارش در دسترس نیست. برای میزبانی استاتیک، واسط API توضیح‌داده‌شده در README پروژه باید فعال باشد.'], + retry: ['Try again', 'تلاش دوباره'], + cancelled: ['Analysis cancelled. Adjust the filters and try again.', 'تحلیل لغو شد. فیلترها را تنظیم کن و دوباره شروع کن.'], + emptyTitle: ['No battles in this window.', 'در این بازه بتلی پیدا نشد.'], + emptyCopy: ['Try a longer time window or lower the minimum total battle players.', 'بازهٔ زمانی را بیشتر کن یا حداقل تعداد کل بازیکنان بتل را کاهش بده.'], + overview: ['Performance overview', 'نمای کلی عملکرد'], + encounters: ['Encounters', 'درگیری'], + original: ['Original battles', 'بتل اصلی'], + killFame: ['Kill fame earned', 'کیل فیم کسب‌شده'], + deathFame: ['Death fame', 'فیم تلفات'], + netFame: ['Net fame', 'خالص فیم'], + kills: ['Kills', 'کیل'], + deaths: ['Deaths', 'مرگ'], + kd: ['Kill / death ratio', 'نسبت کیل به مرگ'], + attendance: ['Avg. guild attendance', 'میانگین حضور گیلد'], + players: ['members', 'نفر'], + totalPlayers: ['total battle players', 'بازیکن در کل بتل'], + guildPlayers: ['guild members', 'عضو گیلد'], + unique: ['Unique members', 'اعضای یکتا'], + avgIp: ['Avg. recorded IP', 'میانگین IP ثبت‌شده'], + trend: ['Fame across the campaign', 'روند فیم در این بازه'], + trendHint: ['Kill fame per day · UTC', 'کیل فیم روزانه · زمان UTC'], + composition: ['Anatomy of the guild', 'ترکیب نیروهای گیلد'], + compositionHint: ['Role distribution across included encounters', 'سهم نقش‌ها در درگیری‌های انتخاب‌شده'], + appearances: ['member appearances', 'حضور بازیکن'], + tanks: ['Tanks', 'تانک'], healers: ['Healers', 'هیلر'], supports: ['Supports', 'ساپورت'], + ranges: ['Ranged DPS', 'رنج'], melees: ['Melee DPS', 'میلی'], battlemounts: ['Battle mounts', 'بتل‌مانت'], unknowns: ['Unknown', 'نامشخص'], + weapons: ['Weapons of choice', 'سلاح‌های منتخب'], + weaponHint: ['Frequency in recorded compositions', 'دفعات حضور در composition ثبت‌شده'], + allRoles: ['All roles', 'همهٔ نقش‌ها'], + noWeapons: ['No recorded weapons for this role.', 'برای این نقش سلاحی ثبت نشده است.'], + leaderboard: ['People behind the performance', 'بازیکنان اثرگذار'], + name: ['Player', 'بازیکن'], presence: ['Attendance', 'حضور'], heal: ['Healing', 'هیل'], damage: ['Damage', 'دمیج'], + ledger: ['The battle ledger', 'دفتر نبردها'], + ledgerHint: ['Open an encounter to inspect its composition.', 'هر درگیری را باز کن تا ترکیب نیروهایش را ببینی.'], + searchBattle: ['Filter by other guild or battle ID', 'فیلتر نام گیلد دیگر یا شناسهٔ بتل'], + recent: ['Most recent', 'جدیدترین'], mostFame: ['Highest kill fame', 'بیشترین کیل فیم'], mostPlayers: ['Largest guild attendance', 'بیشترین حضور گیلد'], + report: ['Full report', 'گزارش کامل'], merged: ['combined', 'ادغام‌شده'], single: ['Single battle', 'تک‌بتل'], + otherGuilds: ['Other guilds', 'سایر گیلدها'], + methodology: ['How to read this report', 'راهنمای خواندن گزارش'], + caveat: ['Attendance and composition reflect players recorded by AlbionBB, not a complete in-game mass. Composition is counted once per player per encounter; a member appearing in several encounters is counted in each. Weapon swaps during a fight may not all be represented. Kill fame alone does not establish victory or tactical quality.', 'حضور و ترکیب نیروها مربوط به بازیکنان ثبت‌شده در AlbionBB است و لزوماً تمام مس بازی نیست. در هر درگیری، هر بازیکن یک‌بار در composition شمرده می‌شود؛ حضور در چند درگیری چند بار محاسبه می‌شود. همهٔ تعویض سلاح‌ها لزوماً در گزارش دیده نمی‌شوند. کیل فیم به‌تنهایی معیار پیروزی یا کیفیت تاکتیکی نیست.'], + filtered: ['Filters apply to every statistic below.', 'همهٔ آمار زیر بر اساس فیلترهای انتخابی است.'], + loaded: ['Updated', 'دریافت داده'], + partial: ['Some reports were unavailable. Retry to build a complete analysis.', 'بعضی گزارش‌ها در دسترس نبودند. برای تحلیل کامل دوباره تلاش کن.'], + export: ['Download CSV', 'دانلود CSV'], + noMatch: ['No encounters match this search.', 'درگیری مطابق این جست‌وجو پیدا نشد.'], + more: ['Show more encounters', 'نمایش درگیری‌های بیشتر'], + service: ['Source: AlbionBB · Europe · All battle times in UTC', 'منبع: AlbionBB · اروپا · تمام زمان‌های بتل به UTC'], +}; +export const textFor = lang => Object.fromEntries(Object.entries(messages).map(([key, pair]) => [key, pair[lang === 'fa' ? 1 : 0]])); diff --git a/src/intel.css b/src/intel.css new file mode 100644 index 0000000..3ec59c5 --- /dev/null +++ b/src/intel.css @@ -0,0 +1,11 @@ +.intel-page{background:#101111;background-image:radial-gradient(ellipse at 95% 0,#78202d17,transparent 38%);--positive:#75c6a8;--negative:#ee8590} +.intel-page button,.intel-page input,.intel-page select{font:inherit}.intel-page input,.intel-page select{color:var(--text);background:#111314;border:1px solid #ffffff25;border-radius:5px;min-height:46px;padding:10px 14px;outline:none}.intel-page input:focus,.intel-page select:focus{border-color:var(--accent);box-shadow:0 0 0 3px #e3485014}.intel-page input::placeholder{color:#747b7d}.intel-page select{font-size:12px;max-width:100%}.intel-page button:disabled{opacity:.5;cursor:wait}.intel-header{max-width:1380px;margin:auto;padding:25px 4%;display:flex;align-items:center;gap:36px;border-bottom:1px solid var(--line)}.intel-header .brand{margin-inline-end:auto}.intel-header .brand small{font-size:7px;letter-spacing:2px}.intel-back{font-size:12px;color:var(--muted)}.intel-back span{color:var(--accent);margin-inline-start:8px}.intel-main{max-width:1280px;margin:auto;padding:0 4% 70px}.intel-hero{position:relative;min-height:315px;padding:58px 0 50px;overflow:hidden}.intel-hero .eyebrow{margin-bottom:18px;font-size:9px}.intel-hero h1{font:600 clamp(58px,6.3vw,88px)/.97 var(--display);letter-spacing:-1.5px;margin:0}.intel-hero h1>span{color:#d65362}.intel-intro{max-width:510px;font-size:13px;color:var(--muted);line-height:1.9;margin:22px 0 8px}.intel-source{position:absolute;inset-inline-end:0;bottom:40px;display:flex;align-items:center;gap:9px;font-size:8px;letter-spacing:1.5px;color:#aaa6a0}.live-dot{width:5px;height:5px;background:#75c6a8;border-radius:50%;box-shadow:0 0 12px #75c6a855}.source-divider{margin:0 6px;color:#4a4a49}.intel-signal{position:absolute;inset-inline-end:6%;top:15px;width:275px;height:275px;display:grid;place-items:center;opacity:.8;pointer-events:none}.signal-orbit{position:absolute;inset:0;border:1px solid #df596024;border-radius:50%;background:repeating-conic-gradient(from 0deg,transparent 0deg 29.7deg,#c34c591c 29.7deg 30deg);mask-image:radial-gradient(transparent 0 46%,#000 47%)}.signal-orbit:after{content:'';position:absolute;width:10px;height:10px;border:1px solid #e34850;top:35px;right:33px;transform:rotate(45deg);box-shadow:0 0 20px #e3485060}.orbit-inner{inset:40px;border-style:dashed;transform:rotate(20deg)}.signal-center{font:700 100px/.8 var(--display);letter-spacing:-7px;color:#e8e1da}.signal-center>span{font-size:45px;letter-spacing:-2px;color:#d94d5a}.intel-signal>i{position:absolute;width:320px;height:1px;background:linear-gradient(90deg,transparent,#e3485050,transparent);transform:rotate(-35deg)}.intel-signal>b{position:absolute;bottom:66px;font-size:7px;letter-spacing:4px;color:#a47279;font-weight:400}.intel-controls{border:1px solid #ffffff26;border-top:2px solid #b13a47;background:linear-gradient(120deg,#1b1a1c,#151718);border-radius:8px;padding:24px 25px 0;box-shadow:0 20px 60px #0002}.intel-controls form{display:grid;grid-template-columns:1.5fr 1.05fr 1fr auto;gap:22px;align-items:end}.intel-controls label,.intel-controls legend{display:block;color:#c0bdb8;font-size:11px;margin-bottom:8px}.intel-controls input{width:100%}.search-field{position:relative}.search-field>span{position:absolute;left:13px;top:0;font:34px/46px var(--body);color:#8b6c72}.search-field input{padding-left:43px;font-size:15px}.period-field{padding:0;border:0;margin:0;min-width:0}.period-options{display:flex;gap:4px;border:1px solid #ffffff25;border-radius:5px;padding:4px;background:#111314;height:46px}.period-options label{position:relative;margin:0;flex:1;cursor:pointer}.period-options input{position:absolute;opacity:0;inset:0;min-height:0;cursor:pointer}.period-options span{display:block;text-align:center;border-radius:3px;font-size:15px;line-height:36px;color:#939696;white-space:nowrap}.period-options small{font-size:10px}.period-options input:checked+span{background:#543039;color:#ffe5e7;box-shadow:inset 0 0 0 1px #c55b6b40}.period-options input:focus-visible+span{outline:2px solid var(--accent)}.intel-submit{white-space:nowrap;border-radius:5px;gap:22px;min-height:46px;font-size:12px;padding:10px 20px}.intel-control-bottom{grid-column:1/-1;display:flex;align-items:center;gap:24px;border-top:1px solid var(--line);padding:15px 0;margin-top:0}.intel-controls .merge-control{display:flex;align-items:center;gap:9px;white-space:nowrap;font-size:10px;margin:0;cursor:pointer;position:relative}.merge-control input{position:absolute;opacity:0;width:30px;height:20px;min-height:0}.switch{width:28px;height:16px;border-radius:10px;background:#45474b;border:1px solid #ffffff20;position:relative}.switch:after{content:'';position:absolute;width:10px;height:10px;border-radius:50%;background:#cdc7c7;left:2px;top:2px;transition:transform .2s}.merge-control input:checked+.switch{background:#9d3543}.merge-control input:checked+.switch:after{transform:translateX(12px);background:#fff1f1}.merge-control input:focus-visible+.switch{outline:2px solid var(--accent)}.intel-control-bottom p{font-size:10px;line-height:1.7;color:#93918e;margin:0;border-inline-start:1px solid var(--line);padding-inline-start:20px}.intel-status{min-height:62px;display:flex;align-items:center;gap:9px;font-size:10px;color:#8d9392;padding:12px 3px;line-height:1.8}.status-mark{width:5px;height:5px;border-radius:50%;background:#7b8582;flex-shrink:0}.is-loading .status-mark{background:var(--accent);animation:intel-pulse 1s infinite}.intel-status button{margin-inline-start:auto;background:#ffffff08;color:#dad2cf;border:1px solid var(--line);border-radius:4px;padding:5px 12px;white-space:nowrap}.intel-empty{padding:56px 20px 65px;text-align:center;border:1px dashed #ffffff1b;border-radius:8px;background:radial-gradient(ellipse at 50% 0,#7337420d,transparent 75%)}.empty-crosshair{font-size:40px;color:#a24e5a;margin-bottom:18px}.intel-empty .eyebrow{font-size:8px;color:#9c6e76;margin-bottom:18px}.intel-empty h2{font:500 35px/1.4 var(--display);letter-spacing:0}.intel-empty>p:not(.eyebrow){color:var(--muted);font-size:12px;margin:12px auto;max-width:530px}.intel-steps{display:flex;justify-content:center;gap:40px;margin-top:30px}.intel-steps span{display:flex;align-items:center;gap:9px;font-size:10px;color:#b1aaa6}.intel-steps b{font:400 18px var(--display);color:#d16473}.intel-method{margin-top:35px;border-block:1px solid var(--line);font-size:11px;color:var(--muted);padding:16px 0}.intel-method summary{display:flex;align-items:center;justify-content:space-between;cursor:pointer;list-style:none;color:#c4bfba}.intel-method summary::-webkit-details-marker{display:none}.intel-method summary span{color:var(--accent);font-size:22px}.intel-method p{max-width:950px;line-height:2}.intel-footer{border-top:1px solid var(--line);max-width:1280px;margin:auto;padding:24px 4% 35px;display:flex;justify-content:space-between;align-items:center;gap:25px;color:#7c8380;font-size:9px}.intel-footer>span{font-weight:700;letter-spacing:1px;color:#c4b9b6}.intel-footer>span>span{color:var(--accent)}.intel-footer>a{font-size:8px;letter-spacing:1px}.intel-error,.intel-no-results{padding:35px;border:1px solid #a6484b70;background:#e3485008;border-radius:7px}.intel-error h2,.intel-no-results h2{font-size:30px}.intel-error p,.intel-no-results p{font-size:12px;color:var(--muted)}.intel-error .button{font-size:12px;padding:9px 15px}.guild-choice{display:block;background:#ffffff09;border:1px solid var(--line);padding:12px;margin:10px 0;text-align:start;border-radius:4px}.intel-result-heading{display:flex;justify-content:space-between;gap:24px;align-items:center;margin:20px 0 26px}.intel-result-heading .eyebrow{font-size:9px;margin-bottom:8px}.intel-result-heading h2{font:600 46px/1.2 var(--display);display:flex;align-items:center;gap:14px}.guild-region{font:500 9px var(--body);color:#d7b7bd;border:1px solid #c45e7045;padding:3px 7px;border-radius:3px;letter-spacing:1px}.intel-result-heading p:not(.eyebrow){font-size:11px;color:#c4bab4;line-height:1.9;margin-bottom:0}.intel-result-heading p>span{font-size:10px;color:#858b86}.intel-download{background:transparent;border:1px solid #ffffff25;padding:9px 15px;border-radius:5px;font-size:11px;color:#cac2bd}.intel-download:hover{border-color:var(--accent)}.intel-metrics{display:grid;grid-template-columns:1.25fr repeat(5,1fr);gap:12px;margin-bottom:22px}.intel-metric{padding:19px 17px 16px;border:1px solid var(--line);border-radius:6px;background:linear-gradient(145deg,#ffffff04,transparent);display:flex;flex-direction:column;min-width:0;position:relative}.intel-metric>span{font-size:10px;white-space:nowrap;color:#a7a5a1}.intel-metric strong{font:600 39px/1.4 var(--display);text-align:start;letter-spacing:-.7px;color:#e7e5dd;margin:6px 0 4px;overflow-wrap:anywhere}.intel-metric small{font-size:9px;color:#92978f;line-height:1.8}.featured-metric{background:linear-gradient(135deg,#71313f55,#341d242b);border-color:#c8617450}.featured-metric strong{color:#f4c6cc}.featured-metric:before{content:'';position:absolute;top:-1px;inset-inline:16px;height:2px;background:#d95d70}.positive{color:var(--positive)}.negative{color:var(--negative)}.intel-analysis-grid{display:grid;grid-template-columns:1.25fr 1fr;gap:20px;margin-bottom:20px}.intel-panel{padding:25px;border:1px solid var(--line);border-radius:7px;background:#17191970;min-width:0}.panel-heading{display:flex;justify-content:space-between;align-items:center;gap:15px;margin-bottom:24px}.panel-heading .eyebrow{font-size:8px;color:#a5747c;margin-bottom:10px;letter-spacing:1.7px}.panel-heading h3{font:500 27px/1.25 var(--display);margin:0}.panel-heading p:not(.eyebrow){font-size:10px;color:#8e9693;margin:7px 0 0}.panel-heading select{font-size:10px;min-height:36px;max-width:155px;padding:7px}.chart-key{display:flex;align-items:center;gap:6px;white-space:nowrap;color:#9d9b95;font-size:8px}.chart-key i{width:6px;height:6px;background:#d65c6d}.fame-chart{display:flex;direction:ltr;gap:15px;align-items:stretch;padding-top:15px}.chart-scale{display:flex;flex-direction:column;justify-content:space-between;font-size:9px;color:#858c89;padding:0 0 32px;min-width:30px}.fame-chart svg{width:100%;height:210px;overflow:visible}.fame-bar:hover,.fame-bar:focus{fill:#ffd1d8;outline:none}.composition-body{display:flex;align-items:center;gap:25px;min-height:210px}.role-donut{flex-shrink:0;width:164px;aspect-ratio:1;border-radius:50%;position:relative;display:grid;place-items:center;transform:rotate(-90deg)}.role-donut>div{transform:rotate(90deg);position:absolute;inset:16px;background:#161818;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-direction:column}.role-donut strong{font:500 37px/1.2 var(--display)}.role-donut span{font-size:8px;max-width:85px;text-align:center;color:#969a93;margin-top:7px;line-height:1.7}.role-legend{flex:1;min-width:0}.role-legend>div{display:flex;align-items:center;gap:7px;font-size:10px;padding:6px 0;white-space:nowrap}.role-legend i,.encounter-role-strip i{width:6px;height:6px;background:var(--role);border-radius:2px;flex-shrink:0}.role-legend span{color:#b9b9b0}.role-legend b{margin-inline-start:auto;font-weight:500}.role-legend small{font-size:9px;color:#8b938e;min-width:36px;text-align:end}.intel-detail-grid{display:grid;grid-template-columns:1fr 1.25fr;gap:20px;margin-bottom:40px}.weapon-row{display:flex;align-items:center;gap:10px;padding:9px 0;border-bottom:1px solid #ffffff08}.weapon-row:last-child{border:0}.weapon-row>img{flex-shrink:0;background:#ffffff03;border-radius:4px}.weapon-row>div{flex:1;min-width:0}.weapon-label{display:flex;justify-content:space-between;align-items:center;gap:10px;font-size:11px;line-height:1.5}.weapon-label strong{font-size:11px;font-weight:500;color:#d5c4c0}.weapon-track{height:3px;background:#ffffff0b;border-radius:5px;margin:6px 0 2px;overflow:hidden}.weapon-track i{display:block;background:var(--role);height:100%;border-radius:5px}.weapon-row small{font-size:8px;color:#949790}.intel-table-wrap{overflow-x:auto}.intel-table{width:100%;border-collapse:collapse;font-size:11px;text-align:start}.intel-table th{text-align:start;font-weight:400;font-size:9px;color:#92998f;border-block:1px solid var(--line);padding:12px 6px}.intel-table td{padding:12px 6px;border-bottom:1px solid #ffffff09}.intel-table td:first-child{color:#8d686d;font:400 15px var(--display);width:32px}.intel-table td:nth-child(2){font-weight:500}.intel-table td:nth-child(2) small{display:block;font-size:8px;color:#8c938b;font-weight:400}.intel-table td:nth-child(3){color:#e1bbb9}.intel-table td:last-child{white-space:nowrap;text-align:end}.intel-ledger>.panel-heading{margin-bottom:22px}.intel-ledger>.panel-heading h3{font-size:35px}.ledger-count{font:400 45px var(--display);color:#665155}.ledger-controls{display:flex;gap:12px;margin-bottom:15px}.ledger-controls input{flex:1;min-width:0;font-size:11px}.ledger-controls select{min-width:160px}.encounter{border:1px solid var(--line);border-radius:6px;margin-bottom:10px;background:#17191970;overflow:hidden}.encounter>summary{padding:20px;display:grid;grid-template-columns:85px 1fr 110px 70px 100px 20px;gap:22px;align-items:center;cursor:pointer;list-style:none}.encounter>summary::-webkit-details-marker{display:none}.encounter>summary:hover{background:#ffffff03}.encounter-date{border-inline-end:1px solid var(--line);align-self:stretch;display:flex;justify-content:center;flex-direction:column}.encounter-date strong{font-size:12px;font-weight:500}.encounter-date small{font-size:9px;color:#92978d;display:block;margin-top:4px}.encounter-name{min-width:0}.encounter-type{font-size:8px;color:#92958c;display:inline-flex;gap:5px;line-height:1.4;align-items:center}.encounter-type:before{content:'';width:4px;height:4px;border:1px solid #8d938b;transform:rotate(45deg);display:inline-block}.encounter-type.is-merged{color:#d88d9b}.encounter-type.is-merged:before{border-color:#d88d9b}.encounter-name h4{font-size:13px;margin:4px 0 1px;line-height:1.6;font-weight:500;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}.encounter-name>small{font-size:8px;color:#818b84}.encounter-stat strong{display:block;font:500 25px/1.4 var(--display);white-space:nowrap}.encounter-stat small{font-size:8px;color:#94968c}.encounter-expand{font-size:23px;color:#b57984;transition:transform .2s}.encounter[open] .encounter-expand{transform:rotate(45deg)}.encounter-body{border-top:1px solid var(--line);padding:20px;background:#10121265}.encounter-detail-top{display:flex;justify-content:space-between;gap:20px;font-size:10px;color:#a69a96;margin-bottom:18px}.encounter-detail-top a{color:#e4a2ab}.encounter-role-strip{display:flex;flex-wrap:wrap;gap:10px 22px;margin-bottom:16px}.encounter-role-strip>span{display:flex;align-items:center;gap:7px;font-size:10px;color:#b3b5a9}.encounter-role-strip b{font-weight:500;color:#e6e0d2}.encounter-weapons{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:0 25px}.encounter-ids{display:flex;flex-wrap:wrap;gap:6px;margin-top:18px;direction:ltr}.encounter-ids a{font-size:9px;border:1px solid var(--line);padding:3px 7px;color:#aeaaa1;border-radius:3px}.intel-more{background:#ffffff04;border:1px solid var(--line);padding:14px;width:100%;font-size:12px;color:#d6b6ba;border-radius:4px}.list-empty{padding:25px;font-size:12px;color:var(--muted);text-align:center} +[dir=rtl] .intel-hero h1{font-family:'Vazirmatn',sans-serif;font-size:clamp(39px,4.3vw,60px);font-weight:800;line-height:1.65;letter-spacing:-2px}[dir=rtl] .intel-hero{padding-block:44px 55px}[dir=rtl] .intel-hero .eyebrow{margin-bottom:8px}[dir=rtl] .intel-source{letter-spacing:0}[dir=rtl] .intel-result-heading h2{font-size:43px;font-family:'Barlow Condensed','Vazirmatn',sans-serif}[dir=rtl] .intel-empty h2{font-family:'Vazirmatn',sans-serif;font-size:26px;line-height:1.9}[dir=rtl] .panel-heading h3{font-family:'Vazirmatn',sans-serif;font-size:19px;line-height:1.8}[dir=rtl] .intel-ledger>.panel-heading h3{font-size:24px}[dir=rtl] .intel-metric strong{text-align:end}[dir=rtl] .intel-header .brand{direction:ltr}[dir=rtl] .intel-metric>span{font-size:10px}[dir=rtl] .intel-status,[dir=rtl] .intel-control-bottom p{font-size:10px;line-height:2} +@keyframes intel-pulse{50%{opacity:.35;box-shadow:0 0 15px #e3485077}}@media(prefers-reduced-motion:reduce){.intel-page *{animation:none!important;transition:none!important}} +@media(min-width:1400px){.intel-main{padding-inline:0}.intel-header{padding-inline:3%}} +@media(max-width:1080px){.intel-metrics{grid-template-columns:repeat(3,1fr)}.intel-analysis-grid{grid-template-columns:1fr 1fr}.intel-controls form{grid-template-columns:1.3fr 1fr 1fr}.intel-submit{grid-column:1/-1;justify-content:center}.intel-controls form{gap:18px}.intel-control-bottom{margin-top:-3px}.composition-body{gap:15px;flex-direction:column}.role-legend{width:100%}.role-legend>div{padding-block:5px}.fame-chart svg{height:300px}.intel-signal{inset-inline-end:0;width:240px;height:240px}.intel-intro{max-width:60%}.encounter>summary{grid-template-columns:75px 1fr 90px 60px 75px 15px;gap:15px}.intel-detail-grid{grid-template-columns:1fr 1.1fr}} +@media(max-width:760px){.intel-header{padding:18px 5%;gap:15px}.intel-header .brand img{width:35px;height:35px}.intel-header .brand{gap:8px}.intel-back{font-size:10px}.intel-header .languages{font-size:10px}.intel-main{padding-inline:5%;padding-bottom:35px}.intel-hero{padding:37px 0 55px;min-height:0}.intel-hero h1{font-size:55px}.intel-intro{max-width:100%;font-size:12px}.intel-signal{display:none}.intel-source{position:static;margin-top:22px;font-size:7px}.intel-controls{padding:20px 18px 0}.intel-controls form{grid-template-columns:1fr 1fr;gap:18px 12px}.intel-search{grid-column:1/-1}.intel-controls label,.intel-controls legend{font-size:10px}.minimum-field input{height:46px}.intel-submit{font-size:12px}.intel-control-bottom{flex-direction:column;align-items:flex-start;gap:12px;padding-block:16px}.intel-control-bottom p{border:0;padding:0;font-size:10px}.intel-status{min-height:65px;font-size:9px}.intel-empty{padding:37px 20px}.intel-empty h2{font-size:29px}.intel-empty>p:not(.eyebrow){font-size:11px}.intel-steps{gap:14px;flex-wrap:wrap}.intel-steps span{font-size:9px}.intel-result-heading h2{font-size:36px}.intel-result-heading{align-items:flex-start;margin-top:12px}.intel-download{font-size:9px;padding:7px 9px}.intel-result-heading p:not(.eyebrow){font-size:10px}.intel-metrics{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.intel-metric{padding:16px}.intel-metric strong{font-size:36px}.intel-analysis-grid,.intel-detail-grid{grid-template-columns:1fr;gap:16px}.intel-panel{padding:20px}.composition-body{flex-direction:row;gap:24px;min-height:190px}.role-donut{width:145px}.role-donut>div{inset:14px}.role-legend>div{font-size:10px}.role-legend small{font-size:8px;min-width:30px}.fame-chart svg{height:190px}.chart-scale{padding-bottom:25px}.chart-key{font-size:7px}.panel-heading h3{font-size:26px}.intel-footer{padding:20px 5%;flex-wrap:wrap;gap:8px 18px}.intel-footer p{flex-basis:100%;order:3;font-size:9px}.intel-footer a{margin-inline-start:auto}.encounter>summary{grid-template-columns:65px 1fr 85px 18px;gap:12px;padding:16px}.encounter-stat:not(.encounter-kd){grid-row:2}.encounter-stat:nth-child(3){grid-column:2}.encounter-stat:nth-child(4){grid-column:3}.encounter-kd{grid-column:3;grid-row:1;text-align:end}.encounter-expand{grid-column:4;grid-row:1}.encounter-date{grid-row:1/3}.encounter-name{grid-column:2;grid-row:1}.encounter-name h4{font-size:11px}.encounter-stat strong{font-size:23px}.encounter-stat small{font-size:8px}.encounter-type{font-size:7px}.encounter-weapons{grid-template-columns:repeat(2,minmax(0,1fr));gap:0 16px}.encounter-body{padding:16px}.ledger-controls select{min-width:120px;font-size:10px}.ledger-controls input{font-size:10px}.intel-detail-grid{margin-bottom:30px}[dir=rtl] .intel-hero h1{font-size:39px;letter-spacing:-1.5px;line-height:1.65}[dir=rtl] .intel-hero{padding-block:30px 35px}[dir=rtl] .intel-empty h2{font-size:22px}[dir=rtl] .panel-heading h3{font-size:18px}} +@media(max-width:390px){.intel-back{display:none}.intel-controls form{grid-template-columns:1fr}.period-field,.minimum-field{grid-column:1/-1}.composition-body{gap:15px}.role-donut{width:120px}.role-donut>div{inset:12px}.role-donut strong{font-size:30px}.role-donut span{font-size:7px}.role-legend>div{font-size:9px}.intel-metric>span{font-size:9px}.intel-download{max-width:90px}.encounter-weapons{grid-template-columns:1fr}} + +/* Keep branding anchored in both writing directions and numerical units together. */ +.intel-header .brand{margin-inline-end:0}.intel-back{margin-inline-start:auto}.intel-metric strong{white-space:nowrap;font-variant-numeric:tabular-nums}.intel-table td:nth-child(3){white-space:nowrap}.encounter-stat strong{unicode-bidi:plaintext}.encounter-detail-top{flex-wrap:wrap}@media(max-width:390px){.intel-header .languages{margin-inline-start:auto}} diff --git a/src/intel.js b/src/intel.js new file mode 100644 index 0000000..5312dae --- /dev/null +++ b/src/intel.js @@ -0,0 +1,249 @@ +import { ROLES, normalizeName, ownGuild, groupReports, selectBattles, makeReport, summarize, mapLimit, scanListings } from './intel-core.js'; +import { textFor } from './intel-text.js'; + +const fa = document.documentElement.lang === 'fa', t = textFor(fa ? 'fa' : 'en'); +const locale = fa ? 'fa-IR' : 'en-GB', form = document.querySelector('#intel-form'); +const results = document.querySelector('#intel-results'), empty = document.querySelector('#intel-empty'); +const errorBox = document.querySelector('#intel-error'), status = document.querySelector('#intel-status'); +const cancel = document.querySelector('#intel-cancel'), cache = new Map(); +const apiBase = document.body.dataset.apiBase.replace(/\/$/, ''); +const e = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"', "'":''' }[c])); +const number = (value, decimals = 0) => new Intl.NumberFormat(locale, { maximumFractionDigits: decimals }).format(value); +const compact = value => { + const unit = value >= 1e9 ? [1e9,'B'] : value >= 1e6 ? [1e6,'M'] : value >= 1e3 ? [1e3,'K'] : [1,'']; + return `${number(value / unit[0], unit[0] === 1 ? 0 : 1)}${unit[1]}`; +}; +const full = value => new Intl.NumberFormat(locale).format(value); +const date = value => new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', timeZone: 'UTC' }).format(new Date(value)); +const clock = value => new Intl.DateTimeFormat('en-GB', { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' }).format(new Date(value)); +const roleLabel = role => t[`${role}s`] || t.unknowns; +const roleColor = { tank:'#d5a65c', healer:'#6ac5a3', support:'#9d8de2', range:'#71a8d8', melee:'#ed727c', battlemount:'#b8b6a7', unknown:'#646c73' }; +let controller, generation = 0, loaded, forcedGuild; + +class ReportError extends Error {} +async function api(path, query = {}, signal) { + const url = `${apiBase}${path}${Object.keys(query).length ? `?${new URLSearchParams(query)}` : ''}`; + const cached = cache.get(url); + if (cached && Date.now() - cached.at < 120_000) return cached.data; + for (let attempt = 0; attempt < 3; attempt++) { + signal?.throwIfAborted(); + let response; + try { + response = await fetch(url, { signal: AbortSignal.any([signal || new AbortController().signal, AbortSignal.timeout(35_000)]), headers: { Accept:'application/json' } }); + if (response.status === 404 || !response.headers.get('content-type')?.includes('application/json')) throw new ReportError(t.proxyError); + if (!response.ok) throw Error(`HTTP ${response.status}`); + const data = await response.json(); + cache.set(url, { at:Date.now(), data }); + if (cache.size > 2500) cache.delete(cache.keys().next().value); + return data; + } catch (error) { + if (signal?.aborted || error instanceof ReportError || attempt === 2) throw error; + await new Promise((resolve, reject) => { + const done = () => { signal?.removeEventListener('abort', abort); resolve(); }; + const timer = setTimeout(done, 700 * (attempt + 1)); + const abort = () => { clearTimeout(timer); reject(signal.reason); }; + signal?.addEventListener('abort', abort, { once:true }); + }); + } + } +} +function progress(message, run) { + if (run !== generation) return; + document.querySelector('#status-text').textContent = message; +} +function saveQuery(config) { + const query = new URLSearchParams({ guild:config.name, days:config.days, minimum:config.minimum, merge:config.merge ? '1' : '0' }); + history.replaceState(null, '', `${location.pathname}?${query}`); + document.querySelectorAll('[data-intel-language]').forEach(a => { a.search = query.toString(); }); +} +function showError(message) { + errorBox.hidden = false; + document.querySelector('#error-text').textContent = message; +} +async function analyze(event) { + event?.preventDefault(); + if (!form.reportValidity()) return; + controller?.abort(); + const run = ++generation; + controller = new AbortController(); + const { signal } = controller; + const config = { name:form.elements.guild.value.trim(), days:Number(form.elements.days.value), minimum:Number(form.elements.minimum.value), merge:form.elements.merge.checked }; + saveQuery(config); + results.hidden = true; empty.hidden = true; errorBox.hidden = true; + document.querySelector('#guild-choices').replaceChildren(); + form.querySelector('[type=submit]').disabled = true; + cancel.hidden = false; status.classList.add('is-loading'); + results.setAttribute('aria-busy','true'); + progress(t.finding, run); + try { + const candidates = await api('/guilds/search', { search:config.name }, signal); + if (!Array.isArray(candidates)) throw Error('Invalid guild search'); + const exact = candidates.filter(g => normalizeName(g.Name) === normalizeName(config.name)); + if (!exact.length) throw new ReportError(t.notFound); + if (forcedGuild && !exact.some(g => g.Id === forcedGuild)) forcedGuild = undefined; + if (exact.length > 1 && !forcedGuild) { + showError(t.ambiguous); + document.querySelector('#intel-retry').hidden = true; + const choices = document.querySelector('#guild-choices'); + for (const guild of exact) { + const button = document.createElement('button'); + button.className = 'guild-choice'; button.type = 'button'; button.textContent = `${guild.Name} · ${guild.Id}`; + button.addEventListener('click', () => { forcedGuild = guild.Id; analyze(); }); choices.append(button); + } + return; + } + const guild = exact.find(g => g.Id === forcedGuild) || exact[0]; + const until = Date.now(), since = until - config.days * 86_400_000; + const listings = await scanListings(api, guild.Id, since, signal, + (page, count) => progress(`${t.scanning} · ${t.page} ${number(page)} · ${number(count)} ${t.battles}`, run), config.minimum); + let count = 0; + const battles = await mapLimit(listings, 4, async row => { + const detail = await api(`/battles/${row.albionId}`, {}, signal); + if (detail.albionId !== row.albionId || !ownGuild(detail, guild.Id) || !Array.isArray(detail.players)) throw new ReportError(t.partial); + progress(`${t.details} · ${number(++count)} / ${number(listings.length)}`, run); + return detail; + }); + const selected = selectBattles(battles, guild.Id, { since, until, minPlayers:config.minimum }); + const groups = groupReports(selected, guild.Id, config.merge); + count = 0; + const reports = await mapLimit(groups, 2, async group => { + const combined = group.length > 1 ? await api('/battles/multi', { ids:group.map(b => b.albionId).join(',') }, signal) : null; + if (combined) { + const guildTotal = ownGuild(combined, guild.Id); + for (const key of ['kills', 'deaths', 'killFame']) { + if (guildTotal?.[key] !== group.reduce((sum, b) => sum + (ownGuild(b, guild.Id)[key] || 0), 0)) throw new ReportError(t.partial); + } + } + progress(`${t.merging} · ${number(++count)} / ${number(groups.length)}`, run); + return makeReport(group, combined, guild.Id); + }); + signal.throwIfAborted(); + if (run !== generation) return; + loaded = { guild, config, reports, since, until, originalCount:selected.length }; + render(loaded); + progress(`${guild.Name} · ${number(reports.length)} ${t.encounters} · ${t.loaded} ${clock(until)} UTC`, run); + } catch (error) { + if (run !== generation) return; + controller.abort(); + const cancelled = error?.name === 'AbortError'; + if (cancelled) { + empty.hidden = false; progress(t.cancelled, run); + } else { + showError(error instanceof ReportError ? error.message : t.error); + progress(t.error, run); + } + } finally { + if (run === generation) { + status.classList.remove('is-loading'); cancel.hidden = true; + form.querySelector('[type=submit]').disabled = false; + results.setAttribute('aria-busy','false'); + if (!document.querySelector('#guild-choices').children.length) document.querySelector('#intel-retry').hidden = false; + } + } +} + +function metric(label, value, foot = '', featured = false, exact) { + return `
${e(label)}${e(value)}${foot}
`; +} +function render(data) { + const { reports, guild, config } = data; + if (!reports.length) { + results.innerHTML = `

${e(guild.Name)} / ${config.days} ${e(t.days)}

${e(t.emptyTitle)}

${e(t.emptyCopy)}

`; + results.hidden = false; return; + } + const s = summarize(reports); + const roleTotal = Object.values(s.roles).reduce((sum, n) => sum + n, 0); + const delta = s.killFame - s.deathFame; + results.innerHTML = ` +

${e(t.overview)}

${e(guild.Name)}EU

${e(date(data.since))} — ${e(date(data.until))} · ${number(config.days)} ${e(t.days)} · ${number(config.minimum)}+ ${e(t.totalPlayers)}
${e(t.filtered)}

+
+ ${metric(t.killFame, compact(s.killFame), `${e(t.netFame)} ${delta >= 0 ? '+' : '−'}${e(compact(Math.abs(delta)))}`, true, s.killFame)} + ${metric(t.encounters, number(reports.length), `${number(data.originalCount)} ${e(t.original)}`)} + ${metric(t.kd, s.deaths ? number(s.kills/s.deaths, 2) : s.kills ? '∞' : '—', `${number(s.kills)} ${e(t.kills)} / ${number(s.deaths)} ${e(t.deaths)}`)} + ${metric(t.attendance, number(s.averageAttendance, 1), `${number(s.players.size)} ${e(t.unique)}`)} + ${metric(t.deathFame, compact(s.deathFame), `${number(s.deaths)} ${e(t.deaths)}`, false, s.deathFame)} + ${metric(t.avgIp, s.averageIp ? number(s.averageIp) : '—', `${number(s.ipCount)} ${e(t.appearances)}`)} +
+

01 / MOMENTUM

${e(t.trend)}

${e(t.trendHint)}

${e(t.killFame)}
${trend(s, data)}
+

02 / COMPOSITION

${e(t.composition)}

${e(t.compositionHint)}

${donut(s.roles)}
${ROLES.filter(r => s.roles[r]).map(r => `
${e(roleLabel(r))}${number(s.roles[r])}${number(s.roles[r]/roleTotal*100,1)}%
`).join('')}
+

03 / ARSENAL

${e(t.weapons)}

${e(t.weaponHint)}

+

04 / PEOPLE

${e(t.leaderboard)}

+

05 / ENCOUNTERS

${e(t.ledger)}

${e(t.ledgerHint)}

${number(reports.length)}
+
`; + results.hidden = false; + const weaponSelect = document.querySelector('#weapon-role'), playerSelect = document.querySelector('#player-sort'); + const updateWeapons = () => { document.querySelector('#weapons-list').innerHTML = weaponList([...s.weapons.values()], weaponSelect.value); }; + weaponSelect.addEventListener('change', updateWeapons); updateWeapons(); + const updatePlayers = () => { document.querySelector('#player-list').innerHTML = playersTable([...s.players.values()], playerSelect.value); }; + playerSelect.addEventListener('change', updatePlayers); updatePlayers(); + let visible = 20; + const updateBattles = () => { + const search = normalizeName(document.querySelector('#battle-search').value); + const sort = document.querySelector('#battle-sort').value; + const filtered = reports.filter(r => !search || r.ids.some(id => String(id).includes(search)) || r.battle.guilds.some(g => normalizeName(g.name).includes(search))); + filtered.sort((a,b) => sort === 'fame' ? b.guild.killFame - a.guild.killFame : sort === 'players' ? b.guild.players - a.guild.players : Date.parse(b.startedAt) - Date.parse(a.startedAt)); + document.querySelector('#battle-list').innerHTML = filtered.length ? filtered.slice(0,visible).map(r => battleRow(r, guild.Id)).join('') : `

${e(t.noMatch)}

`; + document.querySelector('#more-battles').hidden = visible >= filtered.length; + }; + for (const id of ['battle-search','battle-sort']) document.querySelector(`#${id}`).addEventListener(id === 'battle-search' ? 'input' : 'change', () => { visible = 20; updateBattles(); }); + document.querySelector('#more-battles').addEventListener('click', () => { visible += 20; updateBattles(); }); updateBattles(); + document.querySelector('#export-csv').addEventListener('click', exportCsv); +} +function trend(s, data) { + const dates = []; + for (let day = Date.parse(new Date(data.since).toISOString().slice(0,10)); day <= data.until; day += 86_400_000) dates.push(new Date(day).toISOString().slice(0,10)); + const max = Math.max(...s.daily.values(), 1), width = 800, height = 195, gap = 3, unit = width / dates.length; + return `
${e(compact(max))}${e(compact(max/2))}0
${[0,.5,1].map(f => ``).join('')}${dates.map((day,i) => { + const value = s.daily.get(day) || 0, h = value / max * (height-12); + return `${e(date(day))} · ${e(full(value))} ${e(t.killFame)}`; + }).join('')}${e(date(dates[0]))}${e(date(dates.at(-1)))}
`; +} +function donut(roles) { + const total = Object.values(roles).reduce((n,v) => n+v,0); let start = 0; + const stops = ROLES.filter(r => roles[r]).map(r => { const end = start + roles[r]/total*100; const stop = `${roleColor[r]} ${start}% ${end}%`; start = end; return stop; }); + return ``; +} +const weaponNames = { + '2H_MACE':'Heavy Mace', 'MAIN_MACE':'Mace', 'MAIN_MACE_CRYSTAL':'Dreadstorm Monarch', '2H_MACE_MORGANA':'Camlann Mace', '2H_DUALMACE_AVALON':'Oathkeepers', + 'MAIN_HAMMER':'Hammer', '2H_HAMMER':'Great Hammer', '2H_HAMMER_UNDEAD':'Tombhammer', '2H_HAMMER_AVALON':'Hand of Justice', + 'MAIN_NATURESTAFF':'Nature Staff', '2H_NATURESTAFF':'Great Nature Staff', '2H_NATURESTAFF_HELL':'Blight Staff', 'MAIN_NATURESTAFF_AVALON':'Ironroot Staff', + 'MAIN_HOLYSTAFF':'Holy Staff', 'MAIN_HOLYSTAFF_AVALON':'Hallowfall', '2H_HOLYSTAFF':'Great Holy Staff', '2H_HOLYSTAFF_HELL':'Fallen Staff', + '2H_LONGBOW':'Longbow', '2H_BOW_AVALON':'Mistpiercer', '2H_CROSSBOW_CANNON_AVALON':'Energy Shaper', 'MAIN_DAGGER_HELL':'Demonfang', + '2H_DUALSCIMITAR_UNDEAD':'Galatine Pair', '2H_FIRE_RINGPAIR_AVALON':'Dawnsong', '2H_HALBERD':'Halberd', '2H_AXE_AVALON':'Realmbreaker', + '2H_KNUCKLES_SET3':'Spiked Gauntlets', '2H_KNUCKLES_HELL':'Hellfire Hands', '2H_SHAPESHIFTER_KEEPER':'Primal Staff', '2H_SHAPESHIFTER_AVALON':'Lightcaller', + '2H_ENIGMATICSTAFF':'Enigmatic Staff', '2H_ARCANESTAFF_HELL':'Occult Staff', '2H_ARCANESTAFF':'Great Arcane Staff', 'MAIN_ARCANESTAFF':'Arcane Staff', +}; +function weaponName(name) { return weaponNames[name] || name.replace(/^T\d+_/, '').replace(/^(MAIN_|2H_|MOUNT_)/, '').replaceAll('_',' ').toLowerCase().replace(/\b\w/g, c => c.toUpperCase()); } +function weaponList(weapons, role = 'all', limit = 12) { + const items = weapons.filter(w => role === 'all' || w.role === role).sort((a,b) => b.count-a.count).slice(0,limit); + const max = Math.max(...items.map(w => w.count),1); + return items.length ? items.map(w => `
${e(weaponName(w.name))}${number(w.count)}
${e(roleLabel(w.role))}
`).join('') : `

${e(t.noWeapons)}

`; +} +function playersTable(players, sort = 'killFame') { + const metricLabel = sort === 'attendance' ? t.presence : t[sort]; + return `${players.sort((a,b) => b[sort]-a[sort] || a.name.localeCompare(b.name)).slice(0,10).map((p,i) => ``).join('')}
#${e(t.name)}${e(metricLabel)}${e(t.kills)} / ${e(t.deaths)}
${new Intl.NumberFormat(locale,{minimumIntegerDigits:2}).format(i+1)}${e(p.name)}${number(p.attendance)} ${e(t.encounters)}${e(['attendance','kills'].includes(sort) ? number(p[sort]) : compact(p[sort]))}${number(p.kills)} / ${number(p.deaths)}
`; +} +function battleRow(report, guildId) { + const other = report.battle.guilds.filter(g => g.albionId !== guildId).sort((a,b) => b.players-a.players); + const opponents = other.slice(0,3).map(g => g.name).join(' / '); + const s = summarize([report]); + return `
${e(date(report.startedAt))}${clock(report.startedAt)} UTC
${report.ids.length > 1 ? `${number(report.ids.length)} ${e(t.merged)}` : e(t.single)}

${e(opponents || '—')}

${e(t.otherGuilds)}
${e(compact(report.guild.killFame))}${e(t.killFame)}
${number(report.guild.players)}${e(t.guildPlayers)}
${number(report.guild.kills)} / ${number(report.guild.deaths)}${e(t.kills)} / ${e(t.deaths)}
${clock(report.startedAt)} — ${clock(report.finishedAt)} UTC${number(report.battle.totalPlayers)} ${e(t.totalPlayers)}${e(t.report)} ↗
${ROLES.filter(r => s.roles[r]).map(r => `${e(roleLabel(r))}${number(s.roles[r])}`).join('')}
${weaponList([...s.weapons.values()], 'all', 100)}
${report.ids.map(id => `#${id} ↗`).join('')}
`; +} +function exportCsv() { + if (!loaded) return; + const escape = value => `"${String(value ?? '').replace(/^[=+@\-\t\r]/, "'$&").replaceAll('"','""')}"`; + const rows = [['Guild','Start UTC','End UTC','Battle IDs','Guild members','Kills','Deaths','Kill fame','Death fame','Report'], ...loaded.reports.map(r => [loaded.guild.Name,r.startedAt,r.finishedAt,r.ids.join(','),r.guild.players,r.guild.kills,r.guild.deaths,r.guild.killFame,r.players.reduce((sum,p) => sum+(p.deathFame||0),0),r.url])]; + const blob = new Blob(['\uFEFF', rows.map(row => row.map(escape).join(',')).join('\r\n')], { type:'text/csv;charset=utf-8' }); + const url = URL.createObjectURL(blob), a = document.createElement('a'); + a.href = url; a.download = `guild-intelligence-${loaded.config.days}d.csv`; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); +} +form.addEventListener('submit', analyze); +cancel.addEventListener('click', () => controller?.abort()); +document.querySelector('#intel-retry').addEventListener('click', () => analyze()); +const query = new URLSearchParams(location.search); +form.elements.guild.value = query.get('guild') || ''; +if (['7','30','60'].includes(query.get('days'))) form.elements.days.value = query.get('days'); +if (/^\d+$/.test(query.get('minimum') || '') && Number(query.get('minimum')) >= 1 && Number(query.get('minimum')) <= 1000) form.elements.minimum.value = query.get('minimum'); +if (query.get('merge') === '0') form.elements.merge.checked = false; +document.querySelectorAll('[data-intel-language]').forEach(a => { a.search = query.toString(); }); +if (form.elements.guild.value) analyze(); diff --git a/test/intel.test.mjs b/test/intel.test.mjs new file mode 100644 index 0000000..c1551b7 --- /dev/null +++ b/test/intel.test.mjs @@ -0,0 +1,100 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { selectBattles, groupReports, makeReport, summarize, scanListings, mapLimit, normalizeName } from '../src/intel-core.js'; +import { proxyAlbion, upstreamUrl } from '../scripts/albion-proxy.mjs'; +import { renderIntel } from '../scripts/render-intel.mjs'; + +const battle = (id, minute = 0, options = {}) => ({ + albionId:id, startedAt:new Date(Date.UTC(2026,9,20,10,minute)).toISOString(), finishedAt:new Date(Date.UTC(2026,9,20,10,minute+2)).toISOString(), + totalPlayers:options.total ?? 40, + guilds:[{ albionId:'guild', name:'OneUP', players:4, kills:2, deaths:1, killFame:1000 }, { albionId:options.enemy || 'enemy', name:'Enemy', players:36 }], + players:['a','b','c','d'].map(name => ({ name,guildName:'OneUP',role:'healer',kills:0,deaths:0,killFame:250,deathFame:50,ip:1500,weapon:{name:'MAIN_HOLYSTAFF',type:'T6_MAIN_HOLYSTAFF'} })), +}); +test('minimum attendance is ALL players, inclusive, and applied before merging', () => { + const rows = [battle(1,0,{total:39}),battle(2,1,{total:40}),battle(3,2,{total:41})]; + const chosen = selectBattles(rows,'guild',{since:Date.UTC(2026,9,20),until:Date.UTC(2026,9,21),minPlayers:40}); + assert.deepEqual(chosen.map(b => b.albionId),[2,3]); + assert.equal(chosen[0].guilds[0].players,4); + assert.deepEqual(groupReports(chosen,'guild')[0].map(b=>b.albionId),[2,3]); +}); +test('rolling date boundaries include the exact start and exclude older or future records', () => { + const row = battle(1), since = Date.parse(row.startedAt), until = since+1000; + const before = {...row,albionId:2,startedAt:new Date(since-1).toISOString()}; + const future = {...row,albionId:3,startedAt:new Date(until+1).toISOString()}; + assert.deepEqual(selectBattles([before,row,future],'guild',{since,until,minPlayers:1}),[row]); +}); +test('merge requires time, roster AND other-team continuity and supports disabled merging', () => { + const a=battle(1),b=battle(2,10),c=battle(3,15,{enemy:'unrelated'}),d=battle(4,40); + assert.deepEqual(groupReports([d,b,c,a,a],'guild').map(g=>g.map(b=>b.albionId)),[[1,2],[3],[4]]); + assert.equal(groupReports([a,b],'guild',false).length,2); + b.players=b.players.map(p=>({...p,name:`other-${p.name}`})); + assert.equal(groupReports([a,b],'guild').length,2); +}); +test('summary uses merged roster once, maintains exact fame and recovers end time from originals', () => { + const a=battle(1),b=battle(2,10),combined=battle(1); + combined.finishedAt=a.finishedAt; + combined.guilds[0]={...combined.guilds[0],kills:4,deaths:2,killFame:2000}; + const report=makeReport([a,b],combined,'guild'); + assert.equal(report.finishedAt,b.finishedAt); + assert.match(report.url,/multi\?ids=1,2/); + const s=summarize([report]); + assert.equal(s.roles.healer,4);assert.equal(s.killFame,2000);assert.equal(s.deathFame,200); + assert.equal(s.averageAttendance,4);assert.equal(s.averageIp,1500);assert.equal(s.players.size,4); + assert.equal([...s.weapons.values()][0].count,4); + combined.players[0].ip=0; + assert.equal(summarize([report]).averageIp,1500); +}); +test('scan paginates through a date boundary and sends total-player filter to API', async () => { + const recent=Array.from({length:20},(_,i)=>battle(i+1,i)); + const old={...battle(21),startedAt:'2026-01-01T00:00:00Z'}; + const calls=[]; + const rows=await scanListings(async(path,query)=>{ + calls.push(query);assert.equal(path,'/battles');assert.equal(query.minPlayers,40);assert.equal(query.minGuildPlayers,1); + return query.page===1?recent:[old]; + },'guild',Date.UTC(2026,9,19),undefined,()=>{},40); + assert.equal(calls.length,2);assert.equal(rows.length,20); + await assert.rejects(scanListings(async()=>recent,'guild',0),/Pagination stopped advancing/); +}); +test('battle-mount composition counts the mount instead of the rider weapon', () => { + const b=battle(1); + b.players[0]={...b.players[0],role:'battlemount',mount:'T8_MOUNT_MAMMOTH_BATTLE'}; + const s=summarize([makeReport([b],null,'guild')]); + assert.equal(s.roles.battlemount,1); + assert.equal(s.weapons.get('battlemount:T8_MOUNT_MAMMOTH_BATTLE').count,1); + assert.equal(s.weapons.get('healer:MAIN_HOLYSTAFF').count,3); +}); +test('bounded concurrency preserves order and propagates failures', async () => { + let active=0,peak=0; + const out=await mapLimit([1,2,3,4,5],2,async n=>{ + peak=Math.max(peak,++active);await new Promise(resolve=>setTimeout(resolve,5));active--;return n*2; + }); + assert.deepEqual(out,[2,4,6,8,10]);assert.equal(peak,2); + await assert.rejects(mapLimit([1,2],1,async()=>{throw Error('failed report');}),/failed report/); +}); +test('proxy only permits public whitelisted read endpoints and strips browser headers', async () => { + assert.throws(()=>upstreamUrl('https://oneup.test/api/albion/https://evil.test')); + assert.throws(()=>upstreamUrl('https://oneup.test/api/albion/battles?url=https://evil.test')); + assert.throws(()=>upstreamUrl('https://oneup.test/api/albion/battles/multi?ids=1,evil')); + assert.equal(upstreamUrl('https://oneup.test/api/albion/guilds/search?search=OneUP').hostname,'api.albionbb.com'); + const request=new Request('https://oneup.test/api/albion/battles/123',{headers:{Authorization:'private',Cookie:'private'}}); + const result=await proxyAlbion(request,async(url,options)=>{ + assert.equal(url.href,'https://api.albionbb.com/eu/battles/123'); + assert.deepEqual(options.headers,{Accept:'application/json'}); + return Response.json({albionId:123}); + }); + assert.deepEqual(await result.json(),{albionId:123}); + assert.equal((await proxyAlbion(new Request(request.url,{method:'POST'}))).status,405); + assert.equal((await proxyAlbion(request,async()=>new Response('',{status:429}))).status,429); +}); +test('bilingual page has accessible filters, correct total-player copy and escaped configuration', () => { + assert.equal(normalizeName(' OneUP '),'oneup'); + for(const lang of ['en','fa']){ + const html=renderIntel(lang,'https://oneup.test','/api/albion'); + assert.match(html,new RegExp(``)); + assert.match(html,/value="7" checked/);assert.match(html,/value="30"/);assert.match(html,/value="60"/); + assert.match(html,/aria-live="polite"/);assert.match(html,/id="min-help"/); + assert.ok(!html.includes('undefined')); + } + assert.match(renderIntel('en','https://oneup.test'),/All guilds combined, before merging/); + assert.match(renderIntel('fa','https://oneup.test'),/مجموع بازیکنان همهٔ گیلدها/); +}); diff --git a/worker.mjs b/worker.mjs new file mode 100644 index 0000000..d55933a --- /dev/null +++ b/worker.mjs @@ -0,0 +1,20 @@ +import { proxyAlbion } from './scripts/albion-proxy.mjs'; + +export default { + async fetch(request, env) { + const url = new URL(request.url); + if (url.pathname.startsWith('/api/albion/')) { + // An optional separately hosted API only shares public reports with the configured site. + const origin = request.headers.get('Origin'); + const allowed = !origin || origin === url.origin || origin === env.SITE_ORIGIN; + if (!allowed) return new Response('Forbidden', { status: 403 }); + const response = await proxyAlbion(request); + if (origin && origin === env.SITE_ORIGIN) { + response.headers.set('Access-Control-Allow-Origin', origin); + response.headers.set('Vary', 'Origin'); + } + return response; + } + return env.ASSETS.fetch(request); + }, +}; diff --git a/wrangler.jsonc b/wrangler.jsonc new file mode 100644 index 0000000..bc72462 --- /dev/null +++ b/wrangler.jsonc @@ -0,0 +1,6 @@ +{ + "name": "oneup-guild", + "main": "worker.mjs", + "compatibility_date": "2026-10-20", + "assets": { "directory": "./dist", "binding": "ASSETS", "run_worker_first": ["/api/albion/*"] } +}