feat: 版本更新优化非强制更新
This commit is contained in:
+19
-5
@@ -28,6 +28,18 @@ const waitForPromptDecision = (payload) => {
|
||||
})
|
||||
}
|
||||
|
||||
const toBoolean = (v) => {
|
||||
if (v === true) return true
|
||||
if (v === false || v === null || typeof v === 'undefined') return false
|
||||
if (typeof v === 'number') return v === 1
|
||||
if (typeof v === 'string') {
|
||||
const s = v.trim().toLowerCase()
|
||||
if (s === '1' || s === 'true') return true
|
||||
if (s === '0' || s === 'false' || s === '') return false
|
||||
}
|
||||
return !!v
|
||||
}
|
||||
|
||||
export const compareVersion = (a, b) => {
|
||||
const pa = String(a || '')
|
||||
.split('.')
|
||||
@@ -311,6 +323,7 @@ export const createHotUpdate = ({
|
||||
uni.showToast({ title: '已经是最新版本', icon: 'none' })
|
||||
return
|
||||
}
|
||||
const isForceUpdate = toBoolean(info?.isForceUpdate)
|
||||
const promptKey = String(info.type || '') + ':' + String(latest || '')
|
||||
const desc = getUpdateDesc(info)
|
||||
const content = desc
|
||||
@@ -320,7 +333,7 @@ export const createHotUpdate = ({
|
||||
: '发现新的版本,请立即更新到最新版本'
|
||||
const title = latest ? `发现新版本 v${latest}` : '提示'
|
||||
const confirmText = '立即升级'
|
||||
const cancelText = info.isForceUpdate ? '关闭' : '取消'
|
||||
const cancelText = isForceUpdate ? '关闭' : '取消'
|
||||
|
||||
const doUpdate = () => {
|
||||
const wgtUrl = String(info.filePath || '')
|
||||
@@ -337,7 +350,7 @@ export const createHotUpdate = ({
|
||||
emitUniEvent(HOT_UPDATE_PROMPT_CLOSE_EVENT, {})
|
||||
}
|
||||
|
||||
if (info.isForceUpdate) {
|
||||
if (isForceUpdate) {
|
||||
if (source !== 'manual' && state.lastAutoUpdateAttemptKey === promptKey) return
|
||||
state.lastAutoUpdateAttemptKey = promptKey
|
||||
try {
|
||||
@@ -353,7 +366,7 @@ export const createHotUpdate = ({
|
||||
title,
|
||||
content,
|
||||
version: latest,
|
||||
isForceUpdate: !!info.isForceUpdate,
|
||||
isForceUpdate,
|
||||
confirmText,
|
||||
cancelText,
|
||||
})
|
||||
@@ -393,6 +406,7 @@ export const createHotUpdate = ({
|
||||
const { updateInfo, localCompareVersion, latestVersion } = payload
|
||||
if (!hasNewVersion(updateInfo, localCompareVersion)) return
|
||||
|
||||
const isForceUpdate = toBoolean(updateInfo?.isForceUpdate)
|
||||
const promptKey = String(updateInfo.type || '') + ':' + String(latestVersion || '')
|
||||
try {
|
||||
if (latestKeyStorageKey) uni.setStorageSync(latestKeyStorageKey, promptKey)
|
||||
@@ -400,13 +414,13 @@ export const createHotUpdate = ({
|
||||
const storedPrompt = String(uni.getStorageSync(storageKey) || '')
|
||||
const shouldSkipPrompt =
|
||||
allowSkipPrompt &&
|
||||
!updateInfo.isForceUpdate &&
|
||||
!isForceUpdate &&
|
||||
(state.lastPromptKey === promptKey || storedPrompt === promptKey)
|
||||
if (shouldSkipPrompt) return
|
||||
state.lastPromptKey = promptKey
|
||||
uni.setStorageSync(storageKey, promptKey)
|
||||
|
||||
if (updateInfo.type == 'min' && updateInfo.isForceUpdate) {
|
||||
if (updateInfo.type == 'min' && isForceUpdate) {
|
||||
if (state.lastAutoUpdateAttemptKey === promptKey) return
|
||||
state.lastAutoUpdateAttemptKey = promptKey
|
||||
const wgtUrl = String(updateInfo.filePath || '')
|
||||
|
||||
@@ -0,0 +1,855 @@
|
||||
const getIsAppRuntime = () => {
|
||||
try {
|
||||
const baseInfo = typeof uni.getAppBaseInfo === 'function' ? uni.getAppBaseInfo() : null;
|
||||
if (baseInfo?.uniPlatform) return String(baseInfo.uniPlatform) === 'app';
|
||||
} catch (e) {}
|
||||
try {
|
||||
const sysInfo = typeof uni.getSystemInfoSync === 'function' ? uni.getSystemInfoSync() : null;
|
||||
if (sysInfo?.uniPlatform) return String(sysInfo.uniPlatform) === 'app';
|
||||
} catch (e) {}
|
||||
return false;
|
||||
};
|
||||
|
||||
const getIsAppPlus = () => typeof plus !== 'undefined' && !!plus.runtime;
|
||||
|
||||
const getHasDom = () => typeof window !== 'undefined' && !!window.document;
|
||||
|
||||
const isVConsoleEnabled = () => {
|
||||
const disabled = uni.getStorageSync('__disable_vconsole__') === 1;
|
||||
if (disabled) return false;
|
||||
return getIsAppRuntime() || getHasDom() || uni.getStorageSync('__enable_vconsole__') === 1;
|
||||
};
|
||||
|
||||
const VCONSOLE_URLS = [
|
||||
'https://unpkg.com/vconsole@3.3.4/dist/vconsole.min.js',
|
||||
'https://cdn.jsdelivr.net/npm/vconsole@3.3.4/dist/vconsole.min.js',
|
||||
];
|
||||
|
||||
const buildWebviewBootstrapCode = () => {
|
||||
const urlsJson = JSON.stringify(VCONSOLE_URLS);
|
||||
return `(function(){try{
|
||||
if(window.__VC_UNI_BOOTSTRAP__) return;
|
||||
window.__VC_UNI_BOOTSTRAP__ = true;
|
||||
|
||||
var URLS = ${urlsJson};
|
||||
var q = window.__VC_UNI_EVENT_QUEUE__ = window.__VC_UNI_EVENT_QUEUE__ || [];
|
||||
var netItems = window.__VC_UNI_NET_ITEMS__ = window.__VC_UNI_NET_ITEMS__ || [];
|
||||
var netById = window.__VC_UNI_NET_BY_ID__ = window.__VC_UNI_NET_BY_ID__ || {};
|
||||
var logItems = window.__VC_UNI_LOG_ITEMS__ = window.__VC_UNI_LOG_ITEMS__ || [];
|
||||
var logActiveId = window.__VC_UNI_LOG_ACTIVE_ID__ = window.__VC_UNI_LOG_ACTIVE_ID__ || '';
|
||||
|
||||
function safeStringify(v){
|
||||
try{
|
||||
if(v===undefined) return 'undefined';
|
||||
if(v===null) return 'null';
|
||||
if(typeof v==='string') return v;
|
||||
if(typeof v==='number' || typeof v==='boolean') return String(v);
|
||||
return JSON.stringify(v);
|
||||
}catch(e){
|
||||
try{ return String(v); }catch(e2){ return '[unserializable]'; }
|
||||
}
|
||||
}
|
||||
|
||||
function ensureVConsole(){
|
||||
if(window.__vconsole_instance) return window.__vconsole_instance;
|
||||
if(!window.VConsole) return null;
|
||||
try{
|
||||
window.__vconsole_instance = new window.VConsole();
|
||||
}catch(e){
|
||||
return null;
|
||||
}
|
||||
return window.__vconsole_instance;
|
||||
}
|
||||
|
||||
function renderLog(){
|
||||
try{
|
||||
var tbody = document.getElementById('__vc_uni_log_tbody__');
|
||||
if(!tbody) return;
|
||||
var html = '';
|
||||
for(var i=0;i<logItems.length;i++){
|
||||
var it = logItems[i] || {};
|
||||
html += '<tr data-id="' + (it.id || '') + '" style="cursor:pointer;">' +
|
||||
'<td style="padding:6px 4px;width:56px;text-align:center;">' + safeStringify(it.level || '') + '</td>' +
|
||||
'<td style="padding:6px 4px;width:76px;text-align:center;">' + safeStringify(it.time || '') + '</td>' +
|
||||
'<td style="padding:6px 4px;word-break:break-all;">' + safeStringify(it.msg || '') + '</td>' +
|
||||
'</tr>';
|
||||
}
|
||||
tbody.innerHTML = html;
|
||||
}catch(e){}
|
||||
}
|
||||
|
||||
function ensureLogPlugin(vc){
|
||||
try{
|
||||
if(!vc) return;
|
||||
if(window.__VC_UNI_LOG_PLUGIN_ADDED__) return;
|
||||
if(!window.VConsole || !window.VConsole.VConsolePlugin) return;
|
||||
var plugin = new window.VConsole.VConsolePlugin('uni_log', 'U-Log');
|
||||
plugin.on('renderTab', function(cb){
|
||||
var html = '' +
|
||||
'<div style="padding:6px 0;">' +
|
||||
'<table style="width:100%;border-collapse:collapse;font-size:12px;">' +
|
||||
'<thead><tr>' +
|
||||
'<th style="text-align:center;padding:6px 4px;width:56px;">Level</th>' +
|
||||
'<th style="text-align:center;padding:6px 4px;width:76px;">Time</th>' +
|
||||
'<th style="text-align:left;padding:6px 4px;">Message</th>' +
|
||||
'</tr></thead>' +
|
||||
'<tbody id="__vc_uni_log_tbody__"></tbody>' +
|
||||
'</table>' +
|
||||
'<div id="__vc_uni_log_detail__" style="margin-top:8px;padding:6px 4px;border-top:1px solid rgba(0,0,0,.08);font-size:12px;white-space:pre-wrap;word-break:break-all;"></div>' +
|
||||
'</div>';
|
||||
cb(html);
|
||||
});
|
||||
plugin.on('ready', function(){
|
||||
try{
|
||||
var tbody = document.getElementById('__vc_uni_log_tbody__');
|
||||
if(!tbody || tbody.__vc_uni_bound__) return;
|
||||
tbody.__vc_uni_bound__ = true;
|
||||
tbody.addEventListener('click', function(e){
|
||||
try{
|
||||
var el = e && e.target;
|
||||
while(el && el !== tbody && el.tagName !== 'TR'){ el = el.parentNode; }
|
||||
if(!el || el === tbody) return;
|
||||
var id = el.getAttribute('data-id') || '';
|
||||
if(!id) return;
|
||||
var detail = document.getElementById('__vc_uni_log_detail__');
|
||||
if(!detail) return;
|
||||
if(logActiveId === id){
|
||||
logActiveId = '';
|
||||
window.__VC_UNI_LOG_ACTIVE_ID__ = '';
|
||||
detail.textContent = '';
|
||||
return;
|
||||
}
|
||||
logActiveId = id;
|
||||
window.__VC_UNI_LOG_ACTIVE_ID__ = id;
|
||||
var it = null;
|
||||
for(var i=0;i<logItems.length;i++){ if(logItems[i] && logItems[i].id === id){ it = logItems[i]; break; } }
|
||||
detail.textContent = it && it.detail ? String(it.detail) : '';
|
||||
}catch(err){}
|
||||
});
|
||||
}catch(err){}
|
||||
});
|
||||
plugin.on('addTool', function(cb){
|
||||
cb([{
|
||||
name: 'Clear',
|
||||
onClick: function(){
|
||||
try{
|
||||
logItems.length = 0;
|
||||
logActiveId = '';
|
||||
window.__VC_UNI_LOG_ACTIVE_ID__ = '';
|
||||
renderLog();
|
||||
var detail = document.getElementById('__vc_uni_log_detail__');
|
||||
if(detail) detail.textContent = '';
|
||||
}catch(e){}
|
||||
}
|
||||
}]);
|
||||
});
|
||||
vc.addPlugin(plugin);
|
||||
window.__VC_UNI_LOG_PLUGIN_ADDED__ = true;
|
||||
setTimeout(renderLog, 30);
|
||||
}catch(e){}
|
||||
}
|
||||
|
||||
function getNameFromUrl(url){
|
||||
try{
|
||||
var s = String(url||'');
|
||||
var idx = s.indexOf('://');
|
||||
if(idx >= 0){
|
||||
var p = s.indexOf('/', idx + 3);
|
||||
if(p >= 0) s = s.slice(p);
|
||||
}
|
||||
if(s.charAt(0) === '/') s = s.slice(1);
|
||||
return s || 'request';
|
||||
}catch(e){
|
||||
return 'request';
|
||||
}
|
||||
}
|
||||
|
||||
function renderNetwork(){
|
||||
try{
|
||||
var tbody = document.getElementById('__vc_uni_net_tbody__');
|
||||
if(!tbody) return;
|
||||
var html = '';
|
||||
for(var i=0;i<netItems.length;i++){
|
||||
var it = netItems[i] || {};
|
||||
var name = it.name || getNameFromUrl(it.url);
|
||||
var method = it.method || '';
|
||||
var status = (it.status===undefined || it.status===null) ? '' : String(it.status);
|
||||
var cost = '';
|
||||
if(it.startTime && it.endTime) cost = String(it.endTime - it.startTime);
|
||||
html += '<tr data-id="' + (it.id || '') + '" style="cursor:pointer;">' +
|
||||
'<td style="padding:6px 4px;word-break:break-all;">' + name + '</td>' +
|
||||
'<td style="padding:6px 4px;text-align:center;">' + method + '</td>' +
|
||||
'<td style="padding:6px 4px;text-align:center;">' + status + '</td>' +
|
||||
'<td style="padding:6px 4px;text-align:center;">' + cost + '</td>' +
|
||||
'</tr>';
|
||||
}
|
||||
tbody.innerHTML = html;
|
||||
}catch(e){}
|
||||
}
|
||||
|
||||
function formatDetail(it){
|
||||
try{
|
||||
if(!it) return '';
|
||||
function esc(s){
|
||||
return String(s==null?'':s).replace(/[&<>"']/g,function(c){
|
||||
return c==='&'?'&':c==='<'?'<':c==='>'?'>':c==='"'?'"':''';
|
||||
});
|
||||
}
|
||||
function pretty(v){
|
||||
try{
|
||||
if(v===undefined) return 'undefined';
|
||||
if(v===null) return 'null';
|
||||
if(typeof v==='string'){
|
||||
var t=v.trim();
|
||||
if((t.charAt(0)==='{' && t.charAt(t.length-1)==='}') || (t.charAt(0)==='[' && t.charAt(t.length-1)===']')){
|
||||
try{ return JSON.stringify(JSON.parse(t), null, 2); }catch(e){}
|
||||
}
|
||||
return v;
|
||||
}
|
||||
if(typeof v==='number' || typeof v==='boolean') return String(v);
|
||||
return JSON.stringify(v, null, 2);
|
||||
}catch(e){
|
||||
return safeStringify(v);
|
||||
}
|
||||
}
|
||||
function renderTable(obj){
|
||||
try{
|
||||
if(!obj) return '<div style="color:#999;padding:4px 0;">(empty)</div>';
|
||||
var keys = [];
|
||||
for(var k in obj){ keys.push(k); }
|
||||
if(!keys.length) return '<div style="color:#999;padding:4px 0;">(empty)</div>';
|
||||
keys.sort();
|
||||
var html = '<table style="width:100%;border-collapse:collapse;">';
|
||||
for(var i=0;i<keys.length;i++){
|
||||
var key = keys[i];
|
||||
var val = obj[key];
|
||||
html += '<tr>' +
|
||||
'<td style="padding:4px 6px;vertical-align:top;width:38%;color:#555;word-break:break-all;">' + esc(key) + '</td>' +
|
||||
'<td style="padding:4px 6px;vertical-align:top;word-break:break-all;">' + esc(typeof val==='string'?val:pretty(val)) + '</td>' +
|
||||
'</tr>';
|
||||
}
|
||||
html += '</table>';
|
||||
return html;
|
||||
}catch(e){
|
||||
return '<div style="color:#999;padding:4px 0;">(invalid)</div>';
|
||||
}
|
||||
}
|
||||
function section(title, body){
|
||||
return '<div style="margin-top:10px;">' +
|
||||
'<div style="font-weight:600;margin:6px 0;">' + esc(title) + '</div>' +
|
||||
body +
|
||||
'</div>';
|
||||
}
|
||||
var time = (it.startTime && it.endTime) ? (it.endTime - it.startTime) : '';
|
||||
var meta = '<div style="word-break:break-all;line-height:1.5;">' +
|
||||
'<div><span style="color:#666;">URL: </span>' + esc(it.url || '') + '</div>' +
|
||||
'<div><span style="color:#666;">Method: </span>' + esc(it.method || '') +
|
||||
' <span style="color:#666;margin-left:10px;">Status: </span>' + esc(it.status || '') +
|
||||
' <span style="color:#666;margin-left:10px;">Time: </span>' + esc(time) + '</div>' +
|
||||
'</div>';
|
||||
|
||||
var query = it.getData || null;
|
||||
var postData = it.postData || null;
|
||||
var resp = it.response;
|
||||
var html = '';
|
||||
html += meta;
|
||||
html += section('Headers', renderTable(it.requestHeader || {}));
|
||||
if(query) html += section('Query', '<pre style="margin:0;white-space:pre-wrap;word-break:break-all;">' + esc(pretty(query)) + '</pre>');
|
||||
if(postData!==null && postData!==undefined && String(postData)!=='') html += section('Payload', '<pre style="margin:0;white-space:pre-wrap;word-break:break-all;">' + esc(pretty(postData)) + '</pre>');
|
||||
html += section('Response Headers', renderTable(it.header || {}));
|
||||
html += section('Response', '<pre style="margin:0;white-space:pre-wrap;word-break:break-all;">' + esc(pretty(resp)) + '</pre>');
|
||||
return html;
|
||||
}catch(e){
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function ensureNetworkPlugin(vc){
|
||||
try{
|
||||
if(!vc) return;
|
||||
if(window.__VC_UNI_NET_PLUGIN_ADDED__) return;
|
||||
if(!window.VConsole || !window.VConsole.VConsolePlugin) return;
|
||||
var plugin = new window.VConsole.VConsolePlugin('uni_u_network', 'U-Net');
|
||||
plugin.on('renderTab', function(cb){
|
||||
var html = '' +
|
||||
'<div style="padding:6px 0;">' +
|
||||
'<table style="width:100%;border-collapse:collapse;font-size:12px;">' +
|
||||
'<thead><tr>' +
|
||||
'<th style="text-align:left;padding:6px 4px;">Name</th>' +
|
||||
'<th style="text-align:center;padding:6px 4px;width:56px;">Method</th>' +
|
||||
'<th style="text-align:center;padding:6px 4px;width:56px;">Status</th>' +
|
||||
'<th style="text-align:center;padding:6px 4px;width:56px;">Time</th>' +
|
||||
'</tr></thead>' +
|
||||
'<tbody id="__vc_uni_net_tbody__"></tbody>' +
|
||||
'</table>' +
|
||||
'<div id="__vc_uni_net_detail__" style="margin-top:8px;padding:6px 4px;border-top:1px solid rgba(0,0,0,.08);font-size:12px;"></div>' +
|
||||
'</div>';
|
||||
cb(html);
|
||||
});
|
||||
plugin.on('ready', function(){
|
||||
try{
|
||||
var tbody = document.getElementById('__vc_uni_net_tbody__');
|
||||
if(!tbody || tbody.__vc_uni_bound__) return;
|
||||
tbody.__vc_uni_bound__ = true;
|
||||
window.__VC_UNI_NET_ACTIVE_ID__ = '';
|
||||
tbody.addEventListener('click', function(e){
|
||||
try{
|
||||
var el = e && e.target;
|
||||
while(el && el !== tbody && el.tagName !== 'TR'){ el = el.parentNode; }
|
||||
if(!el || el === tbody) return;
|
||||
var id = el.getAttribute('data-id') || '';
|
||||
if(!id) return;
|
||||
var detail = document.getElementById('__vc_uni_net_detail__');
|
||||
if(!detail) return;
|
||||
if(window.__VC_UNI_NET_ACTIVE_ID__ === id){
|
||||
window.__VC_UNI_NET_ACTIVE_ID__ = '';
|
||||
detail.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
window.__VC_UNI_NET_ACTIVE_ID__ = id;
|
||||
var it = netById[id];
|
||||
detail.innerHTML = formatDetail(it);
|
||||
}catch(err){}
|
||||
});
|
||||
}catch(err){}
|
||||
});
|
||||
plugin.on('addTool', function(cb){
|
||||
cb([{
|
||||
name: 'Clear',
|
||||
onClick: function(){
|
||||
try{
|
||||
netItems.length = 0;
|
||||
for(var k in netById){ delete netById[k]; }
|
||||
renderNetwork();
|
||||
window.__VC_UNI_NET_ACTIVE_ID__ = '';
|
||||
var detail = document.getElementById('__vc_uni_net_detail__');
|
||||
if(detail) detail.innerHTML = '';
|
||||
}catch(e){}
|
||||
}
|
||||
}]);
|
||||
});
|
||||
vc.addPlugin(plugin);
|
||||
window.__VC_UNI_NET_PLUGIN_ADDED__ = true;
|
||||
setTimeout(renderNetwork, 30);
|
||||
}catch(e){}
|
||||
}
|
||||
|
||||
function handleNetworkAdd(evt){
|
||||
var vc = ensureVConsole();
|
||||
if(!vc) return false;
|
||||
ensureLogPlugin(vc);
|
||||
ensureNetworkPlugin(vc);
|
||||
var item = evt && evt.item ? evt.item : null;
|
||||
var clientId = evt && evt.clientId ? evt.clientId : '';
|
||||
if(!item || !clientId) return true;
|
||||
try{
|
||||
var base = {
|
||||
id: clientId,
|
||||
name: item.name || getNameFromUrl(item.url),
|
||||
method: item.method || '',
|
||||
url: item.url || '',
|
||||
status: item.status || '',
|
||||
startTime: item.startTime || 0,
|
||||
endTime: item.endTime || item.startTime || 0,
|
||||
requestHeader: item.requestHeader || {},
|
||||
getData: item.getData || null,
|
||||
postData: item.postData || null,
|
||||
header: item.header || {},
|
||||
response: item.response || '',
|
||||
};
|
||||
netById[clientId] = base;
|
||||
netItems.push(base);
|
||||
if(netItems.length > 200) netItems.shift();
|
||||
renderNetwork();
|
||||
}catch(e){}
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleNetworkUpdate(evt){
|
||||
var vc = ensureVConsole();
|
||||
if(!vc) return false;
|
||||
ensureLogPlugin(vc);
|
||||
ensureNetworkPlugin(vc);
|
||||
var item = evt && evt.item ? evt.item : null;
|
||||
var clientId = evt && evt.clientId ? evt.clientId : '';
|
||||
if(!item || !clientId) return true;
|
||||
try{
|
||||
var it = netById[clientId];
|
||||
if(!it) return true;
|
||||
if(item.status !== undefined) it.status = item.status;
|
||||
if(item.endTime !== undefined) it.endTime = item.endTime;
|
||||
if(item.url) it.url = item.url;
|
||||
if(item.method) it.method = item.method;
|
||||
if(item.header !== undefined) it.header = item.header || {};
|
||||
if(item.response !== undefined) it.response = item.response;
|
||||
renderNetwork();
|
||||
}catch(e){}
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleLog(evt){
|
||||
try{
|
||||
var vc = ensureVConsole();
|
||||
if(!vc) return false;
|
||||
ensureLogPlugin(vc);
|
||||
var method = (evt && evt.method) || 'log';
|
||||
var args = (evt && evt.args) || [];
|
||||
if(vc && vc.log && typeof vc.log[method] === 'function'){
|
||||
vc.log[method].apply(vc.log, args);
|
||||
}
|
||||
try{
|
||||
var now = new Date();
|
||||
var hh = String(now.getHours()).padStart(2,'0');
|
||||
var mm = String(now.getMinutes()).padStart(2,'0');
|
||||
var ss = String(now.getSeconds()).padStart(2,'0');
|
||||
var msg = '';
|
||||
for(var i=0;i<args.length;i++){
|
||||
msg += (i===0?'':' ') + safeStringify(args[i]);
|
||||
}
|
||||
var id = String(Date.now()) + '_' + String(Math.random()).slice(2,8);
|
||||
logItems.push({
|
||||
id: id,
|
||||
level: method,
|
||||
time: hh + ':' + mm + ':' + ss,
|
||||
msg: msg,
|
||||
detail: safeStringify(args),
|
||||
});
|
||||
if(logItems.length > 200) logItems.shift();
|
||||
renderLog();
|
||||
}catch(e){}
|
||||
var out = [];
|
||||
for(var i=0;i<args.length;i++){ out.push(args[i]); }
|
||||
if(console && console[method]) console[method].apply(console, out);
|
||||
else console.log.apply(console, out);
|
||||
}catch(e){}
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleEvent(evt){
|
||||
if(!evt || !evt.type) return true;
|
||||
if(evt.type === 'log') {
|
||||
var vc = ensureVConsole();
|
||||
if(!vc) return false;
|
||||
ensureNetworkPlugin(vc);
|
||||
return handleLog(evt);
|
||||
}
|
||||
if(evt.type === 'network:add') return handleNetworkAdd(evt);
|
||||
if(evt.type === 'network:update') return handleNetworkUpdate(evt);
|
||||
return true;
|
||||
}
|
||||
|
||||
function flush(){
|
||||
try{
|
||||
var pending = [];
|
||||
for(var i=0;i<q.length;i++){
|
||||
var ok = handleEvent(q[i]);
|
||||
if(ok === false) pending.push(q[i]);
|
||||
}
|
||||
q.length = 0;
|
||||
for(var j=0;j<pending.length;j++) q.push(pending[j]);
|
||||
}catch(e){}
|
||||
}
|
||||
|
||||
window.__VC_UNI_HANDLE_EVENT__ = function(evt){
|
||||
try{
|
||||
handleEvent(evt);
|
||||
}catch(e){}
|
||||
};
|
||||
|
||||
function loadScript(i){
|
||||
var url = URLS[i];
|
||||
if(!url) return;
|
||||
if(document.getElementById('__vconsole_script__')) return;
|
||||
var s = document.createElement('script');
|
||||
s.id = '__vconsole_script__';
|
||||
s.src = url;
|
||||
s.async = true;
|
||||
s.onload = function(){
|
||||
ensureVConsole();
|
||||
flush();
|
||||
};
|
||||
s.onerror = function(){
|
||||
try{s.remove();}catch(e){}
|
||||
loadScript(i+1);
|
||||
};
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
|
||||
if(window.VConsole){
|
||||
ensureVConsole();
|
||||
flush();
|
||||
}else{
|
||||
loadScript(0);
|
||||
}
|
||||
}catch(e){}})();`;
|
||||
};
|
||||
|
||||
const evalJsAllWebviews = (code) => {
|
||||
try {
|
||||
if (!getIsAppPlus() || !plus.webview) return;
|
||||
const all = plus.webview.all?.() || plus.webview.getAllWebview?.() || [];
|
||||
const list = Array.isArray(all) ? all.slice() : [];
|
||||
const launch = plus.webview.getLaunchWebview?.();
|
||||
const top = plus.webview.getTopWebview?.();
|
||||
if (launch) list.push(launch);
|
||||
if (top) list.push(top);
|
||||
|
||||
const seen = new Set();
|
||||
list.forEach((wv) => {
|
||||
try {
|
||||
const key = String(wv?.id || wv?.getURL?.() || '');
|
||||
if (key) {
|
||||
if (seen.has(key)) return;
|
||||
seen.add(key);
|
||||
}
|
||||
if (wv && typeof wv.evalJS === 'function') wv.evalJS(code);
|
||||
} catch (e) {}
|
||||
});
|
||||
} catch (e) {}
|
||||
};
|
||||
|
||||
const pushPendingEvent = (evt) => {
|
||||
const list = uni.__vc_uni_pending_events || (uni.__vc_uni_pending_events = []);
|
||||
list.push(evt);
|
||||
if (list.length > 300) list.splice(0, list.length - 300);
|
||||
};
|
||||
|
||||
const ensureBootstrapPolling = () => {
|
||||
if (uni.__vc_uni_bootstrap_polling) return;
|
||||
uni.__vc_uni_bootstrap_polling = setInterval(() => {
|
||||
try {
|
||||
if (!getIsAppRuntime()) return;
|
||||
if (typeof plus === 'undefined' || !plus?.webview) return;
|
||||
ensureWebviewBootstrap();
|
||||
flushPendingEvents();
|
||||
clearInterval(uni.__vc_uni_bootstrap_polling);
|
||||
uni.__vc_uni_bootstrap_polling = null;
|
||||
} catch (e) {}
|
||||
}, 500);
|
||||
};
|
||||
|
||||
const flushPendingEvents = () => {
|
||||
try {
|
||||
const list = uni.__vc_uni_pending_events;
|
||||
if (!Array.isArray(list) || list.length === 0) return;
|
||||
if (!getIsAppPlus() || !plus?.webview) return;
|
||||
const copy = list.splice(0, list.length);
|
||||
copy.forEach((evt) => {
|
||||
try {
|
||||
sendEventToWebviews(evt);
|
||||
} catch (e) {}
|
||||
});
|
||||
} catch (e) {}
|
||||
};
|
||||
|
||||
const sendEventToWebviews = (evt) => {
|
||||
const payload = JSON.stringify(evt);
|
||||
const js = `(function(){try{
|
||||
var evt=${payload};
|
||||
var q=window.__VC_UNI_EVENT_QUEUE__=window.__VC_UNI_EVENT_QUEUE__||[];
|
||||
q.push(evt);
|
||||
if(window.__VC_UNI_HANDLE_EVENT__) window.__VC_UNI_HANDLE_EVENT__(evt);
|
||||
}catch(e){}})();`;
|
||||
evalJsAllWebviews(js);
|
||||
};
|
||||
|
||||
const ensureWebviewBootstrap = () => {
|
||||
if (!getIsAppRuntime()) return;
|
||||
const state = uni.__vc_uni_bootstrap_state || (uni.__vc_uni_bootstrap_state = { lastAt: 0 });
|
||||
const now = Date.now();
|
||||
if (now - state.lastAt < 500) return;
|
||||
state.lastAt = now;
|
||||
if (!plus?.webview) {
|
||||
setTimeout(ensureWebviewBootstrap, 500);
|
||||
setTimeout(ensureWebviewBootstrap, 1500);
|
||||
ensureBootstrapPolling();
|
||||
return;
|
||||
}
|
||||
const code = buildWebviewBootstrapCode();
|
||||
evalJsAllWebviews(code);
|
||||
setTimeout(() => evalJsAllWebviews(code), 500);
|
||||
setTimeout(() => evalJsAllWebviews(code), 1500);
|
||||
setTimeout(flushPendingEvents, 0);
|
||||
setTimeout(flushPendingEvents, 600);
|
||||
};
|
||||
|
||||
const forwardEventToWebviews = (evt) => {
|
||||
if (!getIsAppRuntime()) return;
|
||||
if (typeof plus === 'undefined' || !plus?.webview) {
|
||||
pushPendingEvent(evt);
|
||||
ensureWebviewBootstrap();
|
||||
ensureBootstrapPolling();
|
||||
return;
|
||||
}
|
||||
sendEventToWebviews(evt);
|
||||
};
|
||||
|
||||
const serializeForLog = (value) => {
|
||||
try {
|
||||
if (value instanceof Error) return value.stack || value.message || String(value);
|
||||
if (typeof value === 'string') return value;
|
||||
if (value === undefined) return 'undefined';
|
||||
if (value === null) return 'null';
|
||||
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') return String(value);
|
||||
return JSON.stringify(value);
|
||||
} catch (e) {
|
||||
try {
|
||||
return String(value);
|
||||
} catch (e2) {
|
||||
return '[unserializable]';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const normalizeHeaders = (headers) => {
|
||||
const out = {};
|
||||
try {
|
||||
if (!headers) return out;
|
||||
Object.keys(headers).forEach((k) => {
|
||||
const v = headers[k];
|
||||
out[String(k)] = typeof v === 'string' ? v : serializeForLog(v);
|
||||
});
|
||||
} catch (e) {}
|
||||
return out;
|
||||
};
|
||||
|
||||
const splitUrl = (url) => {
|
||||
try {
|
||||
const s = String(url || '');
|
||||
const idx = s.indexOf('?');
|
||||
if (idx === -1) return { full: s, getData: null };
|
||||
const query = s.slice(idx + 1);
|
||||
const getData = {};
|
||||
query.split('&').forEach((pair) => {
|
||||
if (!pair) return;
|
||||
const [k, v] = pair.split('=');
|
||||
const key = decodeURIComponent(k || '');
|
||||
if (!key) return;
|
||||
getData[key] = decodeURIComponent(v || '');
|
||||
});
|
||||
return { full: s, getData };
|
||||
} catch (e) {
|
||||
return { full: String(url || ''), getData: null };
|
||||
}
|
||||
};
|
||||
|
||||
const buildNetworkItemBase = ({ method, url, startTime, requestHeader, postData }) => {
|
||||
const info = splitUrl(url);
|
||||
return {
|
||||
method: method || 'GET',
|
||||
url: info.full,
|
||||
status: 0,
|
||||
header: {},
|
||||
requestType: 'custom',
|
||||
requestHeader: requestHeader || {},
|
||||
response: '',
|
||||
startTime,
|
||||
endTime: startTime,
|
||||
getData: info.getData,
|
||||
postData: postData ?? null,
|
||||
};
|
||||
};
|
||||
|
||||
const enableForwarding = () => {
|
||||
if (uni.__vc_uni_forwarding_enabled) return;
|
||||
uni.__vc_uni_forwarding_enabled = true;
|
||||
|
||||
const setConsoleMethod = (method, fn) => {
|
||||
try {
|
||||
console[method] = fn;
|
||||
} catch (e) {}
|
||||
try {
|
||||
Object.defineProperty(console, method, {
|
||||
value: fn,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
});
|
||||
} catch (e) {}
|
||||
};
|
||||
|
||||
const rawConsole = {
|
||||
log: console.log,
|
||||
info: console.info,
|
||||
warn: console.warn,
|
||||
error: console.error,
|
||||
debug: console.debug,
|
||||
};
|
||||
|
||||
const wrappedConsole = {};
|
||||
const wrapMethod = (method) => {
|
||||
const raw = rawConsole[method] || rawConsole.log;
|
||||
const wrapped = (...args) => {
|
||||
try {
|
||||
raw.apply(console, args);
|
||||
} catch (e) {}
|
||||
if (!isVConsoleEnabled()) return;
|
||||
forwardEventToWebviews({
|
||||
type: 'log',
|
||||
method,
|
||||
args: (args || []).map(serializeForLog),
|
||||
at: Date.now(),
|
||||
});
|
||||
};
|
||||
wrappedConsole[method] = wrapped;
|
||||
setConsoleMethod(method, wrapped);
|
||||
};
|
||||
|
||||
['log', 'info', 'warn', 'error', 'debug'].forEach(wrapMethod);
|
||||
|
||||
if (!uni.__vc_uni_console_guard_timer) {
|
||||
uni.__vc_uni_console_guard_timer = setInterval(() => {
|
||||
try {
|
||||
['log', 'info', 'warn', 'error', 'debug'].forEach((method) => {
|
||||
const expected = wrappedConsole[method];
|
||||
if (!expected) return;
|
||||
if (console[method] !== expected) setConsoleMethod(method, expected);
|
||||
});
|
||||
} catch (e) {}
|
||||
}, 1500);
|
||||
}
|
||||
|
||||
if (isVConsoleEnabled()) {
|
||||
forwardEventToWebviews({
|
||||
type: 'log',
|
||||
method: 'log',
|
||||
args: ['[vconsole] forwarding enabled'],
|
||||
at: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const rawRequest = uni.request;
|
||||
if (typeof rawRequest === 'function') {
|
||||
let reqSeq = 0;
|
||||
uni.request = (options = {}) => {
|
||||
const startedAt = Date.now();
|
||||
reqSeq += 1;
|
||||
const clientId = `${startedAt}_${reqSeq}`;
|
||||
const method = String(options?.method || 'GET').toUpperCase();
|
||||
const url = String(options?.url || '');
|
||||
const reqHeader = normalizeHeaders(options?.header);
|
||||
const postData = options?.data ?? null;
|
||||
|
||||
if (isVConsoleEnabled()) {
|
||||
ensureWebviewBootstrap();
|
||||
forwardEventToWebviews({
|
||||
type: 'network:add',
|
||||
clientId,
|
||||
item: buildNetworkItemBase({
|
||||
method,
|
||||
url,
|
||||
startTime: startedAt,
|
||||
requestHeader: reqHeader,
|
||||
postData: typeof postData === 'string' ? postData : postData,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const userSuccess = options?.success;
|
||||
const userFail = options?.fail;
|
||||
const userComplete = options?.complete;
|
||||
|
||||
return rawRequest.call(uni, {
|
||||
...options,
|
||||
success: (res) => {
|
||||
if (isVConsoleEnabled()) {
|
||||
forwardEventToWebviews({
|
||||
type: 'network:update',
|
||||
clientId,
|
||||
item: {
|
||||
status: res?.statusCode ?? '',
|
||||
header: normalizeHeaders(res?.header),
|
||||
response: res?.data ?? '',
|
||||
endTime: Date.now(),
|
||||
},
|
||||
});
|
||||
}
|
||||
if (typeof userSuccess === 'function') userSuccess(res);
|
||||
},
|
||||
fail: (err) => {
|
||||
if (isVConsoleEnabled()) {
|
||||
forwardEventToWebviews({
|
||||
type: 'network:update',
|
||||
clientId,
|
||||
item: {
|
||||
status: 'fail',
|
||||
header: {},
|
||||
response: err ?? '',
|
||||
endTime: Date.now(),
|
||||
},
|
||||
});
|
||||
}
|
||||
if (typeof userFail === 'function') userFail(err);
|
||||
},
|
||||
complete: (res) => {
|
||||
if (typeof userComplete === 'function') userComplete(res);
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const ensureH5VConsole = () => {
|
||||
if (!getHasDom()) return;
|
||||
if (!isVConsoleEnabled()) return;
|
||||
if (window.__vc_uni_h5_inited) return;
|
||||
window.__vc_uni_h5_inited = true;
|
||||
|
||||
const start = () => {
|
||||
const VConsoleCtor = window['VConsole'];
|
||||
if (!VConsoleCtor) return;
|
||||
if (window.__vconsole_instance) return;
|
||||
try {
|
||||
window.__vconsole_instance = new VConsoleCtor();
|
||||
} catch (e) {
|
||||
window.__vc_uni_h5_inited = false;
|
||||
}
|
||||
};
|
||||
|
||||
if (window['VConsole']) {
|
||||
start();
|
||||
return;
|
||||
}
|
||||
|
||||
const loadScript = (idx = 0) => {
|
||||
const url = VCONSOLE_URLS[idx];
|
||||
if (!url) {
|
||||
window.__vc_uni_h5_inited = false;
|
||||
return;
|
||||
}
|
||||
if (window.document.getElementById('__vconsole_script__')) return;
|
||||
const script = window.document.createElement('script');
|
||||
script.id = '__vconsole_script__';
|
||||
script.src = url;
|
||||
script.async = true;
|
||||
script.onload = start;
|
||||
script.onerror = () => {
|
||||
script.remove();
|
||||
loadScript(idx + 1);
|
||||
};
|
||||
window.document.head.appendChild(script);
|
||||
};
|
||||
|
||||
loadScript(0);
|
||||
};
|
||||
|
||||
export const setupVConsole = () => {
|
||||
if (uni.__vc_uni_setup_done) return;
|
||||
uni.__vc_uni_setup_done = true;
|
||||
|
||||
uni.__ensureVConsole = () => {
|
||||
if (!isVConsoleEnabled()) return;
|
||||
if (getIsAppRuntime()) ensureWebviewBootstrap();
|
||||
ensureH5VConsole();
|
||||
};
|
||||
|
||||
const boot = () => {
|
||||
if (!isVConsoleEnabled()) return;
|
||||
uni.__ensureVConsole();
|
||||
enableForwarding();
|
||||
};
|
||||
|
||||
boot();
|
||||
setTimeout(boot, 0);
|
||||
setTimeout(boot, 500);
|
||||
setTimeout(boot, 1500);
|
||||
};
|
||||
Reference in New Issue
Block a user