Обновить окно ошибки запуска UI

This commit is contained in:
AidarKC
2026-11-16 21:14:05 +03:00
parent d9fdaf1930
commit a86a380dc7
5 changed files with 216 additions and 38 deletions
+106 -36
View File
@@ -39,7 +39,7 @@
}());
</script>
<script>
window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
window.__SHINE_BUILD_HASH__ = '20261116-boot-error-ui-v1';
window.__SHINE_CLIENT_VERSION__ = '1.20.9';
</script>
<script>
@@ -301,8 +301,7 @@ window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
const shell = document.createElement('div');
shell.id = menuId;
shell.className = 'modal-shell boot-error-menu-shell';
// Красная строка BOOT ERROR имеет z-index 999999. Меню ошибки должно
// всегда находиться поверх неё, не меняя слои остальных модальных окон.
// Меню диагностики должно быть над аварийным экраном.
shell.style.zIndex = '1000000';
shell.innerHTML = `
<div class="modal-backdrop" data-action="close"></div>
@@ -368,6 +367,8 @@ window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
if (!ok) {
throw new Error('Не удалось отправить ошибку в лог на сервере');
}
setState({ ...(getState() || {}), sentToServer: true });
updateBootOverlay();
showFeedback('Ошибка отправлена в лог на сервере');
} catch (error) {
showFeedback(error?.message || 'Не удалось отправить ошибку в лог на сервере', 'error');
@@ -393,6 +394,55 @@ window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
console.warn('boot error menu failed', error);
}
};
// Краткая безопасная причина для скриншота. Исходный stack и произвольный
// текст исключения доступны в меню диагностики, но не на публичном экране.
const explainBootFailure = (state) => {
const message = String(state.message || '');
const reason = String(state.reasonType || '');
if (/failed to (fetch|load|import)|module script|importing a module|networkerror|loading chunk/i.test(message)) {
return 'Не удалось загрузить модуль приложения.';
}
if (/syntaxerror|unexpected token|unexpected identifier|unexpected end of input/i.test(`${reason} ${message}`)) {
return 'Ошибка синтаксиса JavaScript.';
}
if (/referenceerror|is not defined/i.test(`${reason} ${message}`)) {
return 'Отсутствует необходимая функция или переменная.';
}
if (/typeerror|cannot read properties|is not a function/i.test(`${reason} ${message}`)) {
return 'Ошибка выполнения JavaScript (TypeError).';
}
if (state.kind === 'unhandled_rejection') {
return 'Не удалось завершить операцию при запуске.';
}
return 'Техническая ошибка при запуске приложения.';
};
const bootSourceHint = (state) => {
let filename = '';
try {
const path = new URL(String(state.sourceUrl || ''), window.location.origin).pathname;
const candidate = path.split('/').pop() || '';
if (/^[a-zA-Z0-9_.-]{1,80}$/.test(candidate)) filename = candidate;
} catch {}
const line = Number.isSafeInteger(state.lineNumber) && state.lineNumber > 0
? state.lineNumber : null;
return filename ? `Источник: ${filename}${line ? `:${line}` : ''}` : '';
};
const updateBootOverlay = () => {
const el = document.getElementById('boot-error-overlay');
const state = getState();
if (!el || !state) return;
const cause = el.querySelector('[data-boot-error="cause"]');
const source = el.querySelector('[data-boot-error="source"]');
const status = el.querySelector('[data-boot-error="status"]');
if (cause) cause.textContent = `Причина: ${explainBootFailure(state)}`;
if (source) {
source.textContent = bootSourceHint(state);
source.hidden = !source.textContent;
}
if (status) status.textContent = state.sentToServer === true
? 'Отчёт об ошибке принят сервером.'
: 'Отправка отчёта не подтверждена. Пришлите скриншот этого окна.';
};
const show = (title, text, extra = {}) => {
try {
const reportState = {
@@ -405,49 +455,68 @@ window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
columnNumber: Number.isFinite(extra.columnNumber) ? extra.columnNumber : (Number.isFinite(extra.colno) ? extra.colno : null),
reasonType: safeString(extra.reasonType || '', 64),
clientTs: Number.isFinite(extra.clientTs) ? extra.clientTs : Date.now(),
sentToServer: false,
};
setState(reportState);
let el = document.getElementById('boot-error-overlay');
if (!el) {
el = document.createElement('pre');
const light = document.documentElement.dataset.theme === 'light';
const surface = light ? '#ffffff' : '#1c1f27';
const text = light ? '#20222c' : '#f1f1f5';
const secondary = light ? '#666977' : '#a8abb8';
const border = light ? '#dedee5' : '#303440';
const accent = light ? '#4d447c' : '#b8aef5';
const accentText = light ? '#ffffff' : '#211c34';
el = document.createElement('div');
el.id = 'boot-error-overlay';
el.style.position = 'fixed';
el.style.left = '8px';
el.style.right = '8px';
el.style.bottom = '8px';
el.style.maxHeight = '40vh';
el.style.overflow = 'auto';
el.style.padding = '10px';
el.style.margin = '0';
el.style.background = 'rgba(120, 0, 0, 0.92)';
el.style.color = '#fff';
el.style.fontSize = '12px';
el.style.lineHeight = '1.4';
el.style.zIndex = '999999';
el.style.whiteSpace = 'pre-wrap';
el.style.cursor = 'pointer';
el.style.userSelect = 'none';
el.style.webkitUserSelect = 'none';
el.style.touchAction = 'manipulation';
el.setAttribute('role', 'button');
el.setAttribute('tabindex', '0');
el.setAttribute('aria-haspopup', 'dialog');
el.setAttribute('role', 'alert');
el.setAttribute('aria-label', 'Ошибка запуска приложения');
// Стили встроены специально: аварийный экран виден даже без CSS.
el.style.cssText = 'position:fixed;inset:0;z-index:999999;box-sizing:border-box;display:flex;align-items:center;justify-content:center;padding:20px;background:rgba(0,0,0,.48);visibility:visible;font-family:system-ui,-apple-system,sans-serif;';
const card = document.createElement('section');
card.style.cssText = `box-sizing:border-box;width:min(100%,440px);max-height:calc(100dvh - 40px);overflow:auto;padding:22px;border:1px solid var(--border-subtle,${border});border-radius:14px;background:var(--surface,${surface});color:var(--text-primary,${text});box-shadow:0 14px 42px rgba(0,0,0,.20);`;
const heading = document.createElement('strong');
heading.textContent = 'Не удалось запустить SHiNE';
heading.style.cssText = 'display:block;font-size:18px;line-height:1.4;font-weight:600;margin-bottom:10px;';
const intro = document.createElement('p');
intro.textContent = 'При загрузке возникла ошибка. Попробуйте обновить страницу.';
intro.style.cssText = 'margin:0 0 12px;font-size:14px;line-height:1.5;';
const cause = document.createElement('p');
cause.dataset.bootError = 'cause';
cause.style.cssText = `margin:0 0 4px;font-size:13px;line-height:1.5;color:var(--text-secondary,${secondary});overflow-wrap:anywhere;`;
const source = document.createElement('p');
source.dataset.bootError = 'source';
source.style.cssText = `margin:0 0 12px;font-size:12px;line-height:1.5;color:var(--text-secondary,${secondary});overflow-wrap:anywhere;`;
const status = document.createElement('p');
status.dataset.bootError = 'status';
status.style.cssText = `margin:0 0 18px;font-size:12px;line-height:1.5;color:var(--text-secondary,${secondary});`;
const actions = document.createElement('div');
actions.style.cssText = 'display:flex;flex-wrap:wrap;gap:10px;';
const button = (label, primary) => {
const result = document.createElement('button');
result.type = 'button';
result.textContent = label;
result.style.cssText = `flex:1 1 130px;min-height:42px;padding:10px;border:1px solid var(--border-control,${border});border-radius:10px;font:inherit;font-size:14px;font-weight:600;cursor:pointer;background:${primary ? `var(--accent,${accent})` : `var(--surface,${surface})`};color:${primary ? `var(--on-accent,${accentText})` : `var(--text-primary,${text})`};`;
return result;
};
const retry = button('Обновить страницу', true);
retry.addEventListener('click', () => window.location.reload());
const details = button('Подробности', false);
details.addEventListener('click', openMenu);
actions.append(retry, details);
card.append(heading, intro, cause, source, status, actions);
el.appendChild(card);
document.body.appendChild(el);
el.addEventListener('click', openMenu);
el.addEventListener('keydown', (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
openMenu();
}
});
}
el.textContent = `[BOOT ERROR] ${title}\n${String(text || '')}`;
el.setAttribute('aria-label', `${title}. Нажмите, чтобы открыть меню действий.`);
el.title = 'Нажмите, чтобы открыть меню действий';
} catch {}
updateBootOverlay();
} catch (error) {
console.warn('boot error overlay failed', error);
}
};
window.addEventListener('error', (e) => {
// После запуска приложения ошибки обрабатывает единый client-error-reporter.
if (window.__SHINE_APP_ERROR_HANDLERS_READY__ === true) return;
// Предупреждение браузера о переносе замеров ResizeObserver на следующий кадр – не ошибка
if (/^ResizeObserver loop/.test(String(e?.message || ''))) return;
show('window.error', `${e?.message || ''}\n${e?.filename || ''}:${e?.lineno || ''}:${e?.colno || ''}`, {
@@ -461,6 +530,7 @@ window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
});
});
window.addEventListener('unhandledrejection', (e) => {
if (window.__SHINE_APP_ERROR_HANDLERS_READY__ === true) return;
const reason = e?.reason;
show('unhandledrejection', reason?.stack || reason?.message || String(reason || 'unknown'), {
kind: 'unhandled_rejection',
+3
View File
@@ -1427,6 +1427,9 @@ window.addEventListener('unhandledrejection', (event) => {
else void reportPromise.then((sent) => showGlobalErrorAlert('Ошибка UI', details, sent, reportId));
});
// BOOT ERROR нужен только до подключения штатных глобальных обработчиков приложения.
window.__SHINE_APP_ERROR_HANDLERS_READY__ = true;
function renderPageFailureFallback(pageId, error) {
const reportPromise = captureClientError({
kind: 'page_render_failure',
+1 -1
View File
@@ -3547,7 +3547,7 @@ export class AuthService {
if (this.ws?.ws?.readyState !== WebSocket.OPEN) return false;
try {
const response = await this.ws.request('ClientErrorLog', details || {}, 3000);
return response?.status === 200 && response?.accepted === true;
return response?.status === 200 && response?.payload?.accepted === true;
} catch {
return false;
}
@@ -91,3 +91,108 @@ test('конфиг сервера изолирует client-errors.log на 14
assert.match(xml, /<logger name="client\.frontend" level="error" additivity="false">/);
assert.match(xml, /<totalSizeCap>150MB<\/totalSizeCap>/);
});
test('ClientErrorLog подтверждается по payload.accepted, а не по корневому полю', async () => {
const src = read('../js/services/auth-service.js');
const match = src.match(/async reportClientError\(details\) \{([\s\S]*?)\n \}/);
assert.ok(match, 'reportClientError method exists');
const report = new Function('details', `return (async function () {${match[1]}\n}).call(this);`);
globalThis.WebSocket = { OPEN: 1 };
const request = async () => ({ status: 200, payload: { accepted: true } });
const ws = { ws: { readyState: 1 }, request };
assert.equal(await report.call({ ws }, { kind: 'global_error', message: 'Test' }), true);
ws.request = async () => ({ status: 200, payload: { accepted: false } });
assert.equal(await report.call({ ws }, { kind: 'global_error', message: 'Test' }), false);
ws.request = async () => ({ status: 500, payload: { accepted: true } });
assert.equal(await report.call({ ws }, { kind: 'global_error', message: 'Test' }), false);
ws.ws.readyState = 3;
assert.equal(await report.call({ ws }, { kind: 'global_error', message: 'Test' }), false);
});
test('BOOT ERROR отключает аварийную плашку после подключения штатного обработчика', () => {
const index = read('../index.html');
const app = read('../js/app.js');
assert.match(app, /window\.__SHINE_APP_ERROR_HANDLERS_READY__ = true;/);
const handlers = [...index.matchAll(/window\.addEventListener\('(error|unhandledrejection)', \(e\) => \{\s*([\s\S]*?)\n \}\);/g)];
assert.equal(handlers.length, 2);
for (const match of handlers) {
assert.match(match[2], /if \(window\.__SHINE_APP_ERROR_HANDLERS_READY__ === true\) return;/);
}
});
test('аварийный экран нейтральный, с причиной, источником и кнопкой перезагрузки', () => {
const index = read('../index.html');
assert.match(index, /Не удалось запустить SHiNE/);
assert.match(index, /Причина: \$/);
assert.match(index, /Источник: \$/);
assert.match(index, /Обновить страницу/);
assert.match(index, /Подробности/);
assert.match(index, /Отправка отчёта не подтверждена/);
assert.match(index, /state\.sentToServer === true/);
assert.match(index, /sentToServer: true/);
assert.doesNotMatch(index, /rgba\(120, 0, 0/);
assert.doesNotMatch(index, /\[BOOT ERROR\] \$/);
});
test('аварийный экран не показывает stack и произвольный текст исключения', () => {
const index = read('../index.html');
const match = index.match(/const updateBootOverlay = \(\) => \{([\s\S]*?)\n \};/);
assert.ok(match, 'есть функция обновления аварийного экрана');
assert.doesNotMatch(match[1], /\.stack|state\.message\s*;/);
assert.match(index, /Ошибка выполнения JavaScript \(TypeError\)/);
assert.match(index, /if \(window\.__SHINE_APP_ERROR_HANDLERS_READY__ === true\) return;/);
});
test('BOOT ERROR показывает краткую причину без приватного текста и позволяет перезагрузить страницу', async () => {
const { runInNewContext } = await import('node:vm');
const index = read('../index.html');
const match = index.match(/\(function attachBootErrorOverlay\(\) \{[\s\S]*?\}\(\)\);/);
assert.ok(match, 'загрузочный обработчик найден');
class FakeElement {
constructor(tag = 'div') { this.tag = tag; this.children = []; this.style = {}; this.dataset = {}; this.handlers = {}; this.attributes = {}; this.textContent = ''; }
setAttribute(name, value) { this.attributes[name] = value; }
append(...els) { this.children.push(...els); }
appendChild(el) { this.children.push(el); }
addEventListener(name, handler) { this.handlers[name] = handler; }
querySelector(selector) {
const key = selector.match(/^\[data-boot-error="(.*?)"\]$/)?.[1];
const descend = (el) => {
if (key && el.dataset?.bootError === key) return el;
for (const child of el.children) { const found = descend(child); if (found) return found; }
return null;
};
return descend(this);
}
}
const body = new FakeElement('body');
const handlers = {};
let reloads = 0;
const fakeWindow = {
addEventListener: (type, handler) => { handlers[type] = handler; },
location: { origin: 'https://shineup.me', reload: () => reloads++ },
};
const fakeDocument = {
documentElement: { dataset: { theme: 'dark' } }, body,
createElement: (tag) => new FakeElement(tag),
getElementById: (id) => body.children.find((el) => el.id === id) || null,
};
runInNewContext(match[0], { window: fakeWindow, document: fakeDocument, navigator: { userAgent: 'test' }, console, URL, Date, Number, String, Math });
handlers.error({
message: 'TypeError: private message text: NEVER_SHOW_ME',
filename: 'https://shineup.me/js/app.js?password=NEVER_SHOW_ME', lineno: 42, colno: 9,
error: { stack: 'TypeError: NEVER_SHOW_ME' },
});
const overlay = fakeDocument.getElementById('boot-error-overlay');
assert.ok(overlay);
assert.equal(overlay.querySelector('[data-boot-error="cause"]').textContent, 'Причина: Ошибка выполнения JavaScript (TypeError).');
assert.equal(overlay.querySelector('[data-boot-error="source"]').textContent, 'Источник: app.js:42');
assert.match(overlay.querySelector('[data-boot-error="status"]').textContent, /не подтверждена/);
const rendered = JSON.stringify(body, (k, v) => k === 'handlers' ? undefined : v);
assert.ok(!rendered.includes('NEVER_SHOW_ME'));
const buttons = overlay.children[0].children.at(-1).children;
assert.equal(buttons[0].textContent, 'Обновить страницу');
buttons[0].handlers.click();
assert.equal(reloads, 1);
});