Files
image-workbench-desktop/src/runtime-crash-log.js
T

217 lines
9.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
;(function (global) {
'use strict'
// v3.87.6:崩溃可观测性(先取证再优化)。
// 目标:把「随机的、用着用着就崩」变成可读的记录——
// ① 错误/未处理 Promise/错误边界捕获 → 环形 20 条落盘(刷新后仍能看)
// ② 内存与规模采样 → 环形 40 条持续落盘(崩溃后重开页面即可看到"崩溃前的增长曲线")
// ③ 操作面包屑 → 环形 20 条(崩溃前最后做了什么)
// 全部 best-effort:localStorage 不可用(隐私模式/配额满)时静默降级,绝不影响主流程。
const KEY_ENTRIES = 'iwb_crash_log'
const KEY_SAMPLES = 'iwb_diag_samples'
const KEY_BREAD = 'iwb_diag_breadcrumbs'
const MAX_ENTRIES = 20
const MAX_SAMPLES = 40
const MAX_BREAD = 20
let entries = []
let samples = []
let breadcrumbs = []
const _lstore = () => (typeof global !== 'undefined' && global.IWBStorageLocal && typeof global.IWBStorageLocal.getStore === 'function') ? global.IWBStorageLocal.getStore() : null
let installed = false
let uninstallFns = []
function text(value, max) { return (value === undefined || value === null) ? '' : String(value).slice(0, max || 400) }
function iso(ts) { try { return new Date(ts).toISOString() } catch (e) { return '' } }
function readArray(key) {
try {
const st = _lstore()
const arr = st ? st.get(key, []) : []
return Array.isArray(arr) ? arr : []
} catch (e) { return [] }
}
function writeArray(key, arr) {
try { const st = _lstore(); if (st) st.set(key, arr) } catch (e) { /* 配额满 / 隐私模式:只保留内存副本 */ }
}
function trimPush(bucket, item, max) { bucket.push(item); while (bucket.length > max) bucket.shift(); return bucket }
function env() {
const nav = /** @type {any} */ (global.navigator || {})
return {
userAgent: text(nav.userAgent, 300),
language: text(nav.language, 20),
hardwareConcurrency: Number(nav.hardwareConcurrency) || 0,
deviceMemoryGB: Number(nav.deviceMemory) || 0,
url: text(global.location && global.location.href, 300),
origin: text(global.location && global.location.origin, 120),
viewport: (global.innerWidth && global.innerHeight) ? (global.innerWidth + 'x' + global.innerHeight) : '',
}
}
function memoryNow() {
try {
const pm = global.performance && global.performance.memory
if (!pm || !pm.jsHeapSizeLimit) return null
return {
usedMB: Math.round(pm.usedJSHeapSize / 1048576),
totalMB: Math.round(pm.totalJSHeapSize / 1048576),
limitMB: Math.round(pm.jsHeapSizeLimit / 1048576),
ratio: Number((pm.usedJSHeapSize / pm.jsHeapSizeLimit).toFixed(3)),
}
} catch (e) { return null }
}
function localBytes() {
try {
const ls = global.localStorage
if (!ls) return 0
let total = 0
for (let i = 0; i < ls.length; i++) {
const k = ls.key(i)
total += (String(k || '').length + String(ls.getItem(k) || '').length) * 2
}
return total
} catch (e) { return 0 }
}
// ── ① 错误记录 ──
function record(kind, payload) {
const src = payload || {}
const ts = Number(src.ts) || Date.now()
const rec = {
ts, time: iso(ts), kind: text(kind || 'error', 24),
scope: text(src.scope, 60),
message: text(src.message, 400),
stack: text(src.stack, 1200),
nodeId: text(src.nodeId, 80),
boardId: text(src.boardId, 80),
version: text(src.version, 40),
memory: src.memory || memoryNow(),
extra: (src.extra && typeof src.extra === 'object') ? src.extra : undefined,
}
trimPush(entries, rec, MAX_ENTRIES)
writeArray(KEY_ENTRIES, entries)
return rec
}
// ── ② 内存/规模采样(持续落盘:崩溃后重开页面就能看到崩溃前的增长趋势)──
function sample(extra) {
const src = extra || {}
const ts = Date.now()
const item = {
ts, time: iso(ts),
memory: src.memory || memoryNow(),
boards: Math.max(0, Number(src.boards) || 0),
nodes: Math.max(0, Number(src.nodes) || 0),
images: Math.max(0, Number(src.images) || 0),
base64MB: Math.round((Math.max(0, Number(src.base64Bytes) || 0) / 1048576) * 10) / 10,
localKB: Math.round(localBytes() / 1024),
view: text(src.view, 20),
note: text(src.note, 80),
// v3.87.9 泄漏仪表:历史/缓存等"可能无上限增长"的结构,随采样一起落盘
history: (src.history && typeof src.history === 'object') ? src.history : undefined,
maps: (src.maps && typeof src.maps === 'object') ? src.maps : undefined,
// v3.87.19:同样别再犯"白名单吞字段"的错——诊断新增字段必须能落盘,否则永远看不到。
comp: (src.comp && typeof src.comp === 'object') ? src.comp : undefined,
}
trimPush(samples, item, MAX_SAMPLES)
writeArray(KEY_SAMPLES, samples)
return item
}
// ── ③ 操作面包屑 ──
function breadcrumb(kind, detail) {
const ts = Date.now()
const item = { ts, time: iso(ts), kind: text(kind, 40), detail: text(detail, 200) }
trimPush(breadcrumbs, item, MAX_BREAD)
writeArray(KEY_BREAD, breadcrumbs)
return item
}
// ── ④ 安装全局钩子(幂等)──
function install(getContext) {
if (installed || !global.addEventListener) return false
installed = true
const ctx = () => {
try { return (typeof getContext === 'function' ? getContext() : null) || {} } catch (e) { return {} }
}
const onError = (e) => {
// 资源加载失败(img/script 等)没有 error.message,也不该淹没环形缓冲:只记面包屑
const err = e && e.error
if (!err && !(e && e.message)) {
try { breadcrumb('resource-error', (e && e.target && (e.target.tagName + ' ' + (e.target.src || e.target.href))) || '') } catch (x) { /* ignore */ }
return
}
const c = ctx()
record('error', {
scope: 'window.onerror',
message: (e && e.message) || (err && err.message) || 'unknown error',
stack: (err && err.stack) || '',
version: c.version, boardId: c.boardId, nodeId: c.nodeId,
extra: { source: text(e && e.filename, 200), line: Number(e && e.lineno) || 0, col: Number(e && e.colno) || 0 },
})
}
const onRejection = (e) => {
const reason = e && e.reason
const msg = (reason && (reason.message || reason.error)) || reason
const s = String(msg === undefined ? '' : msg)
// 取消/中断类属于正常流程(用户点取消、切换节点都会触发),不记以免淹没真实错误
if (/abort|cancel|取消|已中断/i.test(s)) return
const c = ctx()
record('rejection', {
scope: 'unhandledrejection',
message: s || 'unhandled rejection',
stack: (reason && reason.stack) || '',
version: c.version, boardId: c.boardId, nodeId: c.nodeId,
})
}
global.addEventListener('error', onError)
global.addEventListener('unhandledrejection', onRejection)
uninstallFns.push(() => { global.removeEventListener('error', onError); global.removeEventListener('unhandledrejection', onRejection) })
// 启动时还原上次落盘的记录(标签页崩溃后重开也能看到)
load()
return true
}
function uninstall() { while (uninstallFns.length) { try { uninstallFns.pop()() } catch (e) { /* ignore */ } } installed = false }
function load() {
entries = readArray(KEY_ENTRIES)
samples = readArray(KEY_SAMPLES)
breadcrumbs = readArray(KEY_BREAD)
return { entries: entries.length, samples: samples.length, breadcrumbs: breadcrumbs.length }
}
function clear() {
entries = []; samples = []; breadcrumbs = []
try { const st = _lstore(); if (st) st.remove(KEY_ENTRIES) } catch (e) { /* ignore */ }
try { const st = _lstore(); if (st) st.remove(KEY_SAMPLES) } catch (e) { /* ignore */ }
try { const st = _lstore(); if (st) st.remove(KEY_BREAD) } catch (e) { /* ignore */ }
}
function report(extra) {
const src = extra || {}
return {
schemaVersion: 1,
generatedAt: Date.now(),
generatedAtISO: iso(Date.now()),
version: text(src.version, 40),
commit: text(src.commit, 40),
env: env(),
memory: memoryNow(),
storage: { localBytes: localBytes() },
context: (src.context && typeof src.context === 'object') ? src.context : undefined,
counts: { entries: entries.length, samples: samples.length, breadcrumbs: breadcrumbs.length },
entries: entries.slice(),
samples: samples.slice(),
breadcrumbs: breadcrumbs.slice(),
}
}
global.IWBCrashLog = {
install, uninstall, load, clear,
record, sample, breadcrumb, report,
entries: () => entries.slice(),
samples: () => samples.slice(),
breadcrumbs: () => breadcrumbs.slice(),
memoryNow,
keys: { entries: KEY_ENTRIES, samples: KEY_SAMPLES, breadcrumbs: KEY_BREAD },
limits: { entries: MAX_ENTRIES, samples: MAX_SAMPLES, breadcrumbs: MAX_BREAD },
}
})(typeof window !== 'undefined' ? window : globalThis)