import {el, chinaTime, textValue} from './dom.js'; const BUFFER_LIMIT = 1200; const RENDER_LIMIT = 600; const categories = new Set(['general', 'login', 'hatching', 'mainline', 'gifts', 'commissions', 'exploration', 'maps', 'ranch', 'daily']); const pageCategories = {login:'login', daily:'daily', ranch:'ranch', hatching:'hatching', mainline:'mainline', gifts:'gifts', commissions:'commissions', exploration:'exploration', maps:'maps', incubator:'hatching'}; export function createLogState() { return {entries:[], next:0, highWater:0, retainedAfter:0, revision:0, debug:false, loading:false, visible:false, views:new Map()}; } export function logView(log, page) { if (!log.views.has(page)) log.views.set(page, {clearedThrough:0, follow:true, scrollTop:0, search:''}); return log.views.get(page); } const levelOf = entry => String(entry.level || entry.kind || (entry.debug ? 'debug' : 'info')).toLowerCase(); const messageOf = entry => String(entry.message || entry.operation || textValue(entry)); const stampOf = entry => entry.time || entry.timestamp || entry.at || ''; const debugEntry = entry => entry.debug || levelOf(entry) === 'debug'; const lineSignature = (entry, inspect) => JSON.stringify([stampOf(entry), messageOf(entry), levelOf(entry), Boolean(inspect && (entry.details_available || entry.detail_url || entry.debug_url))]); // Each account keeps one bounded history. A cursor rewind for debug must not // reintroduce evicted records or move any tab's local clear watermark. export function mergeLogs(log, entries, next) { const bySequence = new Map(log.entries.map(entry => [entry.seq, entry])); let changed = false; for (const source of entries) { const numeric = Number(source.seq ?? source.id); const seq = Number.isFinite(numeric) ? numeric : log.highWater + 1; if (seq <= log.retainedAfter) continue; const entry = {...source, seq, category:categories.has(source.category) ? source.category : 'general'}; log.highWater = Math.max(log.highWater, seq); if (JSON.stringify(bySequence.get(seq)) !== JSON.stringify(entry)) { bySequence.set(seq, entry); changed = true; } } if (changed) { log.entries = [...bySequence.values()].sort((a, b) => a.seq - b.seq); if (log.entries.length > BUFFER_LIMIT) { const removed = log.entries.splice(0, log.entries.length - BUFFER_LIMIT); log.retainedAfter = Math.max(log.retainedAfter, removed.at(-1).seq); } log.revision++; } log.next = next ?? log.next; log.highWater = Math.max(log.highWater, Number(log.next) || 0); } export function visibleLogs(log, view, page) { const category = Object.hasOwn(pageCategories, page) ? pageCategories[page] : null; return log.entries.filter(entry => entry.seq > view.clearedThrough && (log.debug || !debugEntry(entry)) && entry.category === category && (!view.level || levelOf(entry) === view.level) && (!view.search || messageOf(entry).toLocaleLowerCase().includes(view.search.toLocaleLowerCase()))); } export function logLine(entry, inspect) { const level = levelOf(entry); const line = el('div', {class:`log-entry ${['error','warning','debug'].includes(level) ? level : ''}`, 'data-entry-id':entry.id, 'data-sequence':entry.seq}); line.logSignature = lineSignature(entry, inspect); const stamp = stampOf(entry); line.append(el('span', {class:'log-time', text:chinaTime(stamp), title:String(stamp)}), document.createTextNode(messageOf(entry))); if (inspect && (entry.details_available || entry.detail_url || entry.debug_url)) { line.classList.add('inspectable'); line.tabIndex = 0; line.setAttribute('role', 'button'); line.title = '查看脱敏请求 / 响应 JSON'; line.addEventListener('click', () => inspect(entry)); line.addEventListener('keydown', event => { if (event.key === 'Enter' || event.key === ' ') {event.preventDefault();inspect(entry);} }); } return line; } // Append/remove keyed rows, retaining both row identity and the visible reading // anchor. Only the log's own scroll position changes; ancestors are never scrolled. export function syncLogLines(root, entries, {follow, reset=false, scrollTop, inspect} = {}) { const previousTop = scrollTop ?? root.scrollTop; const top = root.getBoundingClientRect().top; const anchor = follow ? null : [...root.children].find(node => node.getBoundingClientRect().bottom > top); const anchorTop = anchor?.getBoundingClientRect().top; if (reset) root.replaceChildren(); const shown = entries.slice(-RENDER_LIMIT); const wanted = new Set(shown.map(entry => String(entry.seq))); for (const node of [...root.children]) if (!wanted.has(node.dataset.sequence)) node.remove(); const existing = new Map([...root.children].map(node => [node.dataset.sequence, node])); let previous = null; for (const entry of shown) { let node = existing.get(String(entry.seq)); if (node && node.logSignature !== lineSignature(entry, inspect)) { const replacement = logLine(entry, inspect); node.replaceWith(replacement); node = replacement; } if (!node) node = logLine(entry, inspect); const next = previous ? previous.nextElementSibling : root.firstElementChild; if (next !== node) root.insertBefore(node, next); previous = node; } if (follow) root.scrollTop = root.scrollHeight; else if (!reset && anchor?.isConnected) root.scrollTop += anchor.getBoundingClientRect().top - anchorTop; else root.scrollTop = previousTop; } export function logText(entries) { return entries.map(entry => [stampOf(entry), messageOf(entry)].join(' ')).join('\n'); }