import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
const html = readFileSync(new URL('../bot/webapp/static/index.html', import.meta.url), 'utf8');
const lines = html.split(/\r?\n/);
function declaration(prefix) {
const line = lines.find(value => value.startsWith(prefix));
assert.ok(line, `Missing application declaration: ${prefix}`);
return line;
}
function between(start, end) {
const first = html.indexOf(start);
const last = html.indexOf(end, first + start.length);
assert.ok(first >= 0 && last > first, `Missing source block: ${start}`);
return html.slice(first, last);
}
const dailySource = between('/* ---------- Ежедневный кубик:', '/* ---------- Квесты и монеты сообщества');
const rankingSource = between('/* ---------- Рейтинги:', '/* ---------- Нейролаб:');
const questSource = between('function questsView(', 'let questBusy=') + declaration('let questBusy=');
const helpers = [
'const esc=', 'const num=', 'const fmt=', 'const usd=', 'const refreshBtn=',
'const intro=', 'const ECON_PERIODS=', 'const ECON_PERIOD_DETAILS=',
'const usageCount=', 'const usageGrouped=',
].map(declaration).join('\n');
function element(dataset = {}) {
return {
dataset, innerHTML: '', attributes: {}, hidden: false,
setAttribute(name, value) { this.attributes[name] = value; },
querySelector() { return null; },
};
}
function deferred() {
let resolve, reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
}
function envelope(kind, rows = [], period = kind === 'referrals' ? 'all' : 'day') {
return {
kind, period, top: rows,
source: kind === 'referrals' ? 'bot.users.ref_awarded' : kind === 'models' ? 'gateway.logs(type=2).model_name' : 'gateway.logs(type=2)',
from_ts: kind === 'referrals' ? null : 1700000000,
to_ts: 1700086400, as_of: 1700086400, generated_at: 1700086400,
timezone: 'Europe/Moscow',
};
}
function dailyStatus(overrides = {}) {
return {
ok: true, claimed: false, paid: false, pending: false,
face: null, value: null, units: null, usd: null,
eligible: true, wallet: true, rank: 1, multiplier: 1,
streak: 2, day: '2026-10-28', already: false, resumed: false,
legacy: false, error: null, ...overrides,
};
}
function harness(overrides = {}) {
const roots = {
'#top-results': element(), '#top-periods': element(), '#econ-daily': element(),
};
const kinds = ['referrals', 'requests', 'tokens', 'models'].map(topKind => element({ topKind }));
const periods = ['day', 'week', 'month'].map(topPeriod => element({ topPeriod }));
const reads = [], writes = [], haptics = [];
const context = vm.createContext({
current: 'top', version: 1, resolvedUid: 'test-account', cache: new Map(),
$: selector => roots[selector] || null,
icon: () => '',
haptic: value => haptics.push(value),
document: { querySelectorAll: selector => selector === '[data-top-kind]' ? kinds : selector === '[data-top-period]' ? periods : [] },
apiFresh: async path => {
reads.push(path);
if (path === 'bonus') return dailyStatus();
const url = new URL(path, 'https://miniapp.test/');
return envelope(url.searchParams.get('kind'), [], url.searchParams.get('period'));
},
post: async (path, body) => { writes.push({ path, body }); throw new Error('Unexpected mutation'); },
...overrides,
});
vm.runInContext(`${helpers}\n${dailySource}\n${rankingSource}\n${questSource}\n` + `
globalThis.frontend = {
topView, topResults, topMeta, topMetric, topPath, topSelect, topLoad,
dailyView, dailyReceive, dailyClaim, dailyRefresh, dailyStatusValid, questsView,
getDaily: () => dailyState,
setSelection: (kind, period) => { topKind = kind; topPeriod = period; },
getSelection: () => ({ kind: topKind, period: topPeriod }),
};
`, context);
return { context, frontend: context.frontend, roots, kinds, periods, reads, writes, haptics };
}
function claimButton(markup) {
return markup.match(/