SHA256
Compare commits
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
dbac798e7f |
+1
-1
@@ -1,2 +1,2 @@
|
|||||||
client.version=1.20.0
|
client.version=1.20.1
|
||||||
server.version=1.16.0
|
server.version=1.16.0
|
||||||
|
|||||||
+177
-2
@@ -12,6 +12,175 @@
|
|||||||
<link rel="icon" type="image/jpeg" href="./img/logo.jpg" />
|
<link rel="icon" type="image/jpeg" href="./img/logo.jpg" />
|
||||||
<link rel="apple-touch-icon" href="./img/logo.jpg" />
|
<link rel="apple-touch-icon" href="./img/logo.jpg" />
|
||||||
<title>СИЯНИЕ</title>
|
<title>СИЯНИЕ</title>
|
||||||
|
<script id="shine-stage0-startup-diagnostics">
|
||||||
|
// Stage 0: пассивные метки только при включённых инструментах разработчика.
|
||||||
|
(function initializeStartupDiagnostics() {
|
||||||
|
let debugEnabled = false;
|
||||||
|
try {
|
||||||
|
const flag = localStorage.getItem('shine-feature-developer-tools-v1');
|
||||||
|
debugEnabled = flag === '1' || flag === 'true';
|
||||||
|
} catch {}
|
||||||
|
if (!debugEnabled || !window.performance || typeof performance.mark !== 'function') return;
|
||||||
|
|
||||||
|
const allowed = new Set([
|
||||||
|
'bootstrap', 'dom_ready', 'css_start', 'css_ok', 'css_error', 'css_complete', 'css_revealed',
|
||||||
|
'main_js_requested', 'main_js_start', 'first_dom_render', 'splash_leave', 'splash_removed',
|
||||||
|
'ws_attempt', 'ws_open', 'ws_error', 'ws_close',
|
||||||
|
'session_restore_start', 'session_restore_ok', 'session_restore_failed',
|
||||||
|
'reconnect_restore_start', 'reconnect_restore_ok', 'reconnect_restore_failed',
|
||||||
|
'health_invoked', 'health_skipped_inflight', 'health_local_demo',
|
||||||
|
'status_connected', 'splash_finish_called', 'splash_transition_start',
|
||||||
|
'splash_removed_via_transition', 'splash_removed_via_timeout',
|
||||||
|
]);
|
||||||
|
const single = new Set([
|
||||||
|
'bootstrap', 'dom_ready', 'css_start', 'css_complete', 'css_revealed',
|
||||||
|
'main_js_requested', 'main_js_start', 'first_dom_render', 'splash_leave', 'splash_removed',
|
||||||
|
'session_restore_start', 'session_restore_ok', 'session_restore_failed',
|
||||||
|
'splash_transition_start', 'splash_removed_via_transition', 'splash_removed_via_timeout',
|
||||||
|
]);
|
||||||
|
const operationsAllowed = new Set([
|
||||||
|
'connection_health', 'monitor_start', 'ping', 'pwa_first_ping_update', 'ui_version_ping',
|
||||||
|
'ui_version_periodic', 'ui_version_fetch', 'sw_refresh',
|
||||||
|
'sw_get_registrations', 'sw_registration_update', 'sw_skip_waiting',
|
||||||
|
]);
|
||||||
|
const operationContexts = new Set([
|
||||||
|
'first_ping', 'reload', 'bootstrap', 'session_runtime', 'session_reset',
|
||||||
|
'periodic', 'visibility', 'retry_countdown', 'manual_retry', 'unspecified',
|
||||||
|
]);
|
||||||
|
const safeErrorNames = new Set([
|
||||||
|
'AbortError', 'TimeoutError', 'NetworkError', 'SecurityError', 'InvalidStateError',
|
||||||
|
'NotAllowedError', 'NotFoundError', 'TypeError', 'SyntaxError', 'RangeError', 'Error',
|
||||||
|
'HttpResponseNotOk',
|
||||||
|
]);
|
||||||
|
const operations = [];
|
||||||
|
const pendingOperations = new Map();
|
||||||
|
let operationsDropped = 0;
|
||||||
|
let nextOperationId = 0;
|
||||||
|
const events = [];
|
||||||
|
const counts = Object.create(null);
|
||||||
|
const first = Object.create(null);
|
||||||
|
const maxEvents = 256;
|
||||||
|
const round = (value) => Math.round(value * 10) / 10;
|
||||||
|
function mark(stage) {
|
||||||
|
try {
|
||||||
|
if (!allowed.has(stage)) return;
|
||||||
|
if (single.has(stage) && Object.hasOwn(first, stage)) return;
|
||||||
|
if (stage === 'session_restore_failed' && Object.hasOwn(first, 'session_restore_ok')) return;
|
||||||
|
const atMs = round(performance.now());
|
||||||
|
counts[stage] = (counts[stage] || 0) + 1;
|
||||||
|
if (!Object.hasOwn(first, stage)) first[stage] = atMs;
|
||||||
|
if (events.length < maxEvents) {
|
||||||
|
performance.mark('shine-stage0:' + stage);
|
||||||
|
events.push({ stage, atMs });
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Измерение никогда не должно прерывать запуск приложения.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Only fixed stage/operation names and fixed error classes can enter the export.
|
||||||
|
// Numeric ids are local measurement sequence numbers, never request/session ids.
|
||||||
|
function begin(operation, context = null) {
|
||||||
|
try {
|
||||||
|
if (!operationsAllowed.has(operation)) return null;
|
||||||
|
if (operations.length >= 256) { operationsDropped += 1; return null; }
|
||||||
|
const id = ++nextOperationId;
|
||||||
|
const item = { id, operation, startMs: round(performance.now()), endMs: null,
|
||||||
|
durationMs: null, outcome: 'pending' };
|
||||||
|
if (operationContexts.has(context)) item.context = context;
|
||||||
|
operations.push(item);
|
||||||
|
pendingOperations.set(id, item);
|
||||||
|
performance.mark('shine-stage0:' + operation + ':start');
|
||||||
|
return id;
|
||||||
|
} catch { return null; }
|
||||||
|
}
|
||||||
|
function finish(id, outcome = 'ok', error = null) {
|
||||||
|
try {
|
||||||
|
const item = pendingOperations.get(id);
|
||||||
|
if (!item) return;
|
||||||
|
pendingOperations.delete(id);
|
||||||
|
const endMs = round(performance.now());
|
||||||
|
item.endMs = endMs;
|
||||||
|
item.durationMs = round(endMs - item.startMs);
|
||||||
|
item.outcome = outcome === 'error' ? 'error'
|
||||||
|
: outcome === 'restore-unavailable' ? 'restore-unavailable'
|
||||||
|
: outcome === 'deduplicated' ? 'deduplicated' : 'ok';
|
||||||
|
if (item.outcome === 'error') {
|
||||||
|
let name;
|
||||||
|
try { name = error?.name; } catch {}
|
||||||
|
item.errorType = safeErrorNames.has(name) ? name : 'UnknownError';
|
||||||
|
}
|
||||||
|
performance.mark('shine-stage0:' + item.operation + ':end');
|
||||||
|
} catch {
|
||||||
|
// A diagnostic failure must never affect a network or UI operation.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function exportJson() {
|
||||||
|
const timing = Object.create(null);
|
||||||
|
for (const stage of allowed) {
|
||||||
|
if (Object.hasOwn(first, stage)) timing[stage] = first[stage];
|
||||||
|
}
|
||||||
|
const interval = (a, b) => a in first && b in first ? round(first[b] - first[a]) : null;
|
||||||
|
let domContentLoadedMs = null;
|
||||||
|
let firstContentfulPaintMs = null;
|
||||||
|
try {
|
||||||
|
const navigation = performance.getEntriesByType('navigation')[0];
|
||||||
|
if (navigation && Number.isFinite(navigation.domContentLoadedEventEnd)) {
|
||||||
|
domContentLoadedMs = round(navigation.domContentLoadedEventEnd);
|
||||||
|
}
|
||||||
|
const paint = performance.getEntriesByType('paint').find((item) => item.name === 'first-contentful-paint');
|
||||||
|
if (paint) firstContentfulPaintMs = round(paint.startTime);
|
||||||
|
} catch {}
|
||||||
|
return JSON.stringify({
|
||||||
|
schema: 'shine-stage0-v1',
|
||||||
|
units: 'milliseconds_since_navigation_start',
|
||||||
|
timing,
|
||||||
|
durations: {
|
||||||
|
cssAllSettledMs: interval('css_start', 'css_complete'),
|
||||||
|
cssRevealMs: interval('css_start', 'css_revealed'),
|
||||||
|
moduleLoadAndEvaluationMs: interval('main_js_requested', 'main_js_start'),
|
||||||
|
sessionRestoreMs: interval('session_restore_start',
|
||||||
|
'session_restore_ok' in first ? 'session_restore_ok' : 'session_restore_failed'),
|
||||||
|
splashRemovalMs: interval('bootstrap', 'splash_removed'),
|
||||||
|
renderToSplashLeaveMs: interval('first_dom_render', 'splash_leave'),
|
||||||
|
connectedToSplashLeaveMs: interval('status_connected', 'splash_leave'),
|
||||||
|
splashTransitionToRemovalMs: interval('splash_transition_start', 'splash_removed'),
|
||||||
|
},
|
||||||
|
browser: { domContentLoadedMs, firstContentfulPaintMs },
|
||||||
|
counters: {
|
||||||
|
cssLoaded: counts.css_ok || 0,
|
||||||
|
cssFailed: counts.css_error || 0,
|
||||||
|
wsAttempts: counts.ws_attempt || 0,
|
||||||
|
wsAttemptsAfterFirst: Math.max(0, (counts.ws_attempt || 0) - 1),
|
||||||
|
wsOpened: counts.ws_open || 0,
|
||||||
|
wsOpenErrors: counts.ws_error || 0,
|
||||||
|
wsClosed: counts.ws_close || 0,
|
||||||
|
sessionRestoreFailures: counts.session_restore_failed || 0,
|
||||||
|
reconnectRestoreFailures: counts.reconnect_restore_failed || 0,
|
||||||
|
eventsDropped: Object.values(counts).reduce((sum, n) => sum + n, 0) - events.length,
|
||||||
|
pingStarted: operations.filter((op) => op.operation === 'ping').length,
|
||||||
|
pingCompleted: operations.filter((op) => op.operation === 'ping' && op.endMs !== null).length,
|
||||||
|
connectedAssignments: counts.status_connected || 0,
|
||||||
|
splashFinishCalls: counts.splash_finish_called || 0,
|
||||||
|
operationsDropped,
|
||||||
|
},
|
||||||
|
events: events.slice(),
|
||||||
|
splashTrace: {
|
||||||
|
// No record means the operation was never observed. A pending record has
|
||||||
|
// endMs/durationMs null; it must not be confused with a zero-duration call.
|
||||||
|
operations: operations.map((item) => ({ ...item })),
|
||||||
|
},
|
||||||
|
}, null, 2);
|
||||||
|
}
|
||||||
|
Object.defineProperty(window, '__SHINE_STAGE0__', {
|
||||||
|
value: Object.freeze({ mark, begin, finish }), configurable: false, writable: false,
|
||||||
|
});
|
||||||
|
Object.defineProperty(window, '__SHINE_STAGE0_EXPORT__', {
|
||||||
|
value: exportJson, configurable: false, writable: false,
|
||||||
|
});
|
||||||
|
mark('bootstrap');
|
||||||
|
document.addEventListener('DOMContentLoaded', () => mark('dom_ready'), { once: true });
|
||||||
|
}());
|
||||||
|
</script>
|
||||||
<script>
|
<script>
|
||||||
(function applySavedThemeBeforePaint() {
|
(function applySavedThemeBeforePaint() {
|
||||||
let mode = 'system';
|
let mode = 'system';
|
||||||
@@ -50,8 +219,13 @@ window.__SHINE_BUILD_HASH__ = '20261015230000';
|
|||||||
// на долю секунды виден экран без CSS (логотип 640×640), а потом он «прыгает» на место.
|
// на долю секунды виден экран без CSS (логотип 640×640), а потом он «прыгает» на место.
|
||||||
const root = document.documentElement;
|
const root = document.documentElement;
|
||||||
let pending = cssFiles.length;
|
let pending = cssFiles.length;
|
||||||
const reveal = () => root.classList.add('shine-styles-ready');
|
const reveal = () => { root.classList.add('shine-styles-ready'); window.__SHINE_STAGE0__?.mark('css_revealed'); };
|
||||||
const settle = () => { pending -= 1; if (pending <= 0) reveal(); };
|
const settle = (event) => {
|
||||||
|
window.__SHINE_STAGE0__?.mark(event?.type === 'error' ? 'css_error' : 'css_ok');
|
||||||
|
pending -= 1;
|
||||||
|
if (pending <= 0) { window.__SHINE_STAGE0__?.mark('css_complete'); reveal(); }
|
||||||
|
};
|
||||||
|
window.__SHINE_STAGE0__?.mark('css_start');
|
||||||
cssFiles.forEach((file) => {
|
cssFiles.forEach((file) => {
|
||||||
const link = document.createElement('link');
|
const link = document.createElement('link');
|
||||||
link.rel = 'stylesheet';
|
link.rel = 'stylesheet';
|
||||||
@@ -484,6 +658,7 @@ window.__SHINE_BUILD_HASH__ = '20261015230000';
|
|||||||
const script = document.createElement('script');
|
const script = document.createElement('script');
|
||||||
script.type = 'module';
|
script.type = 'module';
|
||||||
script.src = isLocalPreview ? `./js/app.js?v=${v}&local=${Date.now()}` : `./js/app.js?v=${v}`;
|
script.src = isLocalPreview ? `./js/app.js?v=${v}&local=${Date.now()}` : `./js/app.js?v=${v}`;
|
||||||
|
window.__SHINE_STAGE0__?.mark('main_js_requested');
|
||||||
document.body.appendChild(script);
|
document.body.appendChild(script);
|
||||||
}());
|
}());
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
+130
-20
@@ -129,6 +129,8 @@ import * as addPersonalPublicChatView from './pages/add-personal-public-chat-vie
|
|||||||
import * as networkView from './pages/network-version-switcher.js?v=202610170100';
|
import * as networkView from './pages/network-version-switcher.js?v=202610170100';
|
||||||
import * as notificationsView from './pages/notifications-view.js?v=202610130400';
|
import * as notificationsView from './pages/notifications-view.js?v=202610130400';
|
||||||
|
|
||||||
|
window.__SHINE_STAGE0__?.mark('main_js_start');
|
||||||
|
|
||||||
const CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
|
const CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
|
||||||
const DM_UNSUPPORTED_FORMAT_TEXT = 'Формат сообщения не поддерживается';
|
const DM_UNSUPPORTED_FORMAT_TEXT = 'Формат сообщения не поддерживается';
|
||||||
const DM_DECRYPT_FAILED_TEXT = 'Не удалось расшифровать сообщение';
|
const DM_DECRYPT_FAILED_TEXT = 'Не удалось расшифровать сообщение';
|
||||||
@@ -221,6 +223,7 @@ const UI_BUILD_HASH_PATTERN = /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/;
|
|||||||
|
|
||||||
let currentCleanup = null;
|
let currentCleanup = null;
|
||||||
let pingIntervalId = null;
|
let pingIntervalId = null;
|
||||||
|
let connectionMonitorStartSource = '';
|
||||||
let reconnectIntervalId = null;
|
let reconnectIntervalId = null;
|
||||||
let channelsPrefetchTimerId = null;
|
let channelsPrefetchTimerId = null;
|
||||||
let channelsPrefetchEpoch = 0;
|
let channelsPrefetchEpoch = 0;
|
||||||
@@ -836,6 +839,7 @@ function refreshConnectionUi() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function finishInitialConnectionSplash() {
|
function finishInitialConnectionSplash() {
|
||||||
|
window.__SHINE_STAGE0__?.mark('splash_finish_called');
|
||||||
if (initialConnectionCompleted) return;
|
if (initialConnectionCompleted) return;
|
||||||
initialConnectionCompleted = true;
|
initialConnectionCompleted = true;
|
||||||
if (!initialSplashEl) {
|
if (!initialSplashEl) {
|
||||||
@@ -843,8 +847,27 @@ function finishInitialConnectionSplash() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The CSS 'is-leaving' mutation is not the actual transition start.
|
||||||
|
// This debug-only passive listener observes the browser's transitionstart event.
|
||||||
|
if (window.__SHINE_STAGE0__) {
|
||||||
|
initialSplashEl.addEventListener('transitionstart', (event) => {
|
||||||
|
if (event.target === initialSplashEl && event.propertyName === 'opacity') {
|
||||||
|
window.__SHINE_STAGE0__?.mark('splash_transition_start');
|
||||||
|
}
|
||||||
|
}, { passive: true });
|
||||||
|
}
|
||||||
initialSplashEl.classList.add('is-leaving');
|
initialSplashEl.classList.add('is-leaving');
|
||||||
const removeSplash = () => initialSplashEl.remove();
|
window.__SHINE_STAGE0__?.mark('splash_leave');
|
||||||
|
let splashRemovalRecorded = false;
|
||||||
|
const removeSplash = (event) => {
|
||||||
|
initialSplashEl.remove();
|
||||||
|
window.__SHINE_STAGE0__?.mark('splash_removed');
|
||||||
|
if (!splashRemovalRecorded) {
|
||||||
|
splashRemovalRecorded = true;
|
||||||
|
window.__SHINE_STAGE0__?.mark(event?.type === 'transitionend'
|
||||||
|
? 'splash_removed_via_transition' : 'splash_removed_via_timeout');
|
||||||
|
}
|
||||||
|
};
|
||||||
initialSplashEl.addEventListener('transitionend', removeSplash, { once: true });
|
initialSplashEl.addEventListener('transitionend', removeSplash, { once: true });
|
||||||
window.setTimeout(removeSplash, 700);
|
window.setTimeout(removeSplash, 700);
|
||||||
refreshConnectionUi();
|
refreshConnectionUi();
|
||||||
@@ -858,7 +881,7 @@ function startConnectionCountdown() {
|
|||||||
if (secs <= 0 && !connectionCheckInFlight) {
|
if (secs <= 0 && !connectionCheckInFlight) {
|
||||||
connectionStatusText = '';
|
connectionStatusText = '';
|
||||||
setConnectionStatus('connecting', 'Соединяюсь…');
|
setConnectionStatus('connecting', 'Соединяюсь…');
|
||||||
void checkConnectionHealth();
|
void checkConnectionHealth('retry_countdown');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
refreshConnectionUi();
|
refreshConnectionUi();
|
||||||
@@ -1028,6 +1051,7 @@ function setConnectionStatus(nextState, text = '') {
|
|||||||
const state = String(nextState || '').trim();
|
const state = String(nextState || '').trim();
|
||||||
if (!state) return;
|
if (!state) return;
|
||||||
connectionState = state;
|
connectionState = state;
|
||||||
|
if (state === 'connected') window.__SHINE_STAGE0__?.mark('status_connected');
|
||||||
connectionStatusText = String(text || '').trim();
|
connectionStatusText = String(text || '').trim();
|
||||||
if (state === 'connected') {
|
if (state === 'connected') {
|
||||||
finishInitialConnectionSplash();
|
finishInitialConnectionSplash();
|
||||||
@@ -1047,7 +1071,7 @@ async function triggerImmediateConnectionRetry() {
|
|||||||
if (connectionCheckInFlight) return;
|
if (connectionCheckInFlight) return;
|
||||||
connectionNextRetryAtMs = Date.now() + CONNECTION_CHECK_INTERVAL_MS;
|
connectionNextRetryAtMs = Date.now() + CONNECTION_CHECK_INTERVAL_MS;
|
||||||
setConnectionStatus('connecting', 'Соединяюсь…');
|
setConnectionStatus('connecting', 'Соединяюсь…');
|
||||||
await checkConnectionHealth();
|
await checkConnectionHealth('manual_retry');
|
||||||
}
|
}
|
||||||
|
|
||||||
function extractBuildHashFromHtml(htmlText) {
|
function extractBuildHashFromHtml(htmlText) {
|
||||||
@@ -1058,14 +1082,21 @@ function extractBuildHashFromHtml(htmlText) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function fetchCurrentHostUiBuildHash() {
|
async function fetchCurrentHostUiBuildHash() {
|
||||||
|
const traceId = window.__SHINE_STAGE0__?.begin?.('ui_version_fetch');
|
||||||
try {
|
try {
|
||||||
const url = `./index.html?build_probe=${Date.now()}`;
|
const url = `./index.html?build_probe=${Date.now()}`;
|
||||||
const response = await fetch(url, { cache: 'no-store' });
|
const response = await fetch(url, { cache: 'no-store' });
|
||||||
if (!response?.ok) return '';
|
if (!response?.ok) {
|
||||||
|
window.__SHINE_STAGE0__?.finish?.(traceId, 'error', { name: 'HttpResponseNotOk' });
|
||||||
|
return '';
|
||||||
|
}
|
||||||
const html = await response.text();
|
const html = await response.text();
|
||||||
return extractBuildHashFromHtml(html);
|
return extractBuildHashFromHtml(html);
|
||||||
} catch {
|
} catch (error) {
|
||||||
|
window.__SHINE_STAGE0__?.finish?.(traceId, 'error', error);
|
||||||
return '';
|
return '';
|
||||||
|
} finally {
|
||||||
|
window.__SHINE_STAGE0__?.finish?.(traceId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1075,6 +1106,8 @@ async function checkAndReloadIfUiUpdated(remoteHashRaw) {
|
|||||||
if (uiVersionCheckInFlight) return;
|
if (uiVersionCheckInFlight) return;
|
||||||
|
|
||||||
uiVersionCheckInFlight = true;
|
uiVersionCheckInFlight = true;
|
||||||
|
const traceId = window.__SHINE_STAGE0__?.begin?.('ui_version_ping');
|
||||||
|
let traceError = null;
|
||||||
try {
|
try {
|
||||||
const latestHostHash = await fetchCurrentHostUiBuildHash();
|
const latestHostHash = await fetchCurrentHostUiBuildHash();
|
||||||
if (!latestHostHash || latestHostHash === CURRENT_BUILD_HASH) {
|
if (!latestHostHash || latestHostHash === CURRENT_BUILD_HASH) {
|
||||||
@@ -1092,27 +1125,51 @@ async function checkAndReloadIfUiUpdated(remoteHashRaw) {
|
|||||||
delayMs: 600,
|
delayMs: 600,
|
||||||
activateWaitingWorker: true,
|
activateWaitingWorker: true,
|
||||||
});
|
});
|
||||||
|
} catch (error) {
|
||||||
|
traceError = error;
|
||||||
|
throw error;
|
||||||
} finally {
|
} finally {
|
||||||
|
window.__SHINE_STAGE0__?.finish?.(traceId, traceError ? 'error' : 'ok', traceError);
|
||||||
uiVersionCheckInFlight = false;
|
uiVersionCheckInFlight = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function refreshServiceWorkers({ activateWaitingWorker = false } = {}) {
|
async function refreshServiceWorkers({ activateWaitingWorker = false } = {}) {
|
||||||
if (!('serviceWorker' in navigator)) return;
|
if (!('serviceWorker' in navigator)) return;
|
||||||
|
const trace = window.__SHINE_STAGE0__;
|
||||||
|
const context = activateWaitingWorker ? 'reload' : 'first_ping';
|
||||||
|
const refreshId = trace?.begin?.('sw_refresh', context);
|
||||||
|
let listId = null;
|
||||||
|
let refreshError = null;
|
||||||
try {
|
try {
|
||||||
|
listId = trace?.begin?.('sw_get_registrations', context);
|
||||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||||
|
trace?.finish?.(listId);
|
||||||
|
listId = null;
|
||||||
await Promise.all(registrations.map(async (registration) => {
|
await Promise.all(registrations.map(async (registration) => {
|
||||||
|
const updateId = trace?.begin?.('sw_registration_update', context);
|
||||||
try {
|
try {
|
||||||
await registration.update();
|
await registration.update();
|
||||||
} catch {}
|
trace?.finish?.(updateId);
|
||||||
|
} catch (error) {
|
||||||
|
trace?.finish?.(updateId, 'error', error);
|
||||||
|
}
|
||||||
if (activateWaitingWorker && registration.waiting) {
|
if (activateWaitingWorker && registration.waiting) {
|
||||||
|
const waitingId = trace?.begin?.('sw_skip_waiting', context);
|
||||||
try {
|
try {
|
||||||
registration.waiting.postMessage({ type: 'SKIP_WAITING' });
|
registration.waiting.postMessage({ type: 'SKIP_WAITING' });
|
||||||
} catch {}
|
trace?.finish?.(waitingId);
|
||||||
|
} catch (error) {
|
||||||
|
trace?.finish?.(waitingId, 'error', error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
} catch {
|
} catch (error) {
|
||||||
|
refreshError = error;
|
||||||
|
trace?.finish?.(listId, 'error', error);
|
||||||
// ignore service worker update failures
|
// ignore service worker update failures
|
||||||
|
} finally {
|
||||||
|
trace?.finish?.(refreshId, refreshError ? 'error' : 'ok', refreshError);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1141,12 +1198,21 @@ function scheduleUiReload({
|
|||||||
async function tryUpdatePwaOnFirstConnectedPing() {
|
async function tryUpdatePwaOnFirstConnectedPing() {
|
||||||
if (pwaUpdateCheckAttempted) return;
|
if (pwaUpdateCheckAttempted) return;
|
||||||
pwaUpdateCheckAttempted = true;
|
pwaUpdateCheckAttempted = true;
|
||||||
|
const traceId = window.__SHINE_STAGE0__?.begin?.('pwa_first_ping_update');
|
||||||
|
try {
|
||||||
await refreshServiceWorkers({ activateWaitingWorker: false });
|
await refreshServiceWorkers({ activateWaitingWorker: false });
|
||||||
|
} catch (error) {
|
||||||
|
window.__SHINE_STAGE0__?.finish?.(traceId, 'error', error);
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
window.__SHINE_STAGE0__?.finish?.(traceId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function runPeriodicUiVersionCheck() {
|
async function runPeriodicUiVersionCheck() {
|
||||||
if (uiUpdateReloadScheduled) return;
|
if (uiUpdateReloadScheduled) return;
|
||||||
if (uiVersionCheckInFlight) return;
|
if (uiVersionCheckInFlight) return;
|
||||||
|
const traceId = window.__SHINE_STAGE0__?.begin?.('ui_version_periodic');
|
||||||
try {
|
try {
|
||||||
const latestHostHash = await fetchCurrentHostUiBuildHash();
|
const latestHostHash = await fetchCurrentHostUiBuildHash();
|
||||||
if (!latestHostHash || !CURRENT_BUILD_HASH || latestHostHash === CURRENT_BUILD_HASH) return;
|
if (!latestHostHash || !CURRENT_BUILD_HASH || latestHostHash === CURRENT_BUILD_HASH) return;
|
||||||
@@ -1156,8 +1222,11 @@ async function runPeriodicUiVersionCheck() {
|
|||||||
delayMs: 600,
|
delayMs: 600,
|
||||||
activateWaitingWorker: true,
|
activateWaitingWorker: true,
|
||||||
});
|
});
|
||||||
} catch {
|
} catch (error) {
|
||||||
|
window.__SHINE_STAGE0__?.finish?.(traceId, 'error', error);
|
||||||
// ignore periodic check errors
|
// ignore periodic check errors
|
||||||
|
} finally {
|
||||||
|
window.__SHINE_STAGE0__?.finish?.(traceId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1170,13 +1239,23 @@ function startPeriodicUiVersionCheck() {
|
|||||||
}, UI_VERSION_PERIODIC_CHECK_MS);
|
}, UI_VERSION_PERIODIC_CHECK_MS);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkConnectionHealth() {
|
async function checkConnectionHealth(source = 'unspecified') {
|
||||||
|
window.__SHINE_STAGE0__?.mark('health_invoked');
|
||||||
if (state.session.isLocalDemo) {
|
if (state.session.isLocalDemo) {
|
||||||
|
window.__SHINE_STAGE0__?.mark('health_local_demo');
|
||||||
|
const demoId = window.__SHINE_STAGE0__?.begin?.('connection_health');
|
||||||
setConnectionStatus('connected');
|
setConnectionStatus('connected');
|
||||||
|
window.__SHINE_STAGE0__?.finish?.(demoId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (connectionCheckInFlight) {
|
||||||
|
window.__SHINE_STAGE0__?.mark('health_skipped_inflight');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (connectionCheckInFlight) return;
|
|
||||||
connectionCheckInFlight = true;
|
connectionCheckInFlight = true;
|
||||||
|
const trace = window.__SHINE_STAGE0__;
|
||||||
|
const healthId = trace?.begin?.('connection_health', source);
|
||||||
|
let pingId = null;
|
||||||
if (connectionState !== 'connected') {
|
if (connectionState !== 'connected') {
|
||||||
setConnectionStatus('connecting');
|
setConnectionStatus('connecting');
|
||||||
}
|
}
|
||||||
@@ -1188,25 +1267,47 @@ async function checkConnectionHealth() {
|
|||||||
if (!restored) {
|
if (!restored) {
|
||||||
connectionStatusText = '';
|
connectionStatusText = '';
|
||||||
setConnectionStatus('disconnected');
|
setConnectionStatus('disconnected');
|
||||||
|
trace?.finish?.(healthId, 'restore-unavailable');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
pingId = trace?.begin?.('ping');
|
||||||
const pingResp = await authService.ws.request('Ping', { ts: Date.now() }, 7000);
|
const pingResp = await authService.ws.request('Ping', { ts: Date.now() }, 7000);
|
||||||
|
trace?.finish?.(pingId);
|
||||||
|
pingId = null;
|
||||||
const remoteUiBuildHash = pingResp?.payload?.uiBuildHash || pingResp?.uiBuildHash || '';
|
const remoteUiBuildHash = pingResp?.payload?.uiBuildHash || pingResp?.uiBuildHash || '';
|
||||||
void checkAndReloadIfUiUpdated(remoteUiBuildHash);
|
void checkAndReloadIfUiUpdated(remoteUiBuildHash);
|
||||||
await tryUpdatePwaOnFirstConnectedPing();
|
// Проверка SW остаётся одноразовой, но не задерживает статус после успешного Ping.
|
||||||
|
void tryUpdatePwaOnFirstConnectedPing().catch(() => {
|
||||||
|
// Ошибка уже отмечена диагностикой Stage 0.1; соединение определяет только Ping.
|
||||||
|
});
|
||||||
setConnectionStatus('connected');
|
setConnectionStatus('connected');
|
||||||
} catch {
|
} catch (error) {
|
||||||
|
trace?.finish?.(pingId, 'error', error);
|
||||||
|
trace?.finish?.(healthId, 'error', error);
|
||||||
connectionStatusText = '';
|
connectionStatusText = '';
|
||||||
setConnectionStatus('disconnected');
|
setConnectionStatus('disconnected');
|
||||||
} finally {
|
} finally {
|
||||||
|
trace?.finish?.(healthId);
|
||||||
connectionCheckInFlight = false;
|
connectionCheckInFlight = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function startConnectionMonitor() {
|
function startConnectionMonitor(source = 'unspecified') {
|
||||||
|
const trace = window.__SHINE_STAGE0__;
|
||||||
|
const monitorId = trace?.begin?.('monitor_start', source);
|
||||||
if (state.session.isLocalDemo) {
|
if (state.session.isLocalDemo) {
|
||||||
setConnectionStatus('connected');
|
setConnectionStatus('connected');
|
||||||
|
trace?.finish?.(monitorId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// При первой загрузке bootstrap и session_runtime могут оба запустить монитор.
|
||||||
|
// После успешного Ping второй старт не нужен. Сброс сессии и все прочие
|
||||||
|
// независимые проверки по-прежнему запускаются без подавления.
|
||||||
|
const sameInitialStartup = (source === 'bootstrap' && connectionMonitorStartSource === 'session_runtime')
|
||||||
|
|| (source === 'session_runtime' && connectionMonitorStartSource === 'bootstrap');
|
||||||
|
if (sameInitialStartup && pingIntervalId && (connectionState === 'connected' || connectionCheckInFlight)) {
|
||||||
|
trace?.finish?.(monitorId, 'deduplicated');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (pingIntervalId) {
|
if (pingIntervalId) {
|
||||||
@@ -1214,16 +1315,18 @@ function startConnectionMonitor() {
|
|||||||
pingIntervalId = null;
|
pingIntervalId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
connectionMonitorStartSource = source;
|
||||||
connectionNextRetryAtMs = Date.now() + CONNECTION_CHECK_INTERVAL_MS;
|
connectionNextRetryAtMs = Date.now() + CONNECTION_CHECK_INTERVAL_MS;
|
||||||
void checkConnectionHealth();
|
void checkConnectionHealth(source);
|
||||||
|
|
||||||
pingIntervalId = window.setInterval(() => {
|
pingIntervalId = window.setInterval(() => {
|
||||||
connectionNextRetryAtMs = Date.now() + CONNECTION_CHECK_INTERVAL_MS;
|
connectionNextRetryAtMs = Date.now() + CONNECTION_CHECK_INTERVAL_MS;
|
||||||
if (connectionState === 'disconnected') {
|
if (connectionState === 'disconnected') {
|
||||||
refreshConnectionUi();
|
refreshConnectionUi();
|
||||||
}
|
}
|
||||||
void checkConnectionHealth();
|
void checkConnectionHealth('periodic');
|
||||||
}, CONNECTION_CHECK_INTERVAL_MS);
|
}, CONNECTION_CHECK_INTERVAL_MS);
|
||||||
|
trace?.finish?.(monitorId);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isReconnectAllowedNow() {
|
function isReconnectAllowedNow() {
|
||||||
@@ -1277,6 +1380,7 @@ function resolveSignedDmChatId({ parsed, login }) {
|
|||||||
async function ensureSessionAfterWsReconnect() {
|
async function ensureSessionAfterWsReconnect() {
|
||||||
if (!state.session.isAuthorized) return true;
|
if (!state.session.isAuthorized) return true;
|
||||||
if (wsSessionRestoreInFlight) return wsSessionRestoreInFlight;
|
if (wsSessionRestoreInFlight) return wsSessionRestoreInFlight;
|
||||||
|
window.__SHINE_STAGE0__?.mark('reconnect_restore_start');
|
||||||
|
|
||||||
wsSessionRestoreInFlight = (async () => {
|
wsSessionRestoreInFlight = (async () => {
|
||||||
try {
|
try {
|
||||||
@@ -1291,8 +1395,10 @@ async function ensureSessionAfterWsReconnect() {
|
|||||||
source: 'ws-reconnect',
|
source: 'ws-reconnect',
|
||||||
message: 'Сессия восстановлена после переподключения WS',
|
message: 'Сессия восстановлена после переподключения WS',
|
||||||
});
|
});
|
||||||
|
window.__SHINE_STAGE0__?.mark('reconnect_restore_ok');
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
window.__SHINE_STAGE0__?.mark('reconnect_restore_failed');
|
||||||
if (isSessionInvalidError(error)) {
|
if (isSessionInvalidError(error)) {
|
||||||
await terminateCurrentSession({
|
await terminateCurrentSession({
|
||||||
infoMessage: 'Ваша сессия устарела. Авторизируйтесь заново.',
|
infoMessage: 'Ваша сессия устарела. Авторизируйтесь заново.',
|
||||||
@@ -1534,6 +1640,7 @@ function renderApp() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
screenEl.append(screen);
|
screenEl.append(screen);
|
||||||
|
window.__SHINE_STAGE0__?.mark('first_dom_render');
|
||||||
const pageCleanup = typeof screen.cleanup === 'function' ? screen.cleanup : null;
|
const pageCleanup = typeof screen.cleanup === 'function' ? screen.cleanup : null;
|
||||||
const scrollToBottomControl = attachPageScrollToBottom(pageId, screen);
|
const scrollToBottomControl = attachPageScrollToBottom(pageId, screen);
|
||||||
currentCleanup = () => {
|
currentCleanup = () => {
|
||||||
@@ -1575,16 +1682,19 @@ function refreshUnreadUi() {
|
|||||||
async function tryAutoLogin() {
|
async function tryAutoLogin() {
|
||||||
if (state.session.isLocalDemo) return;
|
if (state.session.isLocalDemo) return;
|
||||||
if (!state.session.login || !state.session.sessionId) return;
|
if (!state.session.login || !state.session.sessionId) return;
|
||||||
|
window.__SHINE_STAGE0__?.mark('session_restore_start');
|
||||||
try {
|
try {
|
||||||
await authService.reconnect(state.entrySettings.shineServer);
|
await authService.reconnect(state.entrySettings.shineServer);
|
||||||
const resumed = await authService.resumeSession(state.session.login, state.session.sessionId);
|
const resumed = await authService.resumeSession(state.session.login, state.session.sessionId);
|
||||||
authorizeSession(resumed);
|
authorizeSession(resumed);
|
||||||
|
window.__SHINE_STAGE0__?.mark('session_restore_ok');
|
||||||
await refreshSessions();
|
await refreshSessions();
|
||||||
try {
|
try {
|
||||||
const contacts = await authService.listContacts();
|
const contacts = await authService.listContacts();
|
||||||
setContacts(contacts.contacts || []);
|
setContacts(contacts.contacts || []);
|
||||||
} catch {}
|
} catch {}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
window.__SHINE_STAGE0__?.mark('session_restore_failed');
|
||||||
if (isSessionInvalidError(error)) {
|
if (isSessionInvalidError(error)) {
|
||||||
const result = await closeSavedProfile(state.session.login);
|
const result = await closeSavedProfile(state.session.login);
|
||||||
if (result?.nextProfile) {
|
if (result?.nextProfile) {
|
||||||
@@ -1610,7 +1720,7 @@ async function ensureSessionRuntimeStarted() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
startConnectionMonitor();
|
startConnectionMonitor('session_runtime');
|
||||||
startChannelsPrefetch();
|
startChannelsPrefetch();
|
||||||
|
|
||||||
if (reconnectIntervalId) {
|
if (reconnectIntervalId) {
|
||||||
@@ -1664,7 +1774,7 @@ async function init() {
|
|||||||
setSessionResetHandler(() => {
|
setSessionResetHandler(() => {
|
||||||
sessionRuntimeStarted = false;
|
sessionRuntimeStarted = false;
|
||||||
stopChannelsPrefetch();
|
stopChannelsPrefetch();
|
||||||
startConnectionMonitor();
|
startConnectionMonitor('session_reset');
|
||||||
clearKeepAliveEntries();
|
clearKeepAliveEntries();
|
||||||
if (reconnectIntervalId) {
|
if (reconnectIntervalId) {
|
||||||
window.clearInterval(reconnectIntervalId);
|
window.clearInterval(reconnectIntervalId);
|
||||||
@@ -2068,7 +2178,7 @@ async function init() {
|
|||||||
}
|
}
|
||||||
await hydrateMessagesFromStore();
|
await hydrateMessagesFromStore();
|
||||||
if (!state.session.isLocalDemo) {
|
if (!state.session.isLocalDemo) {
|
||||||
startConnectionMonitor();
|
startConnectionMonitor('bootstrap');
|
||||||
startPeriodicUiVersionCheck();
|
startPeriodicUiVersionCheck();
|
||||||
}
|
}
|
||||||
await ensureSessionRuntimeStarted();
|
await ensureSessionRuntimeStarted();
|
||||||
@@ -2090,7 +2200,7 @@ async function init() {
|
|||||||
document.addEventListener('visibilitychange', () => {
|
document.addEventListener('visibilitychange', () => {
|
||||||
if (document.visibilityState !== 'visible') return;
|
if (document.visibilityState !== 'visible') return;
|
||||||
void tryLockPortraitOrientation();
|
void tryLockPortraitOrientation();
|
||||||
void checkConnectionHealth();
|
void checkConnectionHealth('visibility');
|
||||||
});
|
});
|
||||||
window.addEventListener('orientationchange', () => {
|
window.addEventListener('orientationchange', () => {
|
||||||
void tryLockPortraitOrientation();
|
void tryLockPortraitOrientation();
|
||||||
|
|||||||
@@ -79,14 +79,17 @@ export class WsJsonClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.openPromise = new Promise((resolve, reject) => {
|
this.openPromise = new Promise((resolve, reject) => {
|
||||||
|
window.__SHINE_STAGE0__?.mark('ws_attempt');
|
||||||
const ws = new WebSocket(this.url);
|
const ws = new WebSocket(this.url);
|
||||||
this.ws = ws;
|
this.ws = ws;
|
||||||
|
|
||||||
ws.addEventListener('open', () => {
|
ws.addEventListener('open', () => {
|
||||||
|
window.__SHINE_STAGE0__?.mark('ws_open');
|
||||||
resolve();
|
resolve();
|
||||||
}, { once: true });
|
}, { once: true });
|
||||||
|
|
||||||
ws.addEventListener('error', () => {
|
ws.addEventListener('error', () => {
|
||||||
|
window.__SHINE_STAGE0__?.mark('ws_error');
|
||||||
captureClientError({
|
captureClientError({
|
||||||
kind: 'ws_open_error',
|
kind: 'ws_open_error',
|
||||||
message: `Failed to connect WebSocket ${this.url}`,
|
message: `Failed to connect WebSocket ${this.url}`,
|
||||||
@@ -96,6 +99,7 @@ export class WsJsonClient {
|
|||||||
}, { once: true });
|
}, { once: true });
|
||||||
|
|
||||||
ws.addEventListener('close', () => {
|
ws.addEventListener('close', () => {
|
||||||
|
window.__SHINE_STAGE0__?.mark('ws_close');
|
||||||
this.failPending('Соединение WebSocket закрыто');
|
this.failPending('Соединение WebSocket закрыто');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,350 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { runInNewContext } from 'node:vm';
|
||||||
|
|
||||||
|
const html = readFileSync(new URL('../index.html', import.meta.url), 'utf8');
|
||||||
|
const app = readFileSync(new URL('../js/app.js', import.meta.url), 'utf8');
|
||||||
|
const diagnosticScript = html.match(/<script id="shine-stage0-startup-diagnostics">([\s\S]*?)<\/script>/)?.[1];
|
||||||
|
assert.ok(diagnosticScript, 'Must extend the original inline Stage 0 diagnostic; no extra scripts');
|
||||||
|
|
||||||
|
export function diagnosticHarness(debug = '1') {
|
||||||
|
const marks = [];
|
||||||
|
let time = 100;
|
||||||
|
const performance = {
|
||||||
|
now: () => { time += 0.7; return time; },
|
||||||
|
mark: (name) => marks.push(name),
|
||||||
|
getEntriesByType: () => [],
|
||||||
|
};
|
||||||
|
const window = { performance };
|
||||||
|
runInNewContext(diagnosticScript, {
|
||||||
|
window, performance,
|
||||||
|
localStorage: { getItem: () => debug },
|
||||||
|
document: { addEventListener() {} },
|
||||||
|
fetch() { throw Error('Unexpected fetch by diagnostic'); },
|
||||||
|
WebSocket: class { constructor() { throw Error('Unexpected socket by diagnostic'); } },
|
||||||
|
setTimeout() { throw Error('Unexpected timeout by diagnostic'); },
|
||||||
|
setInterval() { throw Error('Unexpected interval by diagnostic'); },
|
||||||
|
});
|
||||||
|
return { trace: window.__SHINE_STAGE0__, exportData: () => JSON.parse(window.__SHINE_STAGE0_EXPORT__()), marks, window };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standalone source slices from the real app, without imports or network access.
|
||||||
|
// Preserves actual function bodies so these are not reimplementations of Ping/Splash.
|
||||||
|
const functionSlices = [
|
||||||
|
['function finishInitialConnectionSplash()', 'function startConnectionCountdown()'],
|
||||||
|
['function setConnectionStatus(', 'async function triggerImmediateConnectionRetry()'],
|
||||||
|
['function extractBuildHashFromHtml(', 'function startPeriodicUiVersionCheck()'],
|
||||||
|
['async function checkConnectionHealth(', 'function startConnectionMonitor('],
|
||||||
|
];
|
||||||
|
export function extractSplashChain(source = app) {
|
||||||
|
return functionSlices.map(([start, stop]) => {
|
||||||
|
const from = source.indexOf(start);
|
||||||
|
const until = source.indexOf(stop, from + start.length);
|
||||||
|
assert.ok(from !== -1 && until > from, `Missing source slice: ${start}`);
|
||||||
|
return source.slice(from, until);
|
||||||
|
}).join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function appHarness({ source = app, debug = true, sw = 'one', pingError = null, remoteHash = 'same', hostHash = 'same', wsOpen = true, awaitUpdate = false, awaitPing = false, fetchOk = true } = {}) {
|
||||||
|
const log = [];
|
||||||
|
const timers = [];
|
||||||
|
const eventHandlers = new Map();
|
||||||
|
const { window, exportData } = debug ? diagnosticHarness() : { window: {}, exportData: () => null };
|
||||||
|
let resolvePing;
|
||||||
|
const pingGate = awaitPing ? new Promise(resolve => { resolvePing = resolve; }) : null;
|
||||||
|
let isWsOpen = wsOpen;
|
||||||
|
let resolveUpdate;
|
||||||
|
const updateGate = awaitUpdate ? new Promise(resolve => { resolveUpdate = resolve; }) : null;
|
||||||
|
const element = {
|
||||||
|
classList: { add: (...args) => log.push(['splash-class', ...args]) },
|
||||||
|
addEventListener: (name, callback) => {
|
||||||
|
log.push(['listener', name]);
|
||||||
|
eventHandlers.set(name, callback);
|
||||||
|
},
|
||||||
|
remove: () => log.push(['splash-remove']),
|
||||||
|
};
|
||||||
|
const serviceWorker = sw === 'none' ? undefined : {
|
||||||
|
getRegistrations: async () => {
|
||||||
|
log.push(['sw-list']);
|
||||||
|
if (sw === 'list-error') throw Object.assign(new Error('TOP_SECRET'), { name: 'SecurityError' });
|
||||||
|
return sw === 'empty' ? [] : [
|
||||||
|
{ update: async () => {
|
||||||
|
log.push(['sw-update']);
|
||||||
|
if (updateGate) await updateGate;
|
||||||
|
if (sw === 'update-error') throw Object.assign(new Error('TOKEN_PII'), { name: 'NetworkError' });
|
||||||
|
}, waiting: sw === 'waiting' ? { postMessage(value) { log.push(['sw-post-message', value.type]); } } : null },
|
||||||
|
];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const navigator = sw === 'none' ? {} : { serviceWorker };
|
||||||
|
window.setTimeout = (fn, ms) => { log.push(['timeout', ms]); timers.push(fn); };
|
||||||
|
window.location = { reload() { log.push(['reload']); } };
|
||||||
|
const context = {
|
||||||
|
window,
|
||||||
|
navigator, initialSplashEl: element, initialConnectionCompleted: false,
|
||||||
|
connectionState: '', connectionStatusText: '', connectionNextRetryAtMs: 0,
|
||||||
|
CONNECTION_CHECK_INTERVAL_MS: 20000,
|
||||||
|
connectionCheckInFlight: false, uiVersionCheckInFlight: false, pwaUpdateCheckAttempted: false,
|
||||||
|
uiUpdateReloadScheduled: false,
|
||||||
|
state: { session: { isLocalDemo: false } },
|
||||||
|
wsIsOpen: () => isWsOpen,
|
||||||
|
authService: { ws: {
|
||||||
|
async open() { log.push(['ws-open']); isWsOpen = true; },
|
||||||
|
async request(op) { log.push(['request', op]); if (pingGate) await pingGate; if (pingError) throw pingError; return { uiBuildHash: remoteHash }; },
|
||||||
|
} },
|
||||||
|
ensureSessionAfterWsReconnect: async () => { log.push(['reconnect-restore']); return true; },
|
||||||
|
stopConnectionCountdown: () => log.push(['stop-countdown']),
|
||||||
|
startConnectionCountdown: () => log.push(['start-countdown']),
|
||||||
|
refreshConnectionUi: () => log.push(['refresh-connection-ui']),
|
||||||
|
CURRENT_BUILD_HASH: 'same', UI_BUILD_HASH_PATTERN: /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/,
|
||||||
|
fetch: async () => { log.push(['version-fetch']); return { ok: fetchOk, async text() { return `window.__SHINE_BUILD_HASH__ = '${hostHash}'`; } }; },
|
||||||
|
addAppLogEntry: () => log.push(['log-entry']),
|
||||||
|
};
|
||||||
|
runInNewContext(extractSplashChain(source), context);
|
||||||
|
return {
|
||||||
|
context, log, timers, resolveUpdate, resolvePing, exportData, eventHandlers,
|
||||||
|
setWsOpen(value) { isWsOpen = value; },
|
||||||
|
async run() { await runInNewContext('checkConnectionHealth()', context); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('Stage 0 keeps its export and Stage 0.1 adds bounded, paired operation measurements', () => {
|
||||||
|
const { trace, exportData, marks } = diagnosticHarness();
|
||||||
|
trace.mark('first_dom_render');
|
||||||
|
const ping = trace.begin('ping');
|
||||||
|
assert.equal(exportData().splashTrace.operations[0].durationMs, null);
|
||||||
|
assert.equal(exportData().splashTrace.operations[0].outcome, 'pending');
|
||||||
|
trace.finish(ping);
|
||||||
|
trace.mark('splash_leave');
|
||||||
|
const exported = exportData();
|
||||||
|
assert.equal(exported.schema, 'shine-stage0-v1');
|
||||||
|
assert.ok(exported.timing.first_dom_render);
|
||||||
|
assert.ok(exported.durations.renderToSplashLeaveMs > 0);
|
||||||
|
assert.ok(exported.splashTrace.operations[0].durationMs > 0);
|
||||||
|
assert.equal(exported.splashTrace.operations[0].outcome, 'ok');
|
||||||
|
assert.ok(marks.includes('shine-stage0:ping:start'));
|
||||||
|
assert.ok(marks.includes('shine-stage0:ping:end'));
|
||||||
|
assert.equal(exported.counters.pingStarted, 1);
|
||||||
|
assert.equal(exported.counters.pingCompleted, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Absent operations are missing rather than a zero-duration SW/version/ping measurement', () => {
|
||||||
|
const { exportData } = diagnosticHarness();
|
||||||
|
const result = exportData();
|
||||||
|
assert.deepEqual(result.splashTrace.operations, []);
|
||||||
|
assert.equal(result.durations.splashTransitionToRemovalMs, null);
|
||||||
|
assert.equal(result.counters.pingStarted, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Untrusted strings, error messages, URLs and tokens cannot enter diagnostic JSON', () => {
|
||||||
|
const { trace, exportData } = diagnosticHarness();
|
||||||
|
trace.mark('SECRET_URL_TOKEN');
|
||||||
|
assert.equal(trace.begin('SECRET_URL_TOKEN'), null);
|
||||||
|
const id = trace.begin('sw_registration_update');
|
||||||
|
trace.finish(id, 'error', { name: 'TokenBearerSECRET', message: 'https://secret/?sessionId=abc' });
|
||||||
|
const errId = trace.begin('ping');
|
||||||
|
trace.finish(errId, 'error', { name: 'SecurityError', payload: { token: 'SECRET' } });
|
||||||
|
const json = JSON.stringify(exportData());
|
||||||
|
assert.doesNotMatch(json, /SECRET|https?:|sessionId|token/);
|
||||||
|
assert.equal(exportData().splashTrace.operations[0].errorType, 'UnknownError');
|
||||||
|
assert.equal(exportData().splashTrace.operations[1].errorType, 'SecurityError');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Interleaved registration updates match their own start/end, not FIFO completion', () => {
|
||||||
|
const { trace, exportData } = diagnosticHarness();
|
||||||
|
const a = trace.begin('sw_registration_update');
|
||||||
|
const b = trace.begin('sw_registration_update');
|
||||||
|
trace.finish(b);
|
||||||
|
trace.finish(a, 'error', { name: 'NetworkError', message: 'PRIVATE' });
|
||||||
|
const [first, second] = exportData().splashTrace.operations;
|
||||||
|
assert.ok(first.durationMs > second.durationMs);
|
||||||
|
assert.equal(first.outcome, 'error');
|
||||||
|
assert.equal(first.errorType, 'NetworkError');
|
||||||
|
assert.equal(second.outcome, 'ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Operation cap bounds memory; Stage 0 event cap and original export still work', () => {
|
||||||
|
const { trace, exportData } = diagnosticHarness();
|
||||||
|
for (let i = 0; i < 300; i++) {
|
||||||
|
const id = trace.begin('ping');
|
||||||
|
trace.finish(id);
|
||||||
|
}
|
||||||
|
for (let i = 0; i < 300; i++) trace.mark('ws_attempt');
|
||||||
|
const result = exportData();
|
||||||
|
assert.equal(result.splashTrace.operations.length, 256);
|
||||||
|
assert.equal(result.counters.operationsDropped, 44);
|
||||||
|
assert.equal(result.counters.wsAttempts, 300);
|
||||||
|
assert.equal(result.events.length, 256);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Successful Ping connects and starts Splash before the existing SW update finishes', async () => {
|
||||||
|
const h = appHarness({ awaitUpdate: true });
|
||||||
|
await h.run();
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
assert.deepEqual(h.log.filter(([name]) => name === 'request').map(([, op]) => op), ['Ping']);
|
||||||
|
assert.equal(h.log.filter(([name]) => name === 'splash-class').length, 1);
|
||||||
|
assert.equal(h.timers.length, 1);
|
||||||
|
const stages = h.exportData().events.map(({ stage }) => stage);
|
||||||
|
assert.ok(stages.indexOf('status_connected') < stages.indexOf('splash_finish_called'));
|
||||||
|
assert.ok(stages.indexOf('splash_finish_called') < stages.indexOf('splash_leave'));
|
||||||
|
const ops = h.exportData().splashTrace.operations;
|
||||||
|
const ping = ops.find(op => op.operation === 'ping');
|
||||||
|
const pwa = ops.find(op => op.operation === 'pwa_first_ping_update');
|
||||||
|
assert.equal(ping.outcome, 'ok');
|
||||||
|
assert.equal(pwa.outcome, 'pending');
|
||||||
|
assert.ok(ping.endMs <= pwa.startMs);
|
||||||
|
assert.equal(ops.find(op => op.operation === 'sw_registration_update').endMs, null);
|
||||||
|
h.resolveUpdate();
|
||||||
|
for (let i = 0; i < 12; i++) await Promise.resolve();
|
||||||
|
const finished = h.exportData().splashTrace.operations.find(op => op.operation === 'pwa_first_ping_update');
|
||||||
|
assert.equal(finished.outcome, 'ok');
|
||||||
|
assert.ok(h.exportData().timing.status_connected < finished.endMs);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('CSS transitionstart is measured independently; timeout removal retains original timer', async () => {
|
||||||
|
const h = appHarness();
|
||||||
|
await h.run();
|
||||||
|
const stageBefore = h.exportData();
|
||||||
|
assert.ok(stageBefore.timing.splash_leave);
|
||||||
|
assert.equal(stageBefore.timing.splash_transition_start, undefined);
|
||||||
|
const handler = h.eventHandlers.get('transitionstart');
|
||||||
|
assert.equal(typeof handler, 'function');
|
||||||
|
handler({ target: {}, propertyName: 'opacity' });
|
||||||
|
assert.equal(h.exportData().timing.splash_transition_start, undefined);
|
||||||
|
handler({ target: h.context.initialSplashEl, propertyName: 'opacity' });
|
||||||
|
assert.ok(h.exportData().timing.splash_transition_start);
|
||||||
|
h.timers[0]();
|
||||||
|
const result = h.exportData();
|
||||||
|
assert.ok(result.timing.splash_removed);
|
||||||
|
assert.ok(result.timing.splash_removed_via_timeout);
|
||||||
|
assert.equal(result.timing.splash_removed_via_transition, undefined);
|
||||||
|
assert.equal(h.log.filter(([name]) => name === 'splash-remove').length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('No SW support: no SW operations; Ping and Splash still run', async () => {
|
||||||
|
const h = appHarness({ sw: 'none' });
|
||||||
|
await h.run();
|
||||||
|
assert.equal(h.log.filter(([name]) => name === 'sw-list').length, 0);
|
||||||
|
assert.equal(h.log.filter(([name]) => name === 'request').length, 1);
|
||||||
|
assert.ok(!h.exportData().splashTrace.operations.some(op => op.operation.startsWith('sw_')));
|
||||||
|
assert.ok(h.exportData().splashTrace.operations.some(op => op.operation === 'pwa_first_ping_update'));
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Ping failure records a safe type and does not start PWA update or Splash', async () => {
|
||||||
|
const err = Object.assign(new Error('secret token'), { name: 'NetworkError' });
|
||||||
|
const h = appHarness({ pingError: err });
|
||||||
|
await h.run();
|
||||||
|
const ops = h.exportData().splashTrace.operations;
|
||||||
|
assert.equal(ops.find(op => op.operation === 'ping').errorType, 'NetworkError');
|
||||||
|
assert.equal(ops.find(op => op.operation === 'connection_health').outcome, 'error');
|
||||||
|
assert.ok(!ops.some(op => op.operation.startsWith('sw_') || op.operation === 'pwa_first_ping_update'));
|
||||||
|
assert.equal(h.context.connectionState, 'disconnected');
|
||||||
|
assert.equal(h.log.some(([name]) => name === 'splash-class'), false);
|
||||||
|
assert.doesNotMatch(JSON.stringify(h.exportData()), /secret token/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Existing SW errors are swallowed as before, but have a safe error class', async () => {
|
||||||
|
const h = appHarness({ sw: 'update-error' });
|
||||||
|
await h.run();
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
const update = h.exportData().splashTrace.operations.find(op => op.operation === 'sw_registration_update');
|
||||||
|
assert.equal(update.outcome, 'error');
|
||||||
|
assert.equal(update.errorType, 'NetworkError');
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('UI version check only exists on differing Ping hashes and never blocks connected status', async () => {
|
||||||
|
const h = appHarness({ remoteHash: 'other' });
|
||||||
|
await h.run();
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
const ops = h.exportData().splashTrace.operations;
|
||||||
|
assert.ok(ops.some(op => op.operation === 'ui_version_ping' && op.outcome === 'ok'));
|
||||||
|
assert.ok(ops.some(op => op.operation === 'ui_version_fetch' && op.outcome === 'ok'));
|
||||||
|
assert.equal(h.log.filter(([name]) => name === 'version-fetch').length, 1);
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
const ordinary = appHarness({ remoteHash: 'same' });
|
||||||
|
await ordinary.run();
|
||||||
|
assert.equal(ordinary.log.filter(([name]) => name === 'version-fetch').length, 0);
|
||||||
|
assert.ok(!ordinary.exportData().splashTrace.operations.some(op => op.operation.startsWith('ui_version')));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Stage 0.1 only uses the existing inline module, no new Ping/WS/fetch/timers in the measurement layer', () => {
|
||||||
|
assert.doesNotMatch(diagnosticScript, /new WebSocket|\.send\(|\bfetch\(|\.request\(|setTimeout|setInterval|\.postMessage\(|\.register\(/);
|
||||||
|
assert.doesNotMatch(diagnosticScript, /\.url|\.message|\.payload|\.sessionId/);
|
||||||
|
assert.match(app, /const pingResp = await authService\.ws\.request\('Ping', \{ ts: Date\.now\(\) \}, 7000\)/);
|
||||||
|
assert.match(app, /window\.setTimeout\(removeSplash, 700\)/);
|
||||||
|
assert.match(app, /void tryUpdatePwaOnFirstConnectedPing\(\)\.catch\(/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Repeated health invocation during a pending Ping adds no second Ping or SW update', async () => {
|
||||||
|
const h = appHarness({ awaitPing: true });
|
||||||
|
const first = h.run();
|
||||||
|
for (let i = 0; i < 12; i++) await Promise.resolve();
|
||||||
|
await h.run();
|
||||||
|
assert.equal(h.log.filter(([name, op]) => name === 'request' && op === 'Ping').length, 1);
|
||||||
|
assert.equal(h.exportData().events.filter(e => e.stage === 'health_skipped_inflight').length, 1);
|
||||||
|
h.resolvePing();
|
||||||
|
await first;
|
||||||
|
for (let i = 0; i < 5; i++) await Promise.resolve();
|
||||||
|
assert.equal(h.log.filter(([name]) => name === 'sw-update').length, 1);
|
||||||
|
assert.equal(h.exportData().splashTrace.operations.filter(op => op.operation === 'connection_health').length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Local demo records health invocation but must not run Ping, SW refresh or PWA update', async () => {
|
||||||
|
const h = appHarness();
|
||||||
|
h.context.state.session.isLocalDemo = true;
|
||||||
|
await h.run();
|
||||||
|
assert.equal(h.log.filter(([name]) => name === 'request' || name.startsWith('sw-')).length, 0);
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
const result = h.exportData();
|
||||||
|
assert.ok(result.events.some(e => e.stage === 'health_local_demo'));
|
||||||
|
assert.equal(result.splashTrace.operations.filter(op => op.operation === 'connection_health').length, 1);
|
||||||
|
assert.equal(result.splashTrace.operations.filter(op => op.operation === 'ping').length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Stage 0.1 calls remain safe if cached Stage 0 bootstrap lacks begin/finish methods', async () => {
|
||||||
|
const h = appHarness({ debug: false });
|
||||||
|
h.context.window.__SHINE_STAGE0__ = { mark() {} };
|
||||||
|
await h.run();
|
||||||
|
assert.equal(h.log.filter(([name, op]) => name === 'request' && op === 'Ping').length, 1);
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
assert.equal(h.timers.length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Transitionend removal records source once even if the existing timeout later fires', async () => {
|
||||||
|
const h = appHarness();
|
||||||
|
await h.run();
|
||||||
|
h.eventHandlers.get('transitionend')({ type: 'transitionend', target: h.context.initialSplashEl });
|
||||||
|
assert.ok(h.exportData().timing.splash_removed_via_transition);
|
||||||
|
h.timers[0]();
|
||||||
|
assert.equal(h.exportData().timing.splash_removed_via_timeout, undefined);
|
||||||
|
assert.equal(h.exportData().events.filter(e => e.stage === 'splash_removed').length, 1);
|
||||||
|
// The original code also invokes remove() twice; this diagnostic does not prevent it.
|
||||||
|
assert.equal(h.log.filter(([name]) => name === 'splash-remove').length, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('A non-OK UI version probe has a fixed, non-sensitive error type, while connected remains unchanged', async () => {
|
||||||
|
const h = appHarness({ remoteHash: 'other', fetchOk: false });
|
||||||
|
await h.run();
|
||||||
|
for (let i = 0; i < 4; i++) await Promise.resolve();
|
||||||
|
const probe = h.exportData().splashTrace.operations.find(op => op.operation === 'ui_version_fetch');
|
||||||
|
assert.equal(probe.outcome, 'error');
|
||||||
|
assert.equal(probe.errorType, 'HttpResponseNotOk');
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('SW waiting.postMessage trace is absent during the first Ping and measured on existing reload path', async () => {
|
||||||
|
const h = appHarness({ sw: 'waiting' });
|
||||||
|
await h.run();
|
||||||
|
assert.equal(h.log.filter(([name]) => name === 'sw-post-message').length, 0);
|
||||||
|
assert.equal(h.exportData().splashTrace.operations.filter(op => op.operation === 'sw_skip_waiting').length, 0);
|
||||||
|
await runInNewContext('refreshServiceWorkers({ activateWaitingWorker: true })', h.context);
|
||||||
|
assert.equal(h.log.filter(([name]) => name === 'sw-post-message').length, 1);
|
||||||
|
const result = h.exportData();
|
||||||
|
const posted = result.splashTrace.operations.find(op => op.operation === 'sw_skip_waiting');
|
||||||
|
assert.equal(posted.outcome, 'ok');
|
||||||
|
assert.equal(posted.context, 'reload');
|
||||||
|
assert.equal(result.splashTrace.operations.find(op => op.operation === 'sw_refresh').context, 'first_ping');
|
||||||
|
});
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { runInNewContext } from 'node:vm';
|
||||||
|
|
||||||
|
const html = readFileSync(new URL('../index.html', import.meta.url), 'utf8');
|
||||||
|
const block = html.match(/<script id="shine-stage0-startup-diagnostics">([\s\S]*?)<\/script>/);
|
||||||
|
assert.ok(block, 'Диагностический загрузчик должен быть встроен без нового сетевого запроса');
|
||||||
|
const script = block[1];
|
||||||
|
|
||||||
|
function createHarness(flag) {
|
||||||
|
const listeners = new Map();
|
||||||
|
const marks = [];
|
||||||
|
let tick = 10;
|
||||||
|
const performance = {
|
||||||
|
mark: (name) => marks.push(name),
|
||||||
|
now: () => ++tick,
|
||||||
|
getEntriesByType: (type) => type === 'navigation'
|
||||||
|
? [{ domContentLoadedEventEnd: 120 }]
|
||||||
|
: type === 'paint' ? [{ name: 'first-contentful-paint', startTime: 240 }] : [],
|
||||||
|
};
|
||||||
|
const window = { performance };
|
||||||
|
const sandbox = {
|
||||||
|
window, performance,
|
||||||
|
localStorage: { getItem(key) { assert.equal(key, 'shine-feature-developer-tools-v1'); return flag; } },
|
||||||
|
document: { addEventListener(event, handler) { listeners.set(event, handler); } },
|
||||||
|
WebSocket: class { constructor() { throw Error('не должен создаваться'); } },
|
||||||
|
setInterval() { throw Error('не должен запускаться интервал'); },
|
||||||
|
setTimeout() { throw Error('не должен запускаться таймер'); },
|
||||||
|
};
|
||||||
|
runInNewContext(script, sandbox);
|
||||||
|
return { window, listeners, marks };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('без debug флага нет активного измерителя, экспорта и побочных действий', () => {
|
||||||
|
for (const flag of [null, '0', 'false', '']) {
|
||||||
|
const { window, listeners, marks } = createHarness(flag);
|
||||||
|
assert.equal(window.__SHINE_STAGE0__, undefined);
|
||||||
|
assert.equal(window.__SHINE_STAGE0_EXPORT__, undefined);
|
||||||
|
assert.equal(listeners.size, 0);
|
||||||
|
assert.equal(marks.length, 0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('в debug режиме фиксируются Performance marks и DOM ready, экспорт является валидным JSON', () => {
|
||||||
|
const { window, listeners, marks } = createHarness('1');
|
||||||
|
assert.equal(typeof window.__SHINE_STAGE0_EXPORT__, 'function');
|
||||||
|
assert.ok(marks.includes('shine-stage0:bootstrap'));
|
||||||
|
listeners.get('DOMContentLoaded')();
|
||||||
|
window.__SHINE_STAGE0__.mark('css_start');
|
||||||
|
window.__SHINE_STAGE0__.mark('css_ok');
|
||||||
|
window.__SHINE_STAGE0__.mark('css_error');
|
||||||
|
window.__SHINE_STAGE0__.mark('css_complete');
|
||||||
|
window.__SHINE_STAGE0__.mark('ws_attempt');
|
||||||
|
window.__SHINE_STAGE0__.mark('ws_attempt');
|
||||||
|
window.__SHINE_STAGE0__.mark('ws_open');
|
||||||
|
window.__SHINE_STAGE0__.mark('first_dom_render');
|
||||||
|
window.__SHINE_STAGE0__.mark('session_restore_start');
|
||||||
|
window.__SHINE_STAGE0__.mark('session_restore_ok');
|
||||||
|
const result = JSON.parse(window.__SHINE_STAGE0_EXPORT__());
|
||||||
|
assert.equal(result.schema, 'shine-stage0-v1');
|
||||||
|
assert.equal(result.counters.cssLoaded, 1);
|
||||||
|
assert.equal(result.counters.cssFailed, 1);
|
||||||
|
assert.equal(result.counters.wsAttempts, 2);
|
||||||
|
assert.equal(result.counters.wsAttemptsAfterFirst, 1);
|
||||||
|
assert.equal(result.counters.wsOpened, 1);
|
||||||
|
assert.equal(result.browser.domContentLoadedMs, 120);
|
||||||
|
assert.equal(result.browser.firstContentfulPaintMs, 240);
|
||||||
|
assert.ok(result.durations.cssAllSettledMs > 0);
|
||||||
|
assert.ok(result.events.every((e) => /^[-a-z_]+$/.test(e.stage) && Number.isFinite(e.atMs)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('метрики не принимают секреты, произвольные этапы или повторные однократные события', () => {
|
||||||
|
const { window, marks } = createHarness('true');
|
||||||
|
const token = 'SECRET_token_sessionId_login_url';
|
||||||
|
window.__SHINE_STAGE0__.mark(token);
|
||||||
|
window.__SHINE_STAGE0__.mark('bootstrap');
|
||||||
|
window.__SHINE_STAGE0__.mark('ws_error');
|
||||||
|
window.__SHINE_STAGE0__.mark('ws_error');
|
||||||
|
const json = window.__SHINE_STAGE0_EXPORT__();
|
||||||
|
assert.ok(!json.includes(token));
|
||||||
|
assert.equal(marks.filter((name) => name === 'shine-stage0:bootstrap').length, 1);
|
||||||
|
assert.equal(JSON.parse(json).counters.wsOpenErrors, 2);
|
||||||
|
assert.ok(!/wss?:\/\//.test(json));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ограничен объём событий, счётчики продолжают учитывать попытки без URL', () => {
|
||||||
|
const { window, marks } = createHarness('1');
|
||||||
|
for (let i = 0; i < 500; i++) window.__SHINE_STAGE0__.mark('ws_attempt');
|
||||||
|
const result = JSON.parse(window.__SHINE_STAGE0_EXPORT__());
|
||||||
|
assert.equal(result.counters.wsAttempts, 500);
|
||||||
|
assert.ok(result.events.length <= 256);
|
||||||
|
assert.ok(marks.length <= 256);
|
||||||
|
assert.equal(result.counters.eventsDropped, 245);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('инструмент не подменяет WebSocket, fetch, Push, роуты, Ping и не запускает таймеры', () => {
|
||||||
|
assert.doesNotMatch(script, /new WebSocket|\.send\(|\bfetch\(|serviceWorker|setTimeout|setInterval|pushManager|location\.assign/);
|
||||||
|
assert.doesNotMatch(script, /sessionId|storagePwd|password|token|requestId|authorization|\.url/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('после успешного resume ошибка последующего запроса не маркируется ошибкой восстановления', () => {
|
||||||
|
const { window } = createHarness('1');
|
||||||
|
window.__SHINE_STAGE0__.mark('session_restore_start');
|
||||||
|
window.__SHINE_STAGE0__.mark('session_restore_ok');
|
||||||
|
window.__SHINE_STAGE0__.mark('session_restore_failed');
|
||||||
|
const result = JSON.parse(window.__SHINE_STAGE0_EXPORT__());
|
||||||
|
assert.equal(result.counters.sessionRestoreFailures, 0);
|
||||||
|
assert.equal(result.durations.sessionRestoreMs, 1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { runInNewContext } from 'node:vm';
|
||||||
|
|
||||||
|
const appSource = readFileSync(new URL('../js/app.js', import.meta.url), 'utf8');
|
||||||
|
const html = readFileSync(new URL('../index.html', import.meta.url), 'utf8');
|
||||||
|
const diagnosticScript = html.match(/<script id="shine-stage0-startup-diagnostics">([\s\S]*?)<\/script>/)?.[1];
|
||||||
|
assert.ok(diagnosticScript);
|
||||||
|
|
||||||
|
// Реальные тела функций берутся из app.js; сетевые и DOM-операции заменены контролируемыми стендами.
|
||||||
|
const slices = [
|
||||||
|
['function finishInitialConnectionSplash()', 'function startConnectionCountdown()'],
|
||||||
|
['function setConnectionStatus(', 'async function triggerImmediateConnectionRetry()'],
|
||||||
|
['function extractBuildHashFromHtml(', 'function startPeriodicUiVersionCheck()'],
|
||||||
|
['async function checkConnectionHealth(', 'function startConnectionMonitor('],
|
||||||
|
];
|
||||||
|
function splashChain(source) {
|
||||||
|
return slices.map(([start, end]) => {
|
||||||
|
const from = source.indexOf(start);
|
||||||
|
const to = source.indexOf(end, from + start.length);
|
||||||
|
assert.ok(from >= 0 && to > from, `Не удалось извлечь ${start}`);
|
||||||
|
return source.slice(from, to);
|
||||||
|
}).join('\n');
|
||||||
|
}
|
||||||
|
function deferred() {
|
||||||
|
let resolve;
|
||||||
|
const promise = new Promise(r => { resolve = r; });
|
||||||
|
return { promise, resolve };
|
||||||
|
}
|
||||||
|
const settle = () => new Promise(resolve => setImmediate(resolve));
|
||||||
|
|
||||||
|
function harness({ source = appSource, slowSw = false, swError = false, swSupported = true,
|
||||||
|
initiallyConnected = true, remoteHash = 'same', hostHash = 'same' } = {}) {
|
||||||
|
let now = 10;
|
||||||
|
const performance = { now: () => ++now, mark() {}, getEntriesByType: () => [] };
|
||||||
|
const window = { performance };
|
||||||
|
runInNewContext(diagnosticScript, {
|
||||||
|
window, performance,
|
||||||
|
localStorage: { getItem: () => '1' }, document: { addEventListener() {} },
|
||||||
|
});
|
||||||
|
const log = [];
|
||||||
|
const pendingUpdate = slowSw ? deferred() : null;
|
||||||
|
let open = initiallyConnected;
|
||||||
|
let rejectNextPing = false;
|
||||||
|
const timers = [];
|
||||||
|
const splash = {
|
||||||
|
classList: { add(value) { log.push(['splash-class', value]); } },
|
||||||
|
addEventListener(event) { log.push(['splash-listener', event]); },
|
||||||
|
remove() { log.push(['splash-remove']); },
|
||||||
|
};
|
||||||
|
const registration = {
|
||||||
|
waiting: { postMessage(value) { log.push(['sw-message', value.type]); } },
|
||||||
|
async update() {
|
||||||
|
log.push(['sw-update']);
|
||||||
|
if (pendingUpdate) await pendingUpdate.promise;
|
||||||
|
if (swError) throw Object.assign(new Error('secret token'), { name: 'NetworkError' });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const navigator = swSupported ? {
|
||||||
|
serviceWorker: { async getRegistrations() { log.push(['sw-list']); return [registration]; } },
|
||||||
|
} : {};
|
||||||
|
window.setTimeout = (callback, milliseconds) => { log.push(['timer', milliseconds]); timers.push({ callback, milliseconds }); };
|
||||||
|
window.location = { reload() { log.push(['reload']); } };
|
||||||
|
const context = {
|
||||||
|
window, navigator, initialSplashEl: splash, initialConnectionCompleted: false,
|
||||||
|
connectionState: '', connectionStatusText: '', connectionNextRetryAtMs: 0,
|
||||||
|
CONNECTION_CHECK_INTERVAL_MS: 20000, connectionCheckInFlight: false,
|
||||||
|
pwaUpdateCheckAttempted: false, uiVersionCheckInFlight: false, uiUpdateReloadScheduled: false,
|
||||||
|
state: { session: { isLocalDemo: false } },
|
||||||
|
wsIsOpen: () => open,
|
||||||
|
authService: { ws: {
|
||||||
|
async open() { log.push(['ws-open']); open = true; },
|
||||||
|
async request(op) {
|
||||||
|
log.push(['request', op]);
|
||||||
|
if (rejectNextPing) {
|
||||||
|
rejectNextPing = false;
|
||||||
|
throw Object.assign(new Error('private network error'), { name: 'NetworkError' });
|
||||||
|
}
|
||||||
|
return { uiBuildHash: remoteHash };
|
||||||
|
},
|
||||||
|
} },
|
||||||
|
ensureSessionAfterWsReconnect: async () => { log.push(['ws-restore']); return true; },
|
||||||
|
stopConnectionCountdown: () => log.push(['countdown-stop']),
|
||||||
|
startConnectionCountdown: () => log.push(['countdown-start']),
|
||||||
|
refreshConnectionUi: () => log.push(['connection-ui']),
|
||||||
|
CURRENT_BUILD_HASH: 'same',
|
||||||
|
UI_BUILD_HASH_PATTERN: /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/,
|
||||||
|
fetch: async () => {
|
||||||
|
log.push(['ui-version-fetch']);
|
||||||
|
return { ok: true, async text() { return `window.__SHINE_BUILD_HASH__ = '${hostHash}'`; } };
|
||||||
|
},
|
||||||
|
addAppLogEntry: () => log.push(['app-log']),
|
||||||
|
};
|
||||||
|
runInNewContext(splashChain(source), context);
|
||||||
|
return {
|
||||||
|
log, timers, context, completeUpdate: () => pendingUpdate?.resolve(),
|
||||||
|
disconnect() { open = false; },
|
||||||
|
failNextPing() { rejectNextPing = true; },
|
||||||
|
async health() { await runInNewContext('checkConnectionHealth()', context); },
|
||||||
|
exportData() { return JSON.parse(window.__SHINE_STAGE0_EXPORT__()); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const count = (h, name) => h.log.filter(event => event[0] === name).length;
|
||||||
|
const operation = (h, name, context = null) => h.exportData().splashTrace.operations.find(
|
||||||
|
event => event.operation === name && (!context || event.context === context),
|
||||||
|
);
|
||||||
|
|
||||||
|
// 1. Быстрый Ping, медленный SW: статус и Splash не ждут окончания update().
|
||||||
|
test('Быстрый Ping и медленный SW: connected и splash_leave раньше sw_registration_update:end', async () => {
|
||||||
|
const h = harness({ slowSw: true });
|
||||||
|
await h.health();
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
assert.equal(count(h, 'request'), 1);
|
||||||
|
assert.equal(count(h, 'sw-update'), 1);
|
||||||
|
assert.equal(count(h, 'splash-class'), 1);
|
||||||
|
assert.equal(operation(h, 'connection_health').outcome, 'ok');
|
||||||
|
assert.equal(operation(h, 'pwa_first_ping_update').outcome, 'pending');
|
||||||
|
assert.equal(operation(h, 'sw_registration_update').durationMs, null);
|
||||||
|
assert.ok(h.exportData().timing.status_connected <= h.exportData().timing.splash_leave);
|
||||||
|
h.completeUpdate();
|
||||||
|
await settle();
|
||||||
|
assert.equal(operation(h, 'sw_registration_update').outcome, 'ok');
|
||||||
|
assert.ok(operation(h, 'sw_registration_update').endMs > h.exportData().timing.splash_leave);
|
||||||
|
assert.equal(operation(h, 'pwa_first_ping_update').outcome, 'ok');
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. Зависший SW не удерживает connectionCheckInFlight и не блокирует Splash.
|
||||||
|
test('Зависший SW update: успешный health-check завершается без его разрешения', async () => {
|
||||||
|
const h = harness({ slowSw: true });
|
||||||
|
await h.health();
|
||||||
|
assert.equal(h.context.connectionCheckInFlight, false);
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
assert.equal(count(h, 'splash-class'), 1);
|
||||||
|
assert.equal(operation(h, 'sw_registration_update').outcome, 'pending');
|
||||||
|
assert.equal(operation(h, 'pwa_first_ping_update').durationMs, null);
|
||||||
|
assert.deepEqual(h.timers.map(t => t.milliseconds), [700]);
|
||||||
|
// Тестовый стенд разрешает Promise перед завершением, чтобы не оставлять незавершённые задачи.
|
||||||
|
h.completeUpdate();
|
||||||
|
await settle();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 3. Отказ регистрации не превращает успешный Ping в disconnected.
|
||||||
|
test('Ошибка SW update: connected не меняется, ошибка безопасно экспортируется', async () => {
|
||||||
|
const h = harness({ swError: true });
|
||||||
|
await h.health();
|
||||||
|
await settle();
|
||||||
|
assert.equal(operation(h, 'sw_registration_update').outcome, 'error');
|
||||||
|
assert.equal(operation(h, 'sw_registration_update').errorType, 'NetworkError');
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
assert.equal(count(h, 'request'), 1);
|
||||||
|
assert.doesNotMatch(JSON.stringify(h.exportData()), /secret|token|https?:|sessionId/);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 4. Новый Ping может выполняться во время SW; одноразовый guard не позволяет начать второй SW update.
|
||||||
|
test('Повторный Ping при незавершённом SW: два Ping, но строго один first_ping update', async () => {
|
||||||
|
const h = harness({ slowSw: true });
|
||||||
|
await h.health();
|
||||||
|
await h.health();
|
||||||
|
assert.equal(count(h, 'request'), 2);
|
||||||
|
assert.equal(count(h, 'sw-update'), 1);
|
||||||
|
assert.equal(count(h, 'sw-list'), 1);
|
||||||
|
assert.equal(count(h, 'splash-class'), 1);
|
||||||
|
assert.equal(count(h, 'timer'), 1);
|
||||||
|
assert.equal(h.exportData().counters.pingStarted, 2);
|
||||||
|
assert.equal(h.exportData().splashTrace.operations.filter(x => x.operation === 'pwa_first_ping_update').length, 1);
|
||||||
|
h.completeUpdate();
|
||||||
|
await settle();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 5. reconnect не отменяет ранее стартовавший SW и его завершение не меняет состояние.
|
||||||
|
test('WS reconnect во время обновления: повторный Ping один, старое SW-завершение не меняет статус', async () => {
|
||||||
|
const h = harness({ slowSw: true });
|
||||||
|
await h.health();
|
||||||
|
h.disconnect();
|
||||||
|
await h.health();
|
||||||
|
assert.equal(count(h, 'ws-open'), 1);
|
||||||
|
assert.equal(count(h, 'ws-restore'), 1);
|
||||||
|
assert.equal(count(h, 'request'), 2);
|
||||||
|
assert.equal(count(h, 'sw-update'), 1);
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
h.completeUpdate();
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
assert.equal(count(h, 'splash-class'), 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Позднее завершение SW не возвращает connected после нового неудачного Ping', async () => {
|
||||||
|
const h = harness({ slowSw: true });
|
||||||
|
await h.health();
|
||||||
|
h.failNextPing();
|
||||||
|
await h.health();
|
||||||
|
assert.equal(h.context.connectionState, 'disconnected');
|
||||||
|
assert.equal(count(h, 'request'), 2);
|
||||||
|
assert.equal(count(h, 'sw-update'), 1);
|
||||||
|
h.completeUpdate();
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.context.connectionState, 'disconnected');
|
||||||
|
assert.equal(count(h, 'request'), 2);
|
||||||
|
assert.equal(count(h, 'splash-class'), 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Завершение SW после смены профиля не изменяет session и connection state', async () => {
|
||||||
|
const h = harness({ slowSw: true });
|
||||||
|
await h.health();
|
||||||
|
// Имитируем уже проведённый внешним lifecycle переход профиля/logout.
|
||||||
|
h.context.state.session.isAuthorized = false;
|
||||||
|
h.context.state.session.profileMarker = 'new-profile';
|
||||||
|
h.context.connectionState = 'disconnected';
|
||||||
|
h.completeUpdate();
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.context.state.session.isAuthorized, false);
|
||||||
|
assert.equal(h.context.state.session.profileMarker, 'new-profile');
|
||||||
|
assert.equal(h.context.connectionState, 'disconnected');
|
||||||
|
assert.equal(count(h, 'request'), 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 6. Проверка версии по-прежнему планирует reload и запускает отдельный reload-SW путь.
|
||||||
|
test('Параллельная проверка версии UI: обновление и reload работают при pending first_ping SW', async () => {
|
||||||
|
const h = harness({ slowSw: true, remoteHash: 'new', hostHash: 'new' });
|
||||||
|
await h.health();
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
await settle();
|
||||||
|
assert.equal(count(h, 'ui-version-fetch'), 1);
|
||||||
|
assert.equal(h.context.uiUpdateReloadScheduled, true);
|
||||||
|
assert.equal(h.context.connectionState, 'updating');
|
||||||
|
assert.equal(h.timers.filter(x => x.milliseconds === 600).length, 1);
|
||||||
|
assert.equal(count(h, 'request'), 1);
|
||||||
|
assert.equal(h.exportData().splashTrace.operations.filter(x => x.operation === 'sw_refresh' && x.context === 'first_ping').length, 1);
|
||||||
|
assert.equal(h.exportData().splashTrace.operations.filter(x => x.operation === 'sw_refresh' && x.context === 'reload').length, 1);
|
||||||
|
h.completeUpdate();
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.context.connectionState, 'updating');
|
||||||
|
h.timers.find(t => t.milliseconds === 600).callback();
|
||||||
|
assert.equal(count(h, 'reload'), 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 7. Отсутствие serviceWorker в navigator совместимо с non-blocking веткой.
|
||||||
|
test('Нет Service Worker API: нет SW-операций, Ping и закрытие Splash остаются', async () => {
|
||||||
|
const h = harness({ swSupported: false });
|
||||||
|
await h.health();
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
assert.equal(count(h, 'sw-update'), 0);
|
||||||
|
assert.equal(count(h, 'request'), 1);
|
||||||
|
assert.equal(count(h, 'splash-class'), 1);
|
||||||
|
assert.equal(operation(h, 'sw_refresh'), undefined);
|
||||||
|
assert.equal(operation(h, 'pwa_first_ping_update').outcome, 'ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 8. Guard работает на один запуск документа: после реального page reload создаётся новый контекст.
|
||||||
|
test('Повторная загрузка страницы PWA: ровно один update на каждую страницу', async () => {
|
||||||
|
const firstPage = harness();
|
||||||
|
await firstPage.health();
|
||||||
|
await firstPage.health();
|
||||||
|
await settle();
|
||||||
|
assert.equal(count(firstPage, 'request'), 2);
|
||||||
|
assert.equal(count(firstPage, 'sw-update'), 1);
|
||||||
|
const nextPage = harness();
|
||||||
|
await nextPage.health();
|
||||||
|
await settle();
|
||||||
|
assert.equal(count(nextPage, 'request'), 1);
|
||||||
|
assert.equal(count(nextPage, 'sw-update'), 1);
|
||||||
|
assert.equal(nextPage.exportData().splashTrace.operations.filter(x => x.operation === 'pwa_first_ping_update').length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Обработка исключения SW-задачи независима от успешного Ping.
|
||||||
|
test('Неожиданный reject SW-задачи обработан, status остаётся connected', async () => {
|
||||||
|
const h = harness();
|
||||||
|
runInNewContext("tryUpdatePwaOnFirstConnectedPing = async () => { throw new Error('private reject'); };", h.context);
|
||||||
|
await h.health();
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
assert.equal(count(h, 'splash-class'), 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Контроль минимальности: восстановление старой await-строки внутри того же источника.
|
||||||
|
test('Контроль Stage 0.1 и Stage 1.1: один health-check не создаёт новых Ping/WS/SW/timers', async () => {
|
||||||
|
const pattern = / \/\/ Проверка SW остаётся одноразовой[^\n]*\n void tryUpdatePwaOnFirstConnectedPing\(\)\.catch\(\(\) => \{\n \/\/ Ошибка уже отмечена[^\n]*\n \}\);\n setConnectionStatus\('connected'\);/;
|
||||||
|
assert.match(appSource, pattern);
|
||||||
|
const controlSource = appSource.replace(pattern, " await tryUpdatePwaOnFirstConnectedPing();\n setConnectionStatus('connected');");
|
||||||
|
const before = harness({ source: controlSource });
|
||||||
|
const after = harness();
|
||||||
|
await before.health();
|
||||||
|
await after.health();
|
||||||
|
await settle();
|
||||||
|
const effects = ['request', 'ws-open', 'ws-restore', 'sw-list', 'sw-update', 'timer', 'splash-class'];
|
||||||
|
for (const kind of effects) assert.equal(count(before, kind), count(after, kind), kind);
|
||||||
|
const networkAndWorker = ['request', 'ws-open', 'ws-restore', 'sw-list', 'sw-update'];
|
||||||
|
assert.deepEqual(before.log.filter(x => networkAndWorker.includes(x[0])).map(x => x[0]),
|
||||||
|
after.log.filter(x => networkAndWorker.includes(x[0])).map(x => x[0]));
|
||||||
|
assert.equal(before.context.connectionState, after.context.connectionState);
|
||||||
|
});
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { runInNewContext } from 'node:vm';
|
||||||
|
|
||||||
|
const source = readFileSync(new URL('../js/app.js', import.meta.url), 'utf8');
|
||||||
|
const html = readFileSync(new URL('../index.html', import.meta.url), 'utf8');
|
||||||
|
const diagnostics = html.match(/<script id="shine-stage0-startup-diagnostics">([\s\S]*?)<\/script>/)?.[1];
|
||||||
|
assert.ok(diagnostics);
|
||||||
|
|
||||||
|
// Используются настоящие тела app.js; таймеры, WS, SW и DOM заменены детерминированными стендами.
|
||||||
|
const slices = [
|
||||||
|
['function finishInitialConnectionSplash()', 'function startConnectionCountdown()'],
|
||||||
|
['function setConnectionStatus(', 'async function triggerImmediateConnectionRetry()'],
|
||||||
|
['function extractBuildHashFromHtml(', 'function startPeriodicUiVersionCheck()'],
|
||||||
|
['async function checkConnectionHealth(', 'function isReconnectAllowedNow()'],
|
||||||
|
];
|
||||||
|
const chain = slices.map(([start, end]) => {
|
||||||
|
const a = source.indexOf(start);
|
||||||
|
const b = source.indexOf(end, a + start.length);
|
||||||
|
assert.ok(a >= 0 && b > a, `Невозможно извлечь ${start}`);
|
||||||
|
return source.slice(a, b);
|
||||||
|
}).join('\n');
|
||||||
|
|
||||||
|
function deferred() {
|
||||||
|
let resolve;
|
||||||
|
const promise = new Promise(r => { resolve = r; });
|
||||||
|
return { promise, resolve };
|
||||||
|
}
|
||||||
|
async function settle() {
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
}
|
||||||
|
function harness({ debug = true, ping = 'fast', sw = 'fast', wsOpen = true, localDemo = false } = {}) {
|
||||||
|
let currentMs = 400;
|
||||||
|
const performance = { now: () => ++currentMs, mark() {}, getEntriesByType: () => [] };
|
||||||
|
const window = { performance };
|
||||||
|
runInNewContext(diagnostics, { window, performance,
|
||||||
|
localStorage: { getItem: () => debug ? '1' : '0' }, document: { addEventListener() {} },
|
||||||
|
});
|
||||||
|
const log = [];
|
||||||
|
const intervals = new Map();
|
||||||
|
let nextInterval = 0;
|
||||||
|
let connected = wsOpen;
|
||||||
|
let fail = ping === 'fail';
|
||||||
|
const slowPing = ping === 'slow' ? deferred() : null;
|
||||||
|
const slowSw = sw === 'slow' ? deferred() : null;
|
||||||
|
window.setInterval = (callback, milliseconds) => {
|
||||||
|
const id = ++nextInterval;
|
||||||
|
log.push(['interval', milliseconds]);
|
||||||
|
intervals.set(id, { callback, milliseconds });
|
||||||
|
return id;
|
||||||
|
};
|
||||||
|
window.clearInterval = id => { log.push(['clear-interval']); intervals.delete(id); };
|
||||||
|
window.setTimeout = (_callback, milliseconds) => { log.push(['timeout', milliseconds]); return 123; };
|
||||||
|
window.location = { reload() { log.push(['reload']); } };
|
||||||
|
const splash = { classList: { add(name) { log.push(['splash', name]); } },
|
||||||
|
addEventListener() {}, remove() { log.push(['splash-remove']); } };
|
||||||
|
const navigator = sw === 'unavailable' ? {} : { serviceWorker: {
|
||||||
|
async getRegistrations() { log.push(['sw-registrations']); return [{
|
||||||
|
async update() {
|
||||||
|
log.push(['sw-update']);
|
||||||
|
if (slowSw) await slowSw.promise;
|
||||||
|
if (sw === 'fail') throw Object.assign(new Error('private token'), { name: 'SecurityError' });
|
||||||
|
},
|
||||||
|
}]; },
|
||||||
|
} };
|
||||||
|
const context = {
|
||||||
|
window, navigator, state: { session: { isLocalDemo: localDemo, isAuthorized: true } },
|
||||||
|
initialSplashEl: splash, initialConnectionCompleted: false,
|
||||||
|
connectionState: '', connectionStatusText: '', connectionNextRetryAtMs: 0,
|
||||||
|
connectionCheckInFlight: false, connectionMonitorStartSource: '', pingIntervalId: null,
|
||||||
|
CONNECTION_CHECK_INTERVAL_MS: 20000, pwaUpdateCheckAttempted: false,
|
||||||
|
uiVersionCheckInFlight: false, uiUpdateReloadScheduled: false,
|
||||||
|
wsIsOpen: () => connected,
|
||||||
|
authService: { ws: {
|
||||||
|
async open() { log.push(['ws-open']); connected = true; },
|
||||||
|
async request(op) {
|
||||||
|
log.push(['request', op]);
|
||||||
|
if (slowPing) await slowPing.promise;
|
||||||
|
if (fail) { fail = false; throw Object.assign(new Error('private token'), { name: 'NetworkError' }); }
|
||||||
|
return { uiBuildHash: 'same' };
|
||||||
|
},
|
||||||
|
} },
|
||||||
|
ensureSessionAfterWsReconnect: async () => { log.push(['ws-restore']); return true; },
|
||||||
|
stopConnectionCountdown: () => log.push(['countdown-stop']),
|
||||||
|
startConnectionCountdown: () => log.push(['countdown-start']),
|
||||||
|
refreshConnectionUi: () => log.push(['connection-ui']),
|
||||||
|
CURRENT_BUILD_HASH: 'same', UI_BUILD_HASH_PATTERN: /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/,
|
||||||
|
fetch: async () => { log.push(['fetch']); throw Error('Неожиданный fetch'); },
|
||||||
|
addAppLogEntry: () => log.push(['log']),
|
||||||
|
};
|
||||||
|
runInNewContext(chain, context);
|
||||||
|
const run = (fn) => runInNewContext(fn, context);
|
||||||
|
const count = (name) => log.filter(e => e[0] === name).length;
|
||||||
|
return { log, intervals, context, run, count,
|
||||||
|
start: (source) => run(`startConnectionMonitor('${source}')`),
|
||||||
|
health: (source) => run(`checkConnectionHealth('${source}')`),
|
||||||
|
tick: () => [...intervals.values()][0]?.callback(),
|
||||||
|
failNextPing: () => { fail = true; },
|
||||||
|
closeWs: () => { connected = false; },
|
||||||
|
releasePing: () => slowPing?.resolve(),
|
||||||
|
releaseSw: () => slowSw?.resolve(),
|
||||||
|
exportData: () => JSON.parse(window.__SHINE_STAGE0_EXPORT__()),
|
||||||
|
op: (name, source) => JSON.parse(window.__SHINE_STAGE0_EXPORT__()).splashTrace.operations
|
||||||
|
.filter(o => o.operation === name && (!source || o.context === source)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Реальный исходник обязан направлять события через те же фиксированные источники.
|
||||||
|
test('Идентификаторы соответствуют существующим call-site (bootstrap, session-runtime, reset, visibility и periodic)', () => {
|
||||||
|
assert.match(source, /startConnectionMonitor\('bootstrap'\)/);
|
||||||
|
assert.match(source, /startConnectionMonitor\('session_runtime'\)/);
|
||||||
|
assert.match(source, /startConnectionMonitor\('session_reset'\)/);
|
||||||
|
assert.match(source, /checkConnectionHealth\('visibility'\)/);
|
||||||
|
assert.match(source, /checkConnectionHealth\('periodic'\)/);
|
||||||
|
assert.match(source, /checkConnectionHealth\('retry_countdown'\)/);
|
||||||
|
assert.match(source, /checkConnectionHealth\('manual_retry'\)/);
|
||||||
|
assert.equal((source.match(/startConnectionMonitor\('bootstrap'\)/g) || []).length, 1);
|
||||||
|
assert.equal((source.match(/startConnectionMonitor\('session_runtime'\)/g) || []).length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Сохранённая сессия: bootstrap → session-runtime создаёт только один первоначальный Ping', async () => {
|
||||||
|
const h = harness({ sw: 'slow' });
|
||||||
|
h.start('bootstrap');
|
||||||
|
await settle();
|
||||||
|
h.start('session_runtime');
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.count('request'), 1);
|
||||||
|
assert.equal(h.count('interval'), 1);
|
||||||
|
assert.equal(h.count('clear-interval'), 0);
|
||||||
|
assert.equal(h.intervals.size, 1);
|
||||||
|
assert.equal(h.count('sw-update'), 1);
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
assert.equal(h.count('splash'), 1);
|
||||||
|
assert.equal(h.op('monitor_start', 'session_runtime')[0].outcome, 'deduplicated');
|
||||||
|
assert.equal(h.op('connection_health', 'bootstrap').length, 1);
|
||||||
|
assert.equal(h.op('connection_health', 'session_runtime').length, 0);
|
||||||
|
assert.equal(h.op('sw_registration_update')[0].outcome, 'pending');
|
||||||
|
h.releaseSw();
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.op('sw_registration_update')[0].outcome, 'ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Сохранённая сессия: session-runtime → bootstrap также создаёт один Ping', async () => {
|
||||||
|
const h = harness();
|
||||||
|
h.start('session_runtime');
|
||||||
|
await settle();
|
||||||
|
h.start('bootstrap');
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.count('request'), 1);
|
||||||
|
assert.equal(h.intervals.size, 1);
|
||||||
|
assert.equal(h.op('monitor_start', 'bootstrap')[0].outcome, 'deduplicated');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Без пользователя: bootstrap запускает Ping без блокирования monitor guard', async () => {
|
||||||
|
const h = harness();
|
||||||
|
h.context.state.session.isAuthorized = false;
|
||||||
|
h.start('bootstrap');
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.count('request'), 1);
|
||||||
|
assert.equal(h.op('connection_health', 'bootstrap').length, 1);
|
||||||
|
assert.equal(h.intervals.size, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Медленный Ping: параллельный старт не создаёт второй WS/Ping, Splash по ответу', async () => {
|
||||||
|
const h = harness({ ping: 'slow' });
|
||||||
|
h.start('bootstrap');
|
||||||
|
h.start('session_runtime');
|
||||||
|
assert.equal(h.count('request'), 1);
|
||||||
|
assert.equal(h.count('splash'), 0);
|
||||||
|
assert.equal(h.op('monitor_start', 'session_runtime')[0].outcome, 'deduplicated');
|
||||||
|
h.releasePing();
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.count('request'), 1);
|
||||||
|
assert.equal(h.count('splash'), 1);
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Неудачный первый Ping: второй старт сохраняет самостоятельную немедленную повторную проверку', async () => {
|
||||||
|
const h = harness({ ping: 'fail' });
|
||||||
|
h.start('bootstrap');
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.context.connectionState, 'disconnected');
|
||||||
|
h.start('session_runtime');
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.count('request'), 2);
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
assert.equal(h.op('monitor_start', 'session_runtime')[0].outcome, 'ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('20-секундный Ping: исходный интервал и обычный повтор запроса сохранены', async () => {
|
||||||
|
const h = harness();
|
||||||
|
h.start('bootstrap');
|
||||||
|
await settle();
|
||||||
|
h.start('session_runtime');
|
||||||
|
assert.equal([...h.intervals.values()][0].milliseconds, 20000);
|
||||||
|
h.tick();
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.count('request'), 2);
|
||||||
|
assert.equal(h.op('connection_health', 'periodic').length, 1);
|
||||||
|
assert.equal(h.count('interval'), 1);
|
||||||
|
assert.equal(h.count('sw-update'), 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Reconnect после успешного старта: visibility или другой реальный сигнал вызывает health-check и WS open', async () => {
|
||||||
|
const h = harness();
|
||||||
|
h.start('bootstrap');
|
||||||
|
await settle();
|
||||||
|
h.start('session_runtime');
|
||||||
|
h.closeWs();
|
||||||
|
await h.health('visibility');
|
||||||
|
assert.equal(h.count('request'), 2);
|
||||||
|
assert.equal(h.count('ws-open'), 1);
|
||||||
|
assert.equal(h.count('ws-restore'), 1);
|
||||||
|
assert.equal(h.count('sw-update'), 1);
|
||||||
|
assert.equal(h.op('connection_health', 'visibility').length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Возврат вкладки: независимая visibility-проверка не подавляется startup guard', async () => {
|
||||||
|
const h = harness();
|
||||||
|
h.start('session_runtime');
|
||||||
|
await settle();
|
||||||
|
h.start('bootstrap');
|
||||||
|
await h.health('visibility');
|
||||||
|
assert.equal(h.count('request'), 2);
|
||||||
|
assert.equal(h.op('monitor_start', 'bootstrap')[0].outcome, 'deduplicated');
|
||||||
|
assert.equal(h.op('connection_health', 'visibility')[0].outcome, 'ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Смена пользователя: session-reset и новый runtime сохраняют немедленные проверки', async () => {
|
||||||
|
const h = harness();
|
||||||
|
h.start('bootstrap');
|
||||||
|
await settle();
|
||||||
|
h.start('session_runtime');
|
||||||
|
h.start('session_reset');
|
||||||
|
await settle();
|
||||||
|
h.start('session_runtime');
|
||||||
|
await settle();
|
||||||
|
assert.equal(h.count('request'), 3);
|
||||||
|
assert.equal(h.op('monitor_start', 'session_reset')[0].outcome, 'ok');
|
||||||
|
assert.equal(h.op('monitor_start', 'session_runtime').at(-1).outcome, 'ok');
|
||||||
|
assert.equal(h.intervals.size, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Stage 0/0.1/1.1: метки и безопасные context сохраняются, без чувствительных данных', async () => {
|
||||||
|
const h = harness({ sw: 'fail' });
|
||||||
|
h.start('bootstrap');
|
||||||
|
await settle();
|
||||||
|
h.start('session_runtime');
|
||||||
|
await settle();
|
||||||
|
const e = h.exportData();
|
||||||
|
assert.equal(e.counters.pingStarted, 1);
|
||||||
|
assert.equal(e.counters.pingCompleted, 1);
|
||||||
|
for (const name of ['connection_health','ping','pwa_first_ping_update','sw_refresh','sw_registration_update']) {
|
||||||
|
assert.ok(e.splashTrace.operations.some(x => x.operation === name), `Нет ${name}`);
|
||||||
|
}
|
||||||
|
assert.ok(e.timing.status_connected < e.timing.splash_leave || e.timing.status_connected === e.timing.splash_leave);
|
||||||
|
assert.ok(e.timing.splash_leave != null);
|
||||||
|
assert.equal(h.op('sw_registration_update')[0].errorType, 'SecurityError');
|
||||||
|
assert.ok(e.splashTrace.operations.some(x => x.operation === 'monitor_start' && x.outcome === 'deduplicated'));
|
||||||
|
assert.doesNotMatch(JSON.stringify(e), /private|token|sessionId|https?:/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Debug-off: диагностика не нужна для корректного monitor guard и не создаёт запросов', async () => {
|
||||||
|
const h = harness({ debug: false, sw: 'unavailable' });
|
||||||
|
h.start('bootstrap');
|
||||||
|
await settle();
|
||||||
|
h.start('session_runtime');
|
||||||
|
assert.equal(h.count('request'), 1);
|
||||||
|
assert.equal(h.count('sw-update'), 0);
|
||||||
|
assert.equal(h.intervals.size, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Local demo: никакого Ping при обеих startup-ветках', async () => {
|
||||||
|
const h = harness({ localDemo: true });
|
||||||
|
h.start('bootstrap');
|
||||||
|
h.start('session_runtime');
|
||||||
|
assert.equal(h.count('request'), 0);
|
||||||
|
assert.equal(h.intervals.size, 0);
|
||||||
|
assert.equal(h.context.connectionState, 'connected');
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user