vconsole-helper
Version:
1,075 lines (1,034 loc) • 34 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.vConsoleHelper = {}));
})(this, (function (exports) { 'use strict';
var dom = {};
Object.defineProperty(dom, '__esModule', { value: true });
function insertStyle(_a) {
var _b;
var id = _a.id,
content = _a.content;
var idObjectStyle = document.getElementById(id);
(_b = idObjectStyle === null || idObjectStyle === void 0 ? void 0 : idObjectStyle.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(idObjectStyle);
var styleNode = document.createElement('style');
styleNode.id = id;
styleNode.type = 'text/css';
styleNode.innerHTML = content;
document.getElementsByTagName('head')[0].appendChild(styleNode);
}
function insertHtml(_a) {
var _b;
var id = _a.id,
content = _a.content;
var idObject = document.getElementById(id);
(_b = idObject === null || idObject === void 0 ? void 0 : idObject.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(idObject);
var shareNode = document.createElement('div');
shareNode.id = id;
shareNode.style.display = 'none';
shareNode.innerHTML = content;
document.getElementsByTagName('body')[0].appendChild(shareNode);
}
dom.insertHtml = insertHtml;
var insertStyle_1 = dom.insertStyle = insertStyle;
var loader$1 = {};
var littleLoader = {};
Object.defineProperty(littleLoader, '__esModule', { value: true });
var addScript = function addScript(script) {
var _a;
// Get the first script element, we're just going to use it
// as a reference for where to insert ours. Do NOT try to do
// this just once at the top and then re-use the same script
// as a reference later. Some weird loaders *remove* script
// elements after the browser has executed their contents,
// so the same reference might not have a parentNode later.
var firstScript = document.getElementsByTagName('script')[0];
// Append the script to the DOM, triggering execution.
(_a = firstScript === null || firstScript === void 0 ? void 0 : firstScript.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(script, firstScript);
};
/**
* 以 Callback 的方式加载 js 文件
* @param {String} src js文件路径
* @param {Function|Object} callback 加载回调
* @param {String} charset 指定js的字符集
* @param {Object} context Callback context
*/
var loader = function loader(src, callback, charset, context) {
if (charset === void 0) {
charset = 'utf-8';
}
if (context === void 0) {
context = null;
}
var setup;
if (callback && typeof callback !== 'function') {
context = callback.context || context;
setup = callback.setup;
callback = callback.callback;
}
var done = false;
var err;
var privateCleanup; // _must_ be set below.
/**
* Final handler for error or completion.
*
* **Note**: Will only be called _once_.
*
* @returns {void}
*/
var privateFinish = function privateFinish() {
// Only call once.
if (done) {
return;
}
done = true;
// Internal cleanup.
privateCleanup === null || privateCleanup === void 0 ? void 0 : privateCleanup();
// Callback.
if (callback) {
callback.call(context, err);
}
};
/**
* Error handler
*
* @returns {void}
*/
var privateError = function privateError() {
err = new Error(src || 'EMPTY');
privateFinish();
};
var curScript = document.querySelector("script[src=\"".concat(src, "\"]"));
if (curScript) {
var tc_1 = setInterval(function () {
if (curScript.isready) {
// 判断js加载完成
privateFinish();
clearInterval(tc_1);
}
}, 20);
} else {
var script_1 = document.createElement('script');
script_1.isready = false;
if (script_1.readyState && !('async' in script_1)) {
var isReady_1 = {
loaded: true,
complete: true
};
var inserted_1 = false;
// Clear out listeners, state.
privateCleanup = function privateCleanup() {
script_1.onreadystatechange = null;
script_1.onerror = null;
};
// Attach the handler before setting src, otherwise we might
// miss events (consider that IE could fire them synchronously
// upon setting src, for example).
script_1.onreadystatechange = function () {
var firstState = script_1.readyState;
// Protect against any errors from state change randomness.
if (err) {
return;
}
if (!inserted_1 && isReady_1[firstState]) {
inserted_1 = true;
// Append to DOM.
addScript(script_1);
}
if (firstState === 'loaded') {
// The act of accessing the property should change the script's
// `readyState`.
//
// And, oh yeah, this hack is so hacky-ish we need the following
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
script_1.children;
if (script_1.readyState === 'loading') {
// State transitions indicate we've hit the load error.
//
// **Note**: We are not intending to _return_ a value, just have
// a shorter short-circuit code path here.
return privateError();
}
}
// It's possible for readyState to be "complete" immediately
// after we insert (and execute) the script in the branch
// above. So check readyState again here and react without
// waiting for another onreadystatechange.
if (script_1.readyState === 'complete') {
script_1.isready = true;
privateFinish();
}
};
// Onerror handler _may_ work here.
script_1.onerror = privateError;
// call the setup callback to mutate the script tag
if (setup) {
setup.call(context, script_1);
}
// This triggers a request for the script, but its contents won't
// be executed until we append it to the DOM.
script_1.src = src;
// In some cases, the readyState is already "loaded" immediately
// after setting src. It's a lie! Don't append to the DOM until
// the onreadystatechange event says so.
} else {
// This section is for modern browsers, including IE10+.
// Clear out listeners.
privateCleanup = function privateCleanup() {
script_1.onload = null;
script_1.onerror = null;
};
script_1.onerror = privateError;
script_1.onload = function () {
script_1.isready = true;
privateFinish();
};
script_1.async = true;
script_1.charset = charset || 'utf-8';
// call the setup callback to mutate the script tag
if (setup) {
setup.call(context, script_1);
}
script_1.src = src;
// Append to DOM.
addScript(script_1);
}
}
};
littleLoader.loader = loader;
Object.defineProperty(loader$1, '__esModule', { value: true });
var loader_littleLoader = littleLoader;
/**
* 以 Promise 的方式加载 js 文件
* @param {string} url js文件路径
* @returns {Promise<number>} promise
*/
function loadJS(url) {
return new Promise(function (resolve) {
loader_littleLoader.loader(url, function () {
resolve(1);
});
});
}
/**
* 动态加载CSS
* @param {string} url CSS链接
* @example
*
* loadCSS('xxx.css')
*/
function loadCSS(url) {
var _a;
var addSign = true;
var links = document.getElementsByTagName('link');
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (var i = 0; i < links.length; i++) {
if (((_a = links[i]) === null || _a === void 0 ? void 0 : _a.href) && links[i].href.indexOf(url) !== -1) {
addSign = false;
}
}
if (addSign) {
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
document.getElementsByTagName('head')[0].appendChild(link);
}
}
loader$1.loadCSS = loadCSS;
var loadJS_1 = loader$1.loadJS = loadJS;
const BUILD_NAME_MAP = {
build: '_vConsoleBuildInfo',
commit: '_vConsoleCommitInfo',
};
const V_CONSOLE_DOM = {
LINE: 'line',
WRAP: 'v-console-custom-tab',
URL_INPUT_ID: 'vConsolePluginInput',
URL_JUMP_BUTTON: 'vConsolePluginUrlJumpButton',
GO_BACK_BUTTON: 'vConsolePluginGoBackButton',
PLUGIN_NAME_PREFIX: '__vc_plug_',
// 需要小写,作为插件 id
PLUGIN_VERSION_NAME: 'version_performance',
PLUGIN_SIMPLE_VERSION_NAME: 'simple_version',
};
const EMPTY_LINE = `<div class="${V_CONSOLE_DOM.LINE}"> </div>`;
const V_CONSOLE_NO_DELAY = {
KEY: 'vConsole_no_delay',
VALUE: '1',
};
const V_CONSOLE_URL = 'https://image-1251917893.file.myqcloud.com/igame/npm/vconsole%403.15.1/vconsole.min.js';
const V_CONSOLE_STYLE_CONTENT = `
.${V_CONSOLE_DOM.WRAP} {
padding: 12px 16px 30px;
user-select: auto;
}
.${V_CONSOLE_DOM.WRAP} .${V_CONSOLE_DOM.LINE} {
line-height: 20px;
padding: 5px 0;
color: var(--VC-PURPLE, #6467f0);
word-break: break-all;
user-select: auto;
}
.${V_CONSOLE_DOM.WRAP} textarea {
display: block;
width: 100%;
min-width: 0;
padding: 0;
color: #323233;
line-height: inherit;
text-align: left;
background-color: transparent;
resize: none;
border: 1px solid #ddd;
border-radius: 3px;
margin-bottom: 10px;
height: 60px;
padding: 4px;
line-height: 16px;
font-size: 13px;
user-select: auto;
}
.${V_CONSOLE_DOM.WRAP} textarea:focus {
outline: none;
}
.${V_CONSOLE_DOM.WRAP} button {
height: 30px;
line-height: 1.2;
text-align: center;
border-radius: 2px;
cursor: pointer;
color: #fff;
background-color: #07c160;
border: 1px solid #07c160;
font-size: 14px;
padding: 0 12px;
margin-right: 10px;
}
.vc-cmd,
.vc-cmd-input {
user-select: auto !important;
}
#${V_CONSOLE_DOM.URL_INPUT_ID} {
user-select: auto !important;
}
`;
const DEBUG_CGI_ENV = {
KEY: 'tip_debug_cgi_env',
PROD: 'prod',
TEST: 'test',
};
const BUILD_LIST = [
{
key: 'time',
label: 'Build Time',
},
{
key: 'author',
label: 'Build Author',
},
{
key: 'branch',
label: 'Build Branch',
},
{
key: 'netEnv',
label: 'Build Net Env',
},
];
const COMMIT_LIST = [
{
key: 'message',
label: 'Last Commit Message',
},
{
key: 'author',
label: 'Last Commit Author',
},
{
key: 'date',
label: 'Last Commit Time',
},
{
key: 'hash',
label: 'Last Commit Hash',
},
];
const AEGIS_PERFORMANCE_KEY = '__AEGIS_PERFORMANCE';
const AEGIS_PERFORMANCE_LIST = [
{
key: 'dnsLookup',
label: 'Aegis DNS 查询',
},
{
key: 'tcp',
label: 'Aegis TCP 链接',
},
{
key: 'ttfb',
label: 'Aegis SSL 建连',
},
{
key: 'contentDownload',
label: 'Aegis contentDownload',
},
{
key: 'resourceDownload',
label: 'Aegis resourceDownload',
},
{
key: 'domParse',
label: 'Aegis DOM解析',
},
{
key: 'firstScreenTiming',
label: 'Aegis 首屏耗时',
},
];
function getCurrentState() {
const value = window.sessionStorage.getItem(V_CONSOLE_NO_DELAY.KEY);
if (value === V_CONSOLE_NO_DELAY.VALUE) {
return '已去掉延迟';
}
return '默认';
}
function initLoadDelayPlugin() {
const plugin = new window.VConsole.VConsolePlugin('loadDelay', 'vConsole加载延迟');
const html = `<div class="${V_CONSOLE_DOM.WRAP}">
<div class="${V_CONSOLE_DOM.LINE}">当前状态:${getCurrentState()}</div>
</div>`;
plugin.on('renderTab', (callback) => {
callback(html);
});
const btnList = [];
btnList.push({
name: '去除延迟',
global: false,
onClick() {
sessionStorage.setItem(V_CONSOLE_NO_DELAY.KEY, V_CONSOLE_NO_DELAY.VALUE);
console.log('已设置去除延迟,即将刷新页面......');
setTimeout(() => {
location.reload();
}, 1000);
},
});
btnList.push({
name: '恢复延迟',
global: false,
onClick() {
sessionStorage.removeItem(V_CONSOLE_NO_DELAY.KEY);
console.log('已设置恢复延迟,即将刷新页面......');
setTimeout(() => {
location.reload();
}, 1000);
},
});
btnList.push({
name: '刷新页面',
global: false,
onClick() {
window.location.reload();
},
});
plugin.on('addTool', (callback) => {
callback(btnList);
});
return plugin;
}
function getCurrentEnv() {
const value = window.sessionStorage.getItem(DEBUG_CGI_ENV.KEY);
if (value === DEBUG_CGI_ENV.PROD) {
return '正式';
}
if (value === DEBUG_CGI_ENV.TEST) {
return '测试';
}
return '默认';
}
function initSwitchEnvPlugin() {
const tipPlugin = new window.VConsole.VConsolePlugin('switchEnv', '切换环境');
const currentEnv = getCurrentEnv();
const html = `<div class="${V_CONSOLE_DOM.WRAP}">
<div class="${V_CONSOLE_DOM.LINE}">当前环境:${currentEnv}</div>
</div>`;
tipPlugin.on('renderTab', (callback) => {
callback(html);
});
tipPlugin.on('addTool', (callback) => {
const toolList = [];
toolList.push({
name: '测试环境',
global: false,
onClick() {
console.log('已切换为测试CGI,即将刷新页面......');
window.sessionStorage.setItem(DEBUG_CGI_ENV.KEY, DEBUG_CGI_ENV.TEST);
setTimeout(() => {
location.reload();
}, 1000);
},
});
toolList.push({
name: '现网环境',
global: false,
onClick() {
console.log('已切换为正式CGI,即将刷新页面......');
window.sessionStorage.setItem(DEBUG_CGI_ENV.KEY, DEBUG_CGI_ENV.PROD);
setTimeout(() => {
location.reload();
}, 1000);
},
});
callback(toolList);
});
return tipPlugin;
}
var clipboardWeb$1 = {};
Object.defineProperty(clipboardWeb$1, '__esModule', { value: true });
/**
* 复制到剪切板
*
* @param {string} text 待复制的文本
* @returns {Promise<void>}
* @example
*
* ```ts
* clipboardMp('stupid').then(() => {});
* ```
*/
function clipboardWeb(text) {
return new Promise(function (resolve, reject) {
var pasteText = document.getElementById('#clipboard');
pasteText === null || pasteText === void 0 ? void 0 : pasteText.remove();
var textarea = document.createElement('textarea');
textarea.id = '#clipboard';
textarea.style.position = 'fixed';
textarea.style.top = '-9999px';
textarea.style.zIndex = '-9999';
document.body.appendChild(textarea);
textarea.value = "".concat(text);
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
var result = document.execCommand('Copy', false);
textarea.blur();
if (result) {
resolve();
} else {
reject();
}
});
}
var clipboardWeb_2 = clipboardWeb$1.clipboardWeb = clipboardWeb;
function copyInfo(text) {
clipboardWeb_2(text).then(() => {
alert('已复制,开去粘贴吧~');
})
.catch(() => {
alert('当前环境暂不支持复制,请长按选择复制~');
});
}
function initFeedbackPlugin(uid = '') {
const loginPlugin = new window.VConsole.VConsolePlugin('feedback', '反馈');
loginPlugin.on('init', () => {
// this.list = [];
});
const url = window.location.href;
const UA = navigator.userAgent;
const { cookie } = document;
const html = `<div class="${V_CONSOLE_DOM.WRAP}">
<div class="${V_CONSOLE_DOM.LINE}">url:${url}</div>
<div class="${V_CONSOLE_DOM.LINE}">uid:${uid}</div>
<div class="${V_CONSOLE_DOM.LINE}">ua:${UA}</div>
<div class="${V_CONSOLE_DOM.LINE}">cookie:${cookie}</div>
<div class="${V_CONSOLE_DOM.LINE}">页面宽高:${document.documentElement.clientWidth}*${document.documentElement.clientHeight}</div>
</div>
`;
loginPlugin.on('renderTab', (callback) => {
callback(html);
});
const btnList = [];
btnList.push({
name: '复制用户信息',
global: false,
onClick() {
const userInfo = { url: window.location.href, uid, UA, cookie };
copyInfo(JSON.stringify(userInfo));
},
});
loginPlugin.on('addTool', (callback) => {
callback(btnList);
});
return loginPlugin;
}
function initMsdkPlugin() {
const plugin = new window.VConsole.VConsolePlugin('msdk', 'msdk工具');
const html = `<div class="${V_CONSOLE_DOM.WRAP}">
<div class="${V_CONSOLE_DOM.LINE}">msdk工具</div>
</div>`;
plugin.on('renderTab', (callback) => {
callback(html);
});
const btnList = [];
btnList.push({
name: '关闭页面',
global: false,
onClick() {
var _a, _b;
// @ts-ignore
(_b = (_a = window === null || window === void 0 ? void 0 : window.app) === null || _a === void 0 ? void 0 : _a.closeWebView) === null || _b === void 0 ? void 0 : _b.call(_a);
},
});
plugin.on('addTool', (callback) => {
callback(btnList);
});
return plugin;
}
let inputValue;
function updateInputValue(event) {
var _a;
inputValue = ((_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.value) || '';
}
function jumpToUrl() {
if (!inputValue)
return;
location.href = inputValue;
}
function goBack() {
var _a, _b;
history.go(-1);
(_b = (_a = window.vConsole) === null || _a === void 0 ? void 0 : _a.hide) === null || _b === void 0 ? void 0 : _b.call(_a);
}
function renderPlugin(callback) {
const parseNumber = (num) => +(+num).toFixed(2);
let html = `<div class="${V_CONSOLE_DOM.WRAP}">`;
html += getPerformanceInfo()
.map((item) => {
const { label, value } = item;
return `<div class="${V_CONSOLE_DOM.LINE}">${label}:${parseNumber(value)}ms </div>`;
})
.concat(EMPTY_LINE)
.concat(getVersionHtml())
.concat(EMPTY_LINE)
.concat(getAegisPerformanceInfo())
.join('\n');
html += `
<textarea id="${V_CONSOLE_DOM.URL_INPUT_ID}" type="text" placeholder="请输入跳转路径"></textarea>
<button id="${V_CONSOLE_DOM.URL_JUMP_BUTTON}">跳转</button>
<button id="${V_CONSOLE_DOM.GO_BACK_BUTTON}">返回上一页</button>
`;
html += '</div>';
callback(html);
}
function initVersionPlugin() {
const plugin = new window.VConsole.VConsolePlugin(V_CONSOLE_DOM.PLUGIN_VERSION_NAME, '其他信息');
const callback = function (html) {
const dom = document.getElementById(`${V_CONSOLE_DOM.PLUGIN_NAME_PREFIX}${V_CONSOLE_DOM.PLUGIN_VERSION_NAME}`);
if (dom) {
dom.innerHTML = html;
}
};
plugin.on('renderTab', (callback) => {
renderPlugin(callback);
});
plugin.on('showConsole', () => {
renderPlugin(callback);
});
plugin.on('show', () => {
renderPlugin(callback);
});
const btnList = [];
btnList.push({
name: '隐藏vConsole',
global: false,
onClick() {
var _a;
(_a = window.vConsole) === null || _a === void 0 ? void 0 : _a.destroy();
},
});
plugin.on('addTool', (callback) => {
callback(btnList);
});
plugin.on('show', () => {
var _a, _b, _c;
(_a = document.getElementById(V_CONSOLE_DOM.URL_INPUT_ID)) === null || _a === void 0 ? void 0 : _a.addEventListener('input', updateInputValue);
(_b = document.getElementById(V_CONSOLE_DOM.URL_JUMP_BUTTON)) === null || _b === void 0 ? void 0 : _b.addEventListener('click', jumpToUrl);
(_c = document.getElementById(V_CONSOLE_DOM.GO_BACK_BUTTON)) === null || _c === void 0 ? void 0 : _c.addEventListener('click', goBack);
});
plugin.on('hide', () => {
var _a, _b, _c;
(_a = document.getElementById(V_CONSOLE_DOM.URL_INPUT_ID)) === null || _a === void 0 ? void 0 : _a.removeEventListener('input', updateInputValue);
(_b = document.getElementById(V_CONSOLE_DOM.URL_JUMP_BUTTON)) === null || _b === void 0 ? void 0 : _b.removeEventListener('click', jumpToUrl);
(_c = document.getElementById(V_CONSOLE_DOM.GO_BACK_BUTTON)) === null || _c === void 0 ? void 0 : _c.addEventListener('click', goBack);
});
return plugin;
}
function getPerformanceInfo() {
var _a;
const timing = performance.timing || {};
const timeOrigin = ((_a = performance === null || performance === void 0 ? void 0 : performance.wx) === null || _a === void 0 ? void 0 : _a.timeOrigin) || timing.fetchStart;
const dnsTime = timing.domainLookupEnd - timing.domainLookupStart;
const tcpTime = timing.connectEnd - timing.connectStart;
const backendTime = timing.responseStart - timing.requestStart;
const respTime = timing.responseEnd - timing.responseStart;
const domTime = timing.domContentLoadedEventStart - timing.responseEnd;
const firstRenderTime = timing.domLoading - timeOrigin;
const wholePageTime = timing.loadEventEnd - timeOrigin;
const parseDomTime = timing.domComplete - timing.domInteractive;
const list = [
{
value: dnsTime,
label: 'DNS连接耗时',
},
{
value: tcpTime,
label: 'TCP连接耗时',
},
{
value: backendTime,
label: '后端响应时间',
},
{
value: respTime,
label: 'HTML页面下载时间',
},
{
value: domTime,
label: 'DOM时间',
},
{
value: parseDomTime,
label: '解析DOM树耗时',
},
{
value: firstRenderTime,
label: '首次加载耗时',
},
{
value: wholePageTime,
label: '整页耗时',
},
];
return list;
}
function getVersionHtml() {
const buildInfo = (window[BUILD_NAME_MAP.build] || {});
const commitInfo = (window[BUILD_NAME_MAP.commit] || {});
const buildHtmlList = BUILD_LIST.map((item) => {
const { key, label } = item;
return `<div class="${V_CONSOLE_DOM.LINE}">${label}: ${buildInfo[key] || ''}</div>`;
});
const commitHtmlList = COMMIT_LIST.map((item) => {
const { key, label } = item;
return `<div class="${V_CONSOLE_DOM.LINE}">${label}: ${commitInfo[key] || ''}</div>`;
});
return [
...buildHtmlList,
EMPTY_LINE,
...commitHtmlList,
EMPTY_LINE,
EMPTY_LINE,
].join('\n');
}
function getAegisPerformanceInfo() {
const perfInfo = (window[AEGIS_PERFORMANCE_KEY] || {});
const perfHtmlList = AEGIS_PERFORMANCE_LIST.map((item) => {
var _a;
const { key, label } = item;
return `<div class="${V_CONSOLE_DOM.LINE}">${label}: ${(_a = perfInfo[key]) !== null && _a !== void 0 ? _a : ''}</div>`;
});
return [
EMPTY_LINE,
...perfHtmlList,
EMPTY_LINE,
].join('\n');
}
var time = {};
Object.defineProperty(time, '__esModule', { value: true });
/**
* 将时间戳格式化
* @param {number} timestamp
* @param {string} fmt
* @param {string} [defaultVal]
* @returns {string} 格式化后的日期字符串
* @example
*
* const stamp = new Date('2020-11-27 8:23:24').getTime();
*
* const res = timeStampFormat(stamp, 'yyyy-MM-dd hh:mm:ss')
*
* // 2020-11-27 08:23:24
*/
function timeStampFormat(timestamp, fmt, defaultVal, whitePrefix) {
if (whitePrefix === void 0) {
whitePrefix = '';
}
if (!timestamp) {
return defaultVal || '';
}
var date = new Date();
if ("".concat(timestamp).length === 10) {
timestamp *= 1000;
}
date.setTime(timestamp);
var o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
'q+': Math.floor((date.getMonth() + 3) / 3),
S: date.getMilliseconds() // 毫秒
};
var reg = /(y+)/;
if (whitePrefix) {
reg = new RegExp("(?:^|(?:[^".concat(whitePrefix, "y]))(y+)"));
}
var match = fmt.match(reg);
if (match === null || match === void 0 ? void 0 : match[1]) {
fmt = fmt.replace(match[1], "".concat(date.getFullYear()).slice(4 - match[1].length));
}
// eslint-disable-next-line no-restricted-syntax
for (var k in o) {
var reg_1 = new RegExp("(".concat(k, ")"));
if (whitePrefix) {
reg_1 = new RegExp("(?:^|(?:[^".concat(whitePrefix).concat(k[0], "]))(").concat(k, ")"));
}
match = fmt.match(reg_1);
if (match === null || match === void 0 ? void 0 : match[1]) {
var _a = match.index,
index = _a === void 0 ? 0 : _a;
var realIndex = whitePrefix ? index + match[0].length - match[1].length : index;
var str = "".concat(o[k]);
var len = match[1].length;
var replacePart = len === 1 ? str : "00".concat(str).slice("".concat(str).length);
fmt = fmt.slice(0, realIndex) + replacePart + fmt.slice(realIndex + len);
// fmt = fmt.replace(
// match[1],
// match[1].length === 1 ? str : `00${str}`.slice(`${str}`.length),
// );
}
}
if (whitePrefix) {
fmt = fmt.replace(new RegExp(whitePrefix, 'g'), '');
}
return fmt;
}
/**
* 将日期格式化
* @param {Date} date
* @param {string} format
* @returns {string} 格式化后的日期字符串
* @example
*
* const date = new Date('2020-11-27 8:23:24');
*
* const res = dateFormat(date, 'yyyy-MM-dd hh:mm:ss')
*
* // 2020-11-27 08:23:24
*/
function dateFormat(date, fmt) {
var timestamp = new Date(date).getTime();
return timeStampFormat(timestamp, fmt);
}
var dateFormat_1 = time.dateFormat = dateFormat;
time.timeStampFormat = timeStampFormat;
function renderVersion(callback) {
// @ts-ignore
const info = window.igameVersion;
let innerHtml = '';
if (info === null || info === void 0 ? void 0 : info.version) {
const time = `${dateFormat_1(new Date(+info.version), 'yyyy-MM-dd hh:mm:ss')}`;
innerHtml = `
<div class="${V_CONSOLE_DOM.LINE}">构建时间:${time || ''}</div>
<div class="${V_CONSOLE_DOM.LINE}">构建作者:${info.author || ''}</div>
`;
}
else {
innerHtml = ` <div class="${V_CONSOLE_DOM.LINE}">无构建信息</div>`;
}
callback(`<div class="${V_CONSOLE_DOM.WRAP}">${innerHtml}</div>`);
}
function initVersionSimplePlugin() {
const plugin = new window.VConsole.VConsolePlugin(V_CONSOLE_DOM.PLUGIN_SIMPLE_VERSION_NAME, '版本信息');
const callback = function (html) {
const dom = document.getElementById(`${V_CONSOLE_DOM.PLUGIN_NAME_PREFIX}${V_CONSOLE_DOM.PLUGIN_SIMPLE_VERSION_NAME}`);
if (dom) {
dom.innerHTML = html;
}
};
// 先加载version.js,种上IGameVersion对象
plugin.on('renderTab', (callback) => {
renderVersion(callback);
});
plugin.on('showConsole', () => {
renderVersion(callback);
});
plugin.on('show', () => {
renderVersion(callback);
});
return plugin;
}
/**
* 加载 vConsole
* @param {Object} [options = {}] vConsole 选项
* @param {Array<string>} [plugins = []] 插件列表
* @returns {Promise<Object>} vConsole 实例
*
* @example
* ```ts
* loadVConsole()
* ```
*/
function loadVConsole(options = {}, plugins = []) {
return new Promise((resolve) => {
if (typeof window.VConsole === 'undefined') {
loadJS_1(V_CONSOLE_URL).then(() => {
resolve(initVConsole(options, plugins));
});
}
else {
resolve(initVConsole(options, plugins));
}
});
}
function initVConsole(options, plugins) {
const vConsole = new window.VConsole(Object.assign({}, (options || {})));
vConsole.addPlugin(initVersionPlugin());
vConsole.addPlugin(initFeedbackPlugin());
vConsole.addPlugin(initSwitchEnvPlugin());
vConsole.addPlugin(initLoadDelayPlugin());
vConsole.addPlugin(initVersionSimplePlugin());
vConsole.addPlugin(initMsdkPlugin());
plugins.forEach((plugin) => {
vConsole.addPlugin(plugin());
});
insertStyle_1({
id: 'vConsolePluginStyle',
content: V_CONSOLE_STYLE_CONTENT,
});
if (window && !window.vConsole) {
window.vConsole = vConsole;
}
return vConsole;
}
const V_CONSOLE_STORAGE = {
KEY: 'SHOW_V_CONSOLE',
VALUE: '1',
};
/**
* vConsole 当前展示状态
*/
const V_CONSOLE_STATE = {
show: false,
};
function loadTheVConsole() {
loadVConsole().then((instance) => {
window.vConsole = instance;
});
}
/**
* 展示 vConsole
* @example
* ```ts
* showVConsole()
* ```
*/
function showVConsole() {
V_CONSOLE_STATE.show = true;
localStorage.setItem(V_CONSOLE_STORAGE.KEY, V_CONSOLE_STORAGE.VALUE);
loadTheVConsole();
}
/**
* 关闭 vConsole
* @example
* ```ts
* closeVConsole()
* ```
*/
function closeVConsole() {
var _a;
localStorage.removeItem(V_CONSOLE_STORAGE.KEY);
V_CONSOLE_STATE.show = false;
(_a = window.vConsole) === null || _a === void 0 ? void 0 : _a.destroy();
}
/**
* 切换展示 vConsole
* @returns 是否展示
* @example
* ```ts
* toggleVConsole()
* ```
*/
function toggleVConsole() {
if (V_CONSOLE_STATE.show) {
closeVConsole();
}
else {
showVConsole();
}
return V_CONSOLE_STATE.show;
}
/**
* 检查 localStorage 设置,并展示vConsole
* @example
* ```ts
* checkAndShowVConsole()
* ```
*/
function checkAndShowVConsole() {
const showVConsole = localStorage.getItem(V_CONSOLE_STORAGE.KEY) === V_CONSOLE_STORAGE.VALUE;
if (showVConsole) {
V_CONSOLE_STATE.show = true;
loadTheVConsole();
}
}
/**
* 生成 v-console
* 有几种情况:
* 1. 不显示
* 2. 立即显示
* 3. 异步判断后,确定是否显示
* @param params 参数
* @example
*
* ```ts
* genVConsole({
* immediateShow: isShowVConsole === 'true'
* || isTestEnv()
* || noDelay === V_CONSOLE_NO_DELAY.VALUE,
* hide: isShowVConsole === 'false' || !!UserInfo.tipUid(),
* asyncConfirmFunc: checkIsDevList,
* });
* ```
*/
function genVConsole({ immediateShow = false, hide = false, vConsoleConfig = {}, asyncConfirmFunc, }) {
var _a;
if (hide) {
return;
}
if (immediateShow) {
loadVConsole(vConsoleConfig);
return;
}
if (typeof asyncConfirmFunc === 'function') {
(_a = asyncConfirmFunc === null || asyncConfirmFunc === void 0 ? void 0 : asyncConfirmFunc()) === null || _a === void 0 ? void 0 : _a.then(() => {
loadVConsole(vConsoleConfig);
}).catch((error) => {
console.log('checkIsDevList', error);
});
}
}
exports.BUILD_LIST = BUILD_LIST;
exports.BUILD_NAME_MAP = BUILD_NAME_MAP;
exports.COMMIT_LIST = COMMIT_LIST;
exports.DEBUG_CGI_ENV = DEBUG_CGI_ENV;
exports.V_CONSOLE_DOM = V_CONSOLE_DOM;
exports.V_CONSOLE_NO_DELAY = V_CONSOLE_NO_DELAY;
exports.V_CONSOLE_STATE = V_CONSOLE_STATE;
exports.checkAndShowVConsole = checkAndShowVConsole;
exports.closeVConsole = closeVConsole;
exports.genVConsole = genVConsole;
exports.loadVConsole = loadVConsole;
exports.showVConsole = showVConsole;
exports.toggleVConsole = toggleVConsole;
Object.defineProperty(exports, '__esModule', { value: true });
}));