vue-debug-helper

Vue components debug helper

Pada tanggal 16 Mei 2022. Lihat %(latest_version_link).

  1. // ==UserScript==
  2. // @name vue-debug-helper
  3. // @name:en vue-debug-helper
  4. // @name:zh Vue调试分析助手
  5. // @name:zh-TW Vue調試分析助手
  6. // @name:ja Vueデバッグ分析アシスタント
  7. // @namespace https://github.com/xxxily/vue-debug-helper
  8. // @homepage https://github.com/xxxily/vue-debug-helper
  9. // @version 0.0.16
  10. // @description Vue components debug helper
  11. // @description:en Vue components debug helper
  12. // @description:zh Vue组件探测、统计、分析辅助脚本
  13. // @description:zh-TW Vue組件探測、統計、分析輔助腳本
  14. // @description:ja Vueコンポーネントの検出、統計、分析補助スクリプト
  15. // @author ankvps
  16. // @icon https://cdn.jsdelivr.net/gh/xxxily/vue-debug-helper@main/logo.png
  17. // @match http://*/*
  18. // @match https://*/*
  19. // @grant unsafeWindow
  20. // @grant GM_getResourceText
  21. // @grant GM_addStyle
  22. // @grant GM_setValue
  23. // @grant GM_getValue
  24. // @grant GM_deleteValue
  25. // @grant GM_listValues
  26. // @grant GM_addValueChangeListener
  27. // @grant GM_removeValueChangeListener
  28. // @grant GM_registerMenuCommand
  29. // @grant GM_unregisterMenuCommand
  30. // @grant GM_getTab
  31. // @grant GM_saveTab
  32. // @grant GM_getTabs
  33. // @grant GM_openInTab
  34. // @grant GM_download
  35. // @grant GM_xmlhttpRequest
  36. // @require https://cdn.jsdelivr.net/npm/localforage@1.10.0/dist/localforage.min.js
  37. // @require https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/core.js
  38. // @require https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/md5.js
  39. // @require https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js
  40. // @require https://cdn.jsdelivr.net/npm/jquery-contextmenu@2.9.2/dist/jquery.contextMenu.min.js
  41. // @require https://cdn.jsdelivr.net/npm/jquery-contextmenu@2.9.2/dist/jquery.ui.position.min.js
  42. // @resource contextMenuCss https://cdn.jsdelivr.net/npm/jquery-contextmenu@2.9.2/dist/jquery.contextMenu.min.css
  43. // @run-at document-start
  44. // @connect 127.0.0.1
  45. // @license GPL
  46. // ==/UserScript==
  47. (function (w) { if (w) { w._vueDebugHelper_ = 'https://github.com/xxxily/vue-debug-helper'; } })();
  48.  
  49. class AssertionError extends Error {}
  50. AssertionError.prototype.name = 'AssertionError';
  51.  
  52. /**
  53. * Minimal assert function
  54. * @param {any} t Value to check if falsy
  55. * @param {string=} m Optional assertion error message
  56. * @throws {AssertionError}
  57. */
  58. function assert (t, m) {
  59. if (!t) {
  60. var err = new AssertionError(m);
  61. if (Error.captureStackTrace) Error.captureStackTrace(err, assert);
  62. throw err
  63. }
  64. }
  65.  
  66. /* eslint-env browser */
  67.  
  68. let ls;
  69. if (typeof window === 'undefined' || typeof window.localStorage === 'undefined') {
  70. // A simple localStorage interface so that lsp works in SSR contexts. Not for persistant storage in node.
  71. const _nodeStorage = {};
  72. ls = {
  73. getItem (name) {
  74. return _nodeStorage[name] || null
  75. },
  76. setItem (name, value) {
  77. if (arguments.length < 2) throw new Error('Failed to execute \'setItem\' on \'Storage\': 2 arguments required, but only 1 present.')
  78. _nodeStorage[name] = (value).toString();
  79. },
  80. removeItem (name) {
  81. delete _nodeStorage[name];
  82. }
  83. };
  84. } else {
  85. ls = window.localStorage;
  86. }
  87.  
  88. var localStorageProxy = (name, opts = {}) => {
  89. assert(name, 'namepace required');
  90. const {
  91. defaults = {},
  92. lspReset = false,
  93. storageEventListener = true
  94. } = opts;
  95.  
  96. const state = new EventTarget();
  97. try {
  98. const restoredState = JSON.parse(ls.getItem(name)) || {};
  99. if (restoredState.lspReset !== lspReset) {
  100. ls.removeItem(name);
  101. for (const [k, v] of Object.entries({
  102. ...defaults
  103. })) {
  104. state[k] = v;
  105. }
  106. } else {
  107. for (const [k, v] of Object.entries({
  108. ...defaults,
  109. ...restoredState
  110. })) {
  111. state[k] = v;
  112. }
  113. }
  114. } catch (e) {
  115. console.error(e);
  116. ls.removeItem(name);
  117. }
  118.  
  119. state.lspReset = lspReset;
  120.  
  121. if (storageEventListener && typeof window !== 'undefined' && typeof window.addEventListener !== 'undefined') {
  122. state.addEventListener('storage', (ev) => {
  123. // Replace state with whats stored on localStorage... it is newer.
  124. for (const k of Object.keys(state)) {
  125. delete state[k];
  126. }
  127. const restoredState = JSON.parse(ls.getItem(name)) || {};
  128. for (const [k, v] of Object.entries({
  129. ...defaults,
  130. ...restoredState
  131. })) {
  132. state[k] = v;
  133. }
  134. opts.lspReset = restoredState.lspReset;
  135. state.dispatchEvent(new Event('update'));
  136. });
  137. }
  138.  
  139. function boundHandler (rootRef) {
  140. return {
  141. get (obj, prop) {
  142. if (typeof obj[prop] === 'object' && obj[prop] !== null) {
  143. return new Proxy(obj[prop], boundHandler(rootRef))
  144. } else if (typeof obj[prop] === 'function' && obj === rootRef && prop !== 'constructor') {
  145. // this returns bound EventTarget functions
  146. return obj[prop].bind(obj)
  147. } else {
  148. return obj[prop]
  149. }
  150. },
  151. set (obj, prop, value) {
  152. obj[prop] = value;
  153. try {
  154. ls.setItem(name, JSON.stringify(rootRef));
  155. rootRef.dispatchEvent(new Event('update'));
  156. return true
  157. } catch (e) {
  158. console.error(e);
  159. return false
  160. }
  161. }
  162. }
  163. }
  164.  
  165. return new Proxy(state, boundHandler(state))
  166. };
  167.  
  168. /**
  169. * 对特定数据结构的对象进行排序
  170. * @param {object} obj 一个对象,其结构应该类似于:{key1: [], key2: []}
  171. * @param {boolean} reverse -可选 是否反转、降序排列,默认为false
  172. * @param {object} opts -可选 指定数组的配置项,默认为{key: 'key', value: 'value'}
  173. * @param {object} opts.key -可选 指定对象键名的别名,默认为'key'
  174. * @param {object} opts.value -可选 指定对象值的别名,默认为'value'
  175. * @returns {array} 返回一个数组,其结构应该类似于:[{key: key1, value: []}, {key: key2, value: []}]
  176. */
  177. const objSort = (obj, reverse, opts = { key: 'key', value: 'value' }) => {
  178. const arr = [];
  179. for (const key in obj) {
  180. if (Object.prototype.hasOwnProperty.call(obj, key) && Array.isArray(obj[key])) {
  181. const tmpObj = {};
  182. tmpObj[opts.key] = key;
  183. tmpObj[opts.value] = obj[key];
  184. arr.push(tmpObj);
  185. }
  186. }
  187.  
  188. arr.sort((a, b) => {
  189. return a[opts.value].length - b[opts.value].length
  190. });
  191.  
  192. reverse && arr.reverse();
  193. return arr
  194. };
  195.  
  196. /**
  197. * 根据指定长度创建空白数据
  198. * @param {number} size -可选 指str的重复次数,默认为1024次,如果str为单个单字节字符,则意味着默认产生1Mb的空白数据
  199. * @param {string|number|any} str - 可选 指定数据的字符串,默认为'd'
  200. */
  201. function createEmptyData (count = 1024, str = 'd') {
  202. const arr = [];
  203. arr.length = count + 1;
  204. return arr.join(str)
  205. }
  206.  
  207. /**
  208. * 将字符串分隔的过滤器转换为数组形式的过滤器
  209. * @param {string|array} filter - 必选 字符串或数组,字符串支持使用 , |符号对多个项进行分隔
  210. * @returns {array}
  211. */
  212. function toArrFilters (filter) {
  213. filter = filter || [];
  214.  
  215. /* 如果是字符串,则支持通过, | 两个符号来指定多个组件名称的过滤器 */
  216. if (typeof filter === 'string') {
  217. /* 移除前后的, |分隔符,防止出现空字符的过滤规则 */
  218. filter.replace(/^(,|\|)/, '').replace(/(,|\|)$/, '');
  219.  
  220. if (/\|/.test(filter)) {
  221. filter = filter.split('|');
  222. } else {
  223. filter = filter.split(',');
  224. }
  225. }
  226.  
  227. filter = filter.map(item => item.trim());
  228.  
  229. return filter
  230. }
  231.  
  232. /**
  233. * 字符串过滤器和字符串的匹配方法
  234. * @param {string} filter -必选 过滤器的字符串
  235. * @param {string} str -必选 要跟过滤字符串进行匹配的字符串
  236. * @returns
  237. */
  238. function stringMatch (filter, str) {
  239. let isMatch = false;
  240.  
  241. if (!filter || !str) {
  242. return isMatch
  243. }
  244.  
  245. filter = String(filter);
  246. str = String(str);
  247.  
  248. /* 带星表示进行模糊匹配,且不区分大小写 */
  249. if (/\*/.test(filter)) {
  250. filter = filter.replace(/\*/g, '').toLocaleLowerCase();
  251. if (str.toLocaleLowerCase().indexOf(filter) > -1) {
  252. isMatch = true;
  253. }
  254. } else if (str.includes(filter)) {
  255. isMatch = true;
  256. }
  257.  
  258. return isMatch
  259. }
  260.  
  261. /**
  262. * 判断某个字符串是否跟filters相匹配
  263. * @param {array|string} filters - 必选 字符串或数组,字符串支持使用 , |符号对多个项进行分隔
  264. * @param {string|number} str - 必选 一个字符串或数字,用于跟过滤器进行匹配判断
  265. */
  266. function filtersMatch (filters, str) {
  267. if (!filters || !str) {
  268. return false
  269. }
  270.  
  271. filters = Array.isArray(filters) ? filters : toArrFilters(filters);
  272. str = String(str);
  273.  
  274. let result = false;
  275. for (let i = 0; i < filters.length; i++) {
  276. const filter = String(filters[i]);
  277.  
  278. if (stringMatch(filter, str)) {
  279. result = true;
  280. break
  281. }
  282. }
  283.  
  284. return result
  285. }
  286.  
  287. const inBrowser = typeof window !== 'undefined';
  288.  
  289. function getVueDevtools () {
  290. return inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__
  291. }
  292.  
  293. function copyToClipboard (text) {
  294. if (inBrowser) {
  295. const input = document.createElement('input');
  296. input.value = text;
  297. document.body.appendChild(input);
  298. input.select();
  299. document.execCommand('copy');
  300. document.body.removeChild(input);
  301. }
  302. }
  303.  
  304. window.vueDebugHelper = {
  305. /* 存储全部未被销毁的组件对象 */
  306. components: {},
  307. /* 存储全部创建过的组件的概要信息,即使销毁了概要信息依然存在 */
  308. componentsSummary: {},
  309. /* 基于componentsSummary的组件情况统计 */
  310. componentsSummaryStatistics: {},
  311. /* 已销毁的组件概要信息列表 */
  312. destroyList: [],
  313. /* 基于destroyList的组件情况统计 */
  314. destroyStatistics: {},
  315.  
  316. config: {
  317. inspect: {
  318. enabled: false
  319. },
  320.  
  321. performanceObserver: {
  322. enabled: false,
  323. // https://runebook.dev/zh-CN/docs/dom/performanceentry/entrytype
  324. entryTypes: ['element', 'navigation', 'resource', 'mark', 'measure', 'paint', 'longtask']
  325. },
  326.  
  327. /* 控制接口缓存 */
  328. ajaxCache: {
  329. enabled: false,
  330. filters: ['*'],
  331.  
  332. /* 设置缓存多久失效,默认为1天 */
  333. expires: 1000 * 60 * 60 * 24
  334. },
  335.  
  336. /* 测量选择器时间差 */
  337. measureSelectorInterval: {
  338. selector1: '',
  339. selector2: ''
  340. },
  341.  
  342. /* 是否在控制台打印组件生命周期的相关信息 */
  343. lifecycle: {
  344. show: false,
  345. filters: ['created'],
  346. componentFilters: []
  347. },
  348.  
  349. /* 查找组件的过滤器配置 */
  350. findComponentsFilters: [],
  351.  
  352. /* 阻止组件创建的过滤器 */
  353. blockFilters: [],
  354.  
  355. devtools: true,
  356.  
  357. /* 改写Vue.component */
  358. hackVueComponent: false,
  359.  
  360. /* 给组件注入空白数据的配置信息 */
  361. dd: {
  362. enabled: false,
  363. filters: [],
  364. count: 1024
  365. }
  366. }
  367. };
  368.  
  369. const helper = window.vueDebugHelper;
  370.  
  371. /* 配置信息跟localStorage联动 */
  372. const state = localStorageProxy('vueDebugHelperConfig', {
  373. defaults: helper.config,
  374. lspReset: false,
  375. storageEventListener: false
  376. });
  377. helper.config = state;
  378.  
  379. const methods = {
  380. objSort,
  381. createEmptyData,
  382. /* 清除全部helper的全部记录数据,以便重新统计 */
  383. clearAll () {
  384. helper.components = {};
  385. helper.componentsSummary = {};
  386. helper.componentsSummaryStatistics = {};
  387. helper.destroyList = [];
  388. helper.destroyStatistics = {};
  389. },
  390.  
  391. /**
  392. * 对当前的helper.components进行统计与排序
  393. * 如果一直没运行过清理函数,则表示统计页面创建至今依然存活的组件对象
  394. * 运行过清理函数,则表示统计清理后新创建且至今依然存活的组件对象
  395. */
  396. componentsStatistics (reverse = true) {
  397. const tmpObj = {};
  398.  
  399. Object.keys(helper.components).forEach(key => {
  400. const component = helper.components[key];
  401.  
  402. tmpObj[component._componentName]
  403. ? tmpObj[component._componentName].push(component)
  404. : (tmpObj[component._componentName] = [component]);
  405. });
  406.  
  407. return objSort(tmpObj, reverse, {
  408. key: 'componentName',
  409. value: 'componentInstance'
  410. })
  411. },
  412.  
  413. /**
  414. * 对componentsSummaryStatistics进行排序输出,以便可以直观查看组件的创建情况
  415. */
  416. componentsSummaryStatisticsSort (reverse = true) {
  417. return objSort(helper.componentsSummaryStatistics, reverse, {
  418. key: 'componentName',
  419. value: 'componentsSummary'
  420. })
  421. },
  422.  
  423. /**
  424. * 对destroyList进行排序输出,以便可以直观查看组件的销毁情况
  425. */
  426. destroyStatisticsSort (reverse = true) {
  427. return objSort(helper.destroyStatistics, reverse, {
  428. key: 'componentName',
  429. value: 'destroyList'
  430. })
  431. },
  432.  
  433. /**
  434. * 对destroyList进行排序输出,以便可以直观查看组件的销毁情况
  435. */
  436. getDestroyByDuration (duration = 1000) {
  437. const destroyList = helper.destroyList;
  438. const destroyListLength = destroyList.length;
  439. const destroyListDuration = destroyList.map(item => item.duration).sort();
  440. const maxDuration = Math.max(...destroyListDuration);
  441. const minDuration = Math.min(...destroyListDuration);
  442. const avgDuration = destroyListDuration.reduce((a, b) => a + b, 0) / destroyListLength;
  443. const durationRange = maxDuration - minDuration;
  444. const durationRangePercent = (duration - minDuration) / durationRange;
  445.  
  446. return {
  447. destroyList,
  448. destroyListLength,
  449. destroyListDuration,
  450. maxDuration,
  451. minDuration,
  452. avgDuration,
  453. durationRange,
  454. durationRangePercent
  455. }
  456. },
  457.  
  458. /**
  459. * 获取组件的调用链信息
  460. */
  461. getComponentChain (component, moreDetail = false) {
  462. const result = [];
  463. let current = component;
  464. let deep = 0;
  465.  
  466. while (current && deep < 50) {
  467. deep++;
  468.  
  469. /**
  470. * 由于脚本注入的运行时间会比应用创建时间晚,所以会导致部分先创建的组件缺少相关信息
  471. * 这里尝试对部分信息进行修复,以便更好的查看组件的创建情况
  472. */
  473. if (!current._componentTag) {
  474. const tag = current.$vnode?.tag || current.$options?._componentTag || current._uid;
  475. current._componentTag = tag;
  476. current._componentName = isNaN(Number(tag)) ? tag.replace(/^vue-component-\d+-/, '') : 'anonymous-component';
  477. }
  478.  
  479. if (moreDetail) {
  480. result.push({
  481. tag: current._componentTag,
  482. name: current._componentName,
  483. componentsSummary: helper.componentsSummary[current._uid] || null
  484. });
  485. } else {
  486. result.push(current._componentName);
  487. }
  488.  
  489. current = current.$parent;
  490. }
  491.  
  492. if (moreDetail) {
  493. return result
  494. } else {
  495. return result.join(' -> ')
  496. }
  497. },
  498.  
  499. printLifeCycleInfo (lifecycleFilters, componentFilters) {
  500. lifecycleFilters = toArrFilters(lifecycleFilters);
  501. componentFilters = toArrFilters(componentFilters);
  502.  
  503. helper.config.lifecycle = {
  504. show: true,
  505. filters: lifecycleFilters,
  506. componentFilters: componentFilters
  507. };
  508. },
  509. notPrintLifeCycleInfo () {
  510. helper.config.lifecycle.show = false;
  511. },
  512.  
  513. /**
  514. * 查找组件
  515. * @param {string|array} filters 组件名称或组件uid的过滤器,可以是字符串或者数组,如果是字符串多个过滤选可用,或|分隔
  516. * 如果过滤项是数字,则跟组件的id进行精确匹配,如果是字符串,则跟组件的tag信息进行模糊匹配
  517. * @returns {object} {components: [], componentNames: []}
  518. */
  519. findComponents (filters) {
  520. filters = toArrFilters(filters);
  521.  
  522. /* 对filters进行预处理,如果为纯数字则表示通过id查找组件 */
  523. filters = filters.map(filter => {
  524. if (/^\d+$/.test(filter)) {
  525. return Number(filter)
  526. } else {
  527. return filter
  528. }
  529. });
  530.  
  531. helper.config.findComponentsFilters = filters;
  532.  
  533. const result = {
  534. components: [],
  535. globalComponents: [],
  536. destroyedComponents: []
  537. };
  538.  
  539. /* 在helper.components里进行组件查找 */
  540. const components = helper.components;
  541. const keys = Object.keys(components);
  542. for (let i = 0; i < keys.length; i++) {
  543. const component = components[keys[i]];
  544.  
  545. for (let j = 0; j < filters.length; j++) {
  546. const filter = filters[j];
  547.  
  548. if (typeof filter === 'number' && component._uid === filter) {
  549. result.components.push(component);
  550. break
  551. } else if (typeof filter === 'string') {
  552. const { _componentTag, _componentName } = component;
  553.  
  554. if (stringMatch(filter, _componentTag) || stringMatch(filter, _componentName)) {
  555. result.components.push(component);
  556. break
  557. }
  558. }
  559. }
  560. }
  561.  
  562. /* 进行全局组件查找 */
  563. const globalComponentsKeys = Object.keys(helper.Vue.options.components);
  564. for (let i = 0; i < globalComponentsKeys.length; i++) {
  565. const key = String(globalComponentsKeys[i]);
  566. const component = helper.Vue.options.components[globalComponentsKeys[i]];
  567.  
  568. if (filtersMatch(filters, key)) {
  569. const tmpObj = {};
  570. tmpObj[key] = component;
  571. result.globalComponents.push(tmpObj);
  572. }
  573. }
  574.  
  575. helper.destroyList.forEach(item => {
  576. for (let j = 0; j < filters.length; j++) {
  577. const filter = filters[j];
  578.  
  579. if (typeof filter === 'number' && item.uid === filter) {
  580. result.destroyedComponents.push(item);
  581. break
  582. } else if (typeof filter === 'string') {
  583. if (stringMatch(filter, item.tag) || stringMatch(filter, item.name)) {
  584. result.destroyedComponents.push(item);
  585. break
  586. }
  587. }
  588. }
  589. });
  590.  
  591. return result
  592. },
  593.  
  594. findNotContainElementComponents () {
  595. const result = [];
  596. const keys = Object.keys(helper.components);
  597. keys.forEach(key => {
  598. const component = helper.components[key];
  599. const elStr = Object.prototype.toString.call(component.$el);
  600. if (!/(HTML|Comment)/.test(elStr)) {
  601. result.push(component);
  602. }
  603. });
  604.  
  605. return result
  606. },
  607.  
  608. /**
  609. * 阻止组件的创建
  610. * @param {string|array} filters 组件名称过滤器,可以是字符串或者数组,如果是字符串多个过滤选可用,或|分隔
  611. */
  612. blockComponents (filters) {
  613. filters = toArrFilters(filters);
  614. helper.config.blockFilters = filters;
  615. },
  616.  
  617. /**
  618. * 给指定组件注入大量空数据,以便观察组件的内存泄露情况
  619. * @param {Array|string} filter -必选 指定组件的名称,如果为空则表示注入所有组件
  620. * @param {number} count -可选 指定注入空数据的大小,单位Kb,默认为1024Kb,即1Mb
  621. * @returns
  622. */
  623. dd (filter, count = 1024) {
  624. filter = toArrFilters(filter);
  625. helper.config.dd = {
  626. enabled: true,
  627. filters: filter,
  628. count
  629. };
  630. },
  631. /* 禁止给组件注入空数据 */
  632. undd () {
  633. helper.config.dd = {
  634. enabled: false,
  635. filters: [],
  636. count: 1024
  637. };
  638.  
  639. /* 删除之前注入的数据 */
  640. Object.keys(helper.components).forEach(key => {
  641. const component = helper.components[key];
  642. component.$data && delete component.$data.__dd__;
  643. });
  644. },
  645.  
  646. toggleDevtools () {
  647. helper.config.devtools = !helper.config.devtools;
  648. }
  649. };
  650.  
  651. helper.methods = methods;
  652.  
  653. class Debug {
  654. constructor (msg, printTime = false) {
  655. const t = this;
  656. msg = msg || 'debug message:';
  657. t.log = t.createDebugMethod('log', null, msg);
  658. t.error = t.createDebugMethod('error', null, msg);
  659. t.info = t.createDebugMethod('info', null, msg);
  660. t.warn = t.createDebugMethod('warn', null, msg);
  661. }
  662.  
  663. create (msg) {
  664. return new Debug(msg)
  665. }
  666.  
  667. createDebugMethod (name, color, tipsMsg) {
  668. name = name || 'info';
  669.  
  670. const bgColorMap = {
  671. info: '#2274A5',
  672. log: '#95B46A',
  673. warn: '#F5A623',
  674. error: '#D33F49'
  675. };
  676.  
  677. const printTime = this.printTime;
  678.  
  679. return function () {
  680. if (!window._debugMode_) {
  681. return false
  682. }
  683.  
  684. const msg = tipsMsg || 'debug message:';
  685.  
  686. const arg = Array.from(arguments);
  687. arg.unshift(`color: white; background-color: ${color || bgColorMap[name] || '#95B46A'}`);
  688.  
  689. if (printTime) {
  690. const curTime = new Date();
  691. const H = curTime.getHours();
  692. const M = curTime.getMinutes();
  693. const S = curTime.getSeconds();
  694. arg.unshift(`%c [${H}:${M}:${S}] ${msg} `);
  695. } else {
  696. arg.unshift(`%c ${msg} `);
  697. }
  698.  
  699. window.console[name].apply(window.console, arg);
  700. }
  701. }
  702.  
  703. isDebugMode () {
  704. return Boolean(window._debugMode_)
  705. }
  706. }
  707.  
  708. var Debug$1 = new Debug();
  709.  
  710. var debug = Debug$1.create('vueDebugHelper:');
  711.  
  712. /**
  713. * 打印生命周期信息
  714. * @param {Vue} vm vue组件实例
  715. * @param {string} lifeCycle vue生命周期名称
  716. * @returns
  717. */
  718. function printLifeCycle (vm, lifeCycle) {
  719. const lifeCycleConf = helper.config.lifecycle || { show: false, filters: ['created'], componentFilters: [] };
  720.  
  721. if (!vm || !lifeCycle || !lifeCycleConf.show) {
  722. return false
  723. }
  724.  
  725. const file = vm.options?.__file || vm.$options?.__file || '';
  726.  
  727. const { _componentTag, _componentName, _componentChain, _createdHumanTime, _uid } = vm;
  728. let info = `[${lifeCycle}] tag: ${_componentTag}, uid: ${_uid}, createdTime: ${_createdHumanTime}, chain: ${_componentChain}`;
  729.  
  730. if (file) {
  731. info += `, file: ${file}`;
  732. }
  733.  
  734. const matchComponentFilters = lifeCycleConf.componentFilters.length === 0 || filtersMatch(lifeCycleConf.componentFilters, _componentName);
  735. if (lifeCycleConf.filters.includes(lifeCycle) && matchComponentFilters) {
  736. debug.log(info);
  737. }
  738. }
  739.  
  740. function mixinRegister (Vue) {
  741. if (!Vue || !Vue.mixin) {
  742. debug.error('未检查到VUE对象,请检查是否引入了VUE,且将VUE对象挂载到全局变量window.Vue上');
  743. return false
  744. }
  745.  
  746. Vue.mixin({
  747. beforeCreate: function () {
  748. // const tag = this.$options?._componentTag || this.$vnode?.tag || this._uid
  749. const tag = this.$vnode?.tag || this.$options?._componentTag || this._uid;
  750. const chain = helper.methods.getComponentChain(this);
  751. this._componentTag = tag;
  752. this._componentChain = chain;
  753. this._componentName = isNaN(Number(tag)) ? tag.replace(/^vue-component-\d+-/, '') : 'anonymous-component';
  754. this._createdTime = Date.now();
  755.  
  756. /* 增加人类方便查看的时间信息 */
  757. const timeObj = new Date(this._createdTime);
  758. this._createdHumanTime = `${timeObj.getHours()}:${timeObj.getMinutes()}:${timeObj.getSeconds()}`;
  759.  
  760. /* 判断是否为函数式组件,函数式组件无状态 (没有响应式数据),也没有实例,也没生命周期概念 */
  761. if (this._componentName === 'anonymous-component' && !this.$parent && !this.$vnode) {
  762. this._componentName = 'functional-component';
  763. }
  764.  
  765. helper.components[this._uid] = this;
  766.  
  767. /**
  768. * 收集所有创建过的组件信息,此处只存储组件的基础信息,没销毁的组件会包含组件实例
  769. * 严禁对组件内其它对象进行引用,否则会导致组件实列无法被正常回收
  770. */
  771. const componentSummary = {
  772. uid: this._uid,
  773. name: this._componentName,
  774. tag: this._componentTag,
  775. createdTime: this._createdTime,
  776. createdHumanTime: this._createdHumanTime,
  777. // 0 表示还没被销毁
  778. destroyTime: 0,
  779. // 0 表示还没被销毁,duration可持续当当前查看时间
  780. duration: 0,
  781. component: this,
  782. chain
  783. };
  784. helper.componentsSummary[this._uid] = componentSummary;
  785.  
  786. /* 添加到componentsSummaryStatistics里,生成统计信息 */
  787. Array.isArray(helper.componentsSummaryStatistics[this._componentName])
  788. ? helper.componentsSummaryStatistics[this._componentName].push(componentSummary)
  789. : (helper.componentsSummaryStatistics[this._componentName] = [componentSummary]);
  790.  
  791. printLifeCycle(this, 'beforeCreate');
  792. },
  793. created: function () {
  794. /* 增加空白数据,方便观察内存泄露情况 */
  795. if (helper.config.dd.enabled) {
  796. let needDd = false;
  797.  
  798. if (helper.config.dd.filters.length === 0) {
  799. needDd = true;
  800. } else {
  801. for (let index = 0; index < helper.config.dd.filters.length; index++) {
  802. const filter = helper.config.dd.filters[index];
  803. if (filter === this._componentName || String(this._componentName).endsWith(filter)) {
  804. needDd = true;
  805. break
  806. }
  807. }
  808. }
  809.  
  810. if (needDd) {
  811. const count = helper.config.dd.count * 1024;
  812. const componentInfo = `tag: ${this._componentTag}, uid: ${this._uid}, createdTime: ${this._createdHumanTime}`;
  813.  
  814. /* 此处必须使用JSON.stringify对产生的字符串进行消费,否则没法将内存占用上去 */
  815. this.$data.__dd__ = JSON.stringify(componentInfo + ' ' + helper.methods.createEmptyData(count, this._uid));
  816.  
  817. console.log(`[dd success] ${componentInfo} chain: ${this._componentChain}`);
  818. }
  819. }
  820.  
  821. printLifeCycle(this, 'created');
  822. },
  823. beforeMount: function () {
  824. printLifeCycle(this, 'beforeMount');
  825. },
  826. mounted: function () {
  827. printLifeCycle(this, 'mounted');
  828. },
  829. beforeUpdate: function () {
  830. printLifeCycle(this, 'beforeUpdate');
  831. },
  832. activated: function () {
  833. printLifeCycle(this, 'activated');
  834. },
  835. deactivated: function () {
  836. printLifeCycle(this, 'deactivated');
  837. },
  838. updated: function () {
  839. printLifeCycle(this, 'updated');
  840. },
  841. beforeDestroy: function () {
  842. printLifeCycle(this, 'beforeDestroy');
  843. },
  844. destroyed: function () {
  845. printLifeCycle(this, 'destroyed');
  846.  
  847. if (this._componentTag) {
  848. const uid = this._uid;
  849. const name = this._componentName;
  850. const destroyTime = Date.now();
  851.  
  852. /* helper里的componentSummary有可能通过调用clear函数而被清除掉,所以需进行判断再更新赋值 */
  853. const componentSummary = helper.componentsSummary[this._uid];
  854. if (componentSummary) {
  855. /* 补充/更新组件信息 */
  856. componentSummary.destroyTime = destroyTime;
  857. componentSummary.duration = destroyTime - this._createdTime;
  858.  
  859. helper.destroyList.push(componentSummary);
  860.  
  861. /* 统计被销毁的组件信息 */
  862. Array.isArray(helper.destroyStatistics[name])
  863. ? helper.destroyStatistics[name].push(componentSummary)
  864. : (helper.destroyStatistics[name] = [componentSummary]);
  865.  
  866. /* 删除已销毁的组件实例 */
  867. delete componentSummary.component;
  868. }
  869.  
  870. // 解除引用关系
  871. delete this._componentTag;
  872. delete this._componentChain;
  873. delete this._componentName;
  874. delete this._createdTime;
  875. delete this._createdHumanTime;
  876. delete this.$data.__dd__;
  877. delete helper.components[uid];
  878. } else {
  879. console.error('存在未被正常标记的组件,请检查组件采集逻辑是否需完善', this);
  880. }
  881. }
  882. });
  883. }
  884.  
  885. /*!
  886. * @name menuCommand.js
  887. * @version 0.0.1
  888. * @author Blaze
  889. * @date 2019/9/21 14:22
  890. */
  891.  
  892. const monkeyMenu = {
  893. on (title, fn, accessKey) {
  894. return window.GM_registerMenuCommand && window.GM_registerMenuCommand(title, fn, accessKey)
  895. },
  896. off (id) {
  897. return window.GM_unregisterMenuCommand && window.GM_unregisterMenuCommand(id)
  898. },
  899. /* 切换类型的菜单功能 */
  900. switch (title, fn, defVal) {
  901. const t = this;
  902. t.on(title, fn);
  903. }
  904. };
  905.  
  906. /**
  907. * 简单的i18n库
  908. */
  909.  
  910. class I18n {
  911. constructor (config) {
  912. this._languages = {};
  913. this._locale = this.getClientLang();
  914. this._defaultLanguage = '';
  915. this.init(config);
  916. }
  917.  
  918. init (config) {
  919. if (!config) return false
  920.  
  921. const t = this;
  922. t._locale = config.locale || t._locale;
  923. /* 指定当前要是使用的语言环境,默认无需指定,会自动读取 */
  924. t._languages = config.languages || t._languages;
  925. t._defaultLanguage = config.defaultLanguage || t._defaultLanguage;
  926. }
  927.  
  928. use () {}
  929.  
  930. t (path) {
  931. const t = this;
  932. let result = t.getValByPath(t._languages[t._locale] || {}, path);
  933.  
  934. /* 版本回退 */
  935. if (!result && t._locale !== t._defaultLanguage) {
  936. result = t.getValByPath(t._languages[t._defaultLanguage] || {}, path);
  937. }
  938.  
  939. return result || ''
  940. }
  941.  
  942. /* 当前语言值 */
  943. language () {
  944. return this._locale
  945. }
  946.  
  947. languages () {
  948. return this._languages
  949. }
  950.  
  951. changeLanguage (locale) {
  952. if (this._languages[locale]) {
  953. this._languages = locale;
  954. return locale
  955. } else {
  956. return false
  957. }
  958. }
  959.  
  960. /**
  961. * 根据文本路径获取对象里面的值
  962. * @param obj {Object} -必选 要操作的对象
  963. * @param path {String} -必选 路径信息
  964. * @returns {*}
  965. */
  966. getValByPath (obj, path) {
  967. path = path || '';
  968. const pathArr = path.split('.');
  969. let result = obj;
  970.  
  971. /* 递归提取结果值 */
  972. for (let i = 0; i < pathArr.length; i++) {
  973. if (!result) break
  974. result = result[pathArr[i]];
  975. }
  976.  
  977. return result
  978. }
  979.  
  980. /* 获取客户端当前的语言环境 */
  981. getClientLang () {
  982. return navigator.languages ? navigator.languages[0] : navigator.language
  983. }
  984. }
  985.  
  986. var zhCN = {
  987. about: '关于',
  988. issues: '反馈',
  989. setting: '设置',
  990. hotkeys: '快捷键',
  991. donate: '赞赏',
  992. quit: '退出',
  993. refreshPage: '刷新页面',
  994. debugHelper: {
  995. viewVueDebugHelperObject: 'vueDebugHelper对象',
  996. componentsStatistics: '当前存活组件统计',
  997. destroyStatisticsSort: '已销毁组件统计',
  998. componentsSummaryStatisticsSort: '全部组件混合统计',
  999. getDestroyByDuration: '组件存活时间信息',
  1000. clearAll: '清空统计信息',
  1001. printLifeCycleInfo: '打印组件生命周期信息',
  1002. notPrintLifeCycleInfo: '取消组件生命周期信息打印',
  1003. printLifeCycleInfoPrompt: {
  1004. lifecycleFilters: '输入要打印的生命周期名称,多个可用,或|分隔,支持的值:beforeCreate|created|beforeMount|mounted|beforeUpdate|updated|activated|deactivated|beforeDestroy|destroyed',
  1005. componentFilters: '输入要打印的组件名称,多个可用,或|分隔,不输入则打印所有组件,字符串后面加*可执行模糊匹配'
  1006. },
  1007. findComponents: '查找组件',
  1008. findComponentsPrompt: {
  1009. filters: '输入要查找的组件名称,或uid,多个可用,或|分隔,字符串后面加*可执行模糊匹配'
  1010. },
  1011. findNotContainElementComponents: '查找不包含DOM对象的组件',
  1012. blockComponents: '阻断组件的创建',
  1013. blockComponentsPrompt: {
  1014. filters: '输入要阻断的组件名称,多个可用,或|分隔,输入为空则取消阻断,字符串后面加*可执行模糊匹配'
  1015. },
  1016. dd: '数据注入(dd)',
  1017. undd: '取消数据注入(undd)',
  1018. ddPrompt: {
  1019. filter: '组件过滤器(如果为空,则对所有组件注入)',
  1020. count: '指定注入数据的重复次数(默认1024)'
  1021. },
  1022. toggleHackVueComponent: '改写/还原Vue.component',
  1023. hackVueComponent: {
  1024. hack: '改写Vue.component',
  1025. unhack: '还原Vue.component'
  1026. },
  1027. toggleInspect: '切换Inspect',
  1028. inspectStatus: {
  1029. on: '开启Inspect',
  1030. off: '关闭Inspect'
  1031. },
  1032. togglePerformanceObserver: '开启/关闭性能观察',
  1033. performanceObserverStatus: {
  1034. on: '开启性能观察',
  1035. off: '关闭性能观察'
  1036. },
  1037. performanceObserverPrompt: {
  1038. entryTypes: '输入要观察的类型,多个类型可用,或|分隔,支持的类型有:element,navigation,resource,mark,measure,paint,longtask',
  1039. notSupport: '当前浏览器不支持性能观察'
  1040. },
  1041. enableAjaxCacheTips: '接口缓存功能已开启',
  1042. disableAjaxCacheTips: '接口缓存功能已关闭',
  1043. toggleAjaxCache: '开启/关闭接口缓存',
  1044. ajaxCacheStatus: {
  1045. on: '开启接口缓存',
  1046. off: '关闭接口缓存'
  1047. },
  1048. clearAjaxCache: '清空接口缓存数据',
  1049. clearAjaxCacheTips: '接口缓存数据已清空',
  1050. jaxCachePrompt: {
  1051. filters: '输入要缓存的接口地址,多个可用,或|分隔,字符串后面加*可执行模糊匹配',
  1052. expires: '输入缓存过期时间,单位为分钟,默认为1440分钟(即24小时)'
  1053. },
  1054. measureSelectorInterval: '测量选择器时间差',
  1055. measureSelectorIntervalPrompt: {
  1056. selector1: '输入起始选择器',
  1057. selector2: '输入结束选择器'
  1058. },
  1059. selectorReadyTips: '元素已就绪',
  1060. devtools: {
  1061. enabled: '自动开启vue-devtools',
  1062. disable: '禁止开启vue-devtools'
  1063. }
  1064. }
  1065. };
  1066.  
  1067. var enUS = {
  1068. about: 'about',
  1069. issues: 'feedback',
  1070. setting: 'settings',
  1071. hotkeys: 'Shortcut keys',
  1072. donate: 'donate',
  1073. debugHelper: {
  1074. viewVueDebugHelperObject: 'vueDebugHelper object',
  1075. componentsStatistics: 'Current surviving component statistics',
  1076. destroyStatisticsSort: 'Destroyed component statistics',
  1077. componentsSummaryStatisticsSort: 'All components mixed statistics',
  1078. getDestroyByDuration: 'Component survival time information',
  1079. clearAll: 'Clear statistics',
  1080. dd: 'Data injection (dd)',
  1081. undd: 'Cancel data injection (undd)',
  1082. ddPrompt: {
  1083. filter: 'Component filter (if empty, inject all components)',
  1084. count: 'Specify the number of repetitions of injected data (default 1024)'
  1085. }
  1086. }
  1087. };
  1088.  
  1089. var zhTW = {
  1090. about: '關於',
  1091. issues: '反饋',
  1092. setting: '設置',
  1093. hotkeys: '快捷鍵',
  1094. donate: '讚賞',
  1095. debugHelper: {
  1096. viewVueDebugHelperObject: 'vueDebugHelper對象',
  1097. componentsStatistics: '當前存活組件統計',
  1098. destroyStatisticsSort: '已銷毀組件統計',
  1099. componentsSummaryStatisticsSort: '全部組件混合統計',
  1100. getDestroyByDuration: '組件存活時間信息',
  1101. clearAll: '清空統計信息',
  1102. dd: '數據注入(dd)',
  1103. undd: '取消數據注入(undd)',
  1104. ddPrompt: {
  1105. filter: '組件過濾器(如果為空,則對所有組件注入)',
  1106. count: '指定注入數據的重複次數(默認1024)'
  1107. }
  1108. }
  1109. };
  1110.  
  1111. const messages = {
  1112. 'zh-CN': zhCN,
  1113. zh: zhCN,
  1114. 'zh-HK': zhTW,
  1115. 'zh-TW': zhTW,
  1116. 'en-US': enUS,
  1117. en: enUS,
  1118. };
  1119.  
  1120. /*!
  1121. * @name i18n.js
  1122. * @description vue-debug-helper的国际化配置
  1123. * @version 0.0.1
  1124. * @author xxxily
  1125. * @date 2022/04/26 14:56
  1126. * @github https://github.com/xxxily
  1127. */
  1128.  
  1129. const i18n = new I18n({
  1130. defaultLanguage: 'en',
  1131. /* 指定当前要是使用的语言环境,默认无需指定,会自动读取 */
  1132. // locale: 'zh-TW',
  1133. languages: messages
  1134. });
  1135.  
  1136. /*!
  1137. * @name index.js
  1138. * @description hookJs JS AOP切面编程辅助库
  1139. * @version 0.0.1
  1140. * @author Blaze
  1141. * @date 2020/10/22 17:40
  1142. * @github https://github.com/xxxily
  1143. */
  1144.  
  1145. const win = typeof window === 'undefined' ? global : window;
  1146. const toStr = Function.prototype.call.bind(Object.prototype.toString);
  1147. /* 特殊场景,如果把Boolean也hook了,很容易导致调用溢出,所以是需要使用原生Boolean */
  1148. const toBoolean = Boolean.originMethod ? Boolean.originMethod : Boolean;
  1149. const util = {
  1150. toStr,
  1151. isObj: obj => toStr(obj) === '[object Object]',
  1152. /* 判断是否为引用类型,用于更宽泛的场景 */
  1153. isRef: obj => typeof obj === 'object',
  1154. isReg: obj => toStr(obj) === '[object RegExp]',
  1155. isFn: obj => obj instanceof Function,
  1156. isAsyncFn: fn => toStr(fn) === '[object AsyncFunction]',
  1157. isPromise: obj => toStr(obj) === '[object Promise]',
  1158. firstUpperCase: str => str.replace(/^\S/, s => s.toUpperCase()),
  1159. toArr: arg => Array.from(Array.isArray(arg) ? arg : [arg]),
  1160.  
  1161. debug: {
  1162. log () {
  1163. let log = win.console.log;
  1164. /* 如果log也被hook了,则使用未被hook前的log函数 */
  1165. if (log.originMethod) { log = log.originMethod; }
  1166. if (win._debugMode_) {
  1167. log.apply(win.console, arguments);
  1168. }
  1169. }
  1170. },
  1171. /* 获取包含自身、继承、可枚举、不可枚举的键名 */
  1172. getAllKeys (obj) {
  1173. const tmpArr = [];
  1174. for (const key in obj) { tmpArr.push(key); }
  1175. const allKeys = Array.from(new Set(tmpArr.concat(Reflect.ownKeys(obj))));
  1176. return allKeys
  1177. }
  1178. };
  1179.  
  1180. class HookJs {
  1181. constructor (useProxy) {
  1182. this.useProxy = useProxy || false;
  1183. this.hookPropertiesKeyName = '_hookProperties' + Date.now();
  1184. }
  1185.  
  1186. hookJsPro () {
  1187. return new HookJs(true)
  1188. }
  1189.  
  1190. _addHook (hookMethod, fn, type, classHook) {
  1191. const hookKeyName = type + 'Hooks';
  1192. const hookMethodProperties = hookMethod[this.hookPropertiesKeyName];
  1193. if (!hookMethodProperties[hookKeyName]) {
  1194. hookMethodProperties[hookKeyName] = [];
  1195. }
  1196.  
  1197. /* 注册(储存)要被调用的hook函数,同时防止重复注册 */
  1198. let hasSameHook = false;
  1199. for (let i = 0; i < hookMethodProperties[hookKeyName].length; i++) {
  1200. if (fn === hookMethodProperties[hookKeyName][i]) {
  1201. hasSameHook = true;
  1202. break
  1203. }
  1204. }
  1205.  
  1206. if (!hasSameHook) {
  1207. fn.classHook = classHook || false;
  1208. hookMethodProperties[hookKeyName].push(fn);
  1209. }
  1210. }
  1211.  
  1212. _runHooks (parentObj, methodName, originMethod, hookMethod, target, ctx, args, classHook, hookPropertiesKeyName) {
  1213. const hookMethodProperties = hookMethod[hookPropertiesKeyName];
  1214. const beforeHooks = hookMethodProperties.beforeHooks || [];
  1215. const afterHooks = hookMethodProperties.afterHooks || [];
  1216. const errorHooks = hookMethodProperties.errorHooks || [];
  1217. const hangUpHooks = hookMethodProperties.hangUpHooks || [];
  1218. const replaceHooks = hookMethodProperties.replaceHooks || [];
  1219. const execInfo = {
  1220. result: null,
  1221. error: null,
  1222. args: args,
  1223. type: ''
  1224. };
  1225.  
  1226. function runHooks (hooks, type) {
  1227. let hookResult = null;
  1228. execInfo.type = type || '';
  1229. if (Array.isArray(hooks)) {
  1230. hooks.forEach(fn => {
  1231. if (util.isFn(fn) && classHook === fn.classHook) {
  1232. hookResult = fn(args, parentObj, methodName, originMethod, execInfo, ctx);
  1233. }
  1234. });
  1235. }
  1236. return hookResult
  1237. }
  1238.  
  1239. const runTarget = (function () {
  1240. if (classHook) {
  1241. return function () {
  1242. // eslint-disable-next-line new-cap
  1243. return new target(...args)
  1244. }
  1245. } else {
  1246. return function () {
  1247. return target.apply(ctx, args)
  1248. }
  1249. }
  1250. })();
  1251.  
  1252. const beforeHooksResult = runHooks(beforeHooks, 'before');
  1253. /* 支持终止后续调用的指令 */
  1254. if (beforeHooksResult && beforeHooksResult === 'STOP-INVOKE') {
  1255. return beforeHooksResult
  1256. }
  1257.  
  1258. if (hangUpHooks.length || replaceHooks.length) {
  1259. /**
  1260. * 当存在hangUpHooks或replaceHooks的时候是不会触发原来函数的
  1261. * 本质上来说hangUpHooks和replaceHooks是一样的,只是外部的定义描述不一致和分类不一致而已
  1262. */
  1263. runHooks(hangUpHooks, 'hangUp');
  1264. runHooks(replaceHooks, 'replace');
  1265. } else {
  1266. if (errorHooks.length) {
  1267. try {
  1268. execInfo.result = runTarget();
  1269. } catch (err) {
  1270. execInfo.error = err;
  1271. const errorHooksResult = runHooks(errorHooks, 'error');
  1272. /* 支持执行错误后不抛出异常的指令 */
  1273. if (errorHooksResult && errorHooksResult === 'SKIP-ERROR') ; else {
  1274. throw err
  1275. }
  1276. }
  1277. } else {
  1278. execInfo.result = runTarget();
  1279. }
  1280. }
  1281.  
  1282. /**
  1283. * 执行afterHooks,如果返回的是Promise,理论上应该进行进一步的细分处理
  1284. * 但添加细分处理逻辑后发现性能下降得比较厉害,且容易出现各种异常,所以决定不在hook里处理Promise情况
  1285. * 下面是原Promise处理逻辑,添加后会导致以下网站卡死或无法访问:
  1286. * wenku.baidu.com
  1287. * https://pubs.rsc.org/en/content/articlelanding/2021/sc/d1sc01881g#!divAbstract
  1288. * https://www.elsevier.com/connect/coronavirus-information-center
  1289. */
  1290. // if (execInfo.result && execInfo.result.then && util.isPromise(execInfo.result)) {
  1291. // execInfo.result.then(function (data) {
  1292. // execInfo.result = data
  1293. // runHooks(afterHooks, 'after')
  1294. // return Promise.resolve.apply(ctx, arguments)
  1295. // }).catch(function (err) {
  1296. // execInfo.error = err
  1297. // runHooks(errorHooks, 'error')
  1298. // return Promise.reject.apply(ctx, arguments)
  1299. // })
  1300. // }
  1301.  
  1302. runHooks(afterHooks, 'after');
  1303.  
  1304. return execInfo.result
  1305. }
  1306.  
  1307. _proxyMethodcGenerator (parentObj, methodName, originMethod, classHook, context, proxyHandler) {
  1308. const t = this;
  1309. const useProxy = t.useProxy;
  1310. let hookMethod = null;
  1311.  
  1312. /* 存在缓存则使用缓存的hookMethod */
  1313. if (t.isHook(originMethod)) {
  1314. hookMethod = originMethod;
  1315. } else if (originMethod[t.hookPropertiesKeyName] && t.isHook(originMethod[t.hookPropertiesKeyName].hookMethod)) {
  1316. hookMethod = originMethod[t.hookPropertiesKeyName].hookMethod;
  1317. }
  1318.  
  1319. if (hookMethod) {
  1320. if (!hookMethod[t.hookPropertiesKeyName].isHook) {
  1321. /* 重新标注被hook状态 */
  1322. hookMethod[t.hookPropertiesKeyName].isHook = true;
  1323. util.debug.log(`[hook method] ${util.toStr(parentObj)} ${methodName}`);
  1324. }
  1325. return hookMethod
  1326. }
  1327.  
  1328. /* 使用Proxy模式进行hook可以获得更多特性,但性能也会稍差一些 */
  1329. if (useProxy && Proxy) {
  1330. /* 注意:使用Proxy代理,hookMethod和originMethod将共用同一对象 */
  1331. const handler = { ...proxyHandler };
  1332.  
  1333. /* 下面的写法确定了proxyHandler是无法覆盖construct和apply操作的 */
  1334. if (classHook) {
  1335. handler.construct = function (target, args, newTarget) {
  1336. context = context || this;
  1337. return t._runHooks(parentObj, methodName, originMethod, hookMethod, target, context, args, true, t.hookPropertiesKeyName)
  1338. };
  1339. } else {
  1340. handler.apply = function (target, ctx, args) {
  1341. ctx = context || ctx;
  1342. return t._runHooks(parentObj, methodName, originMethod, hookMethod, target, ctx, args, false, t.hookPropertiesKeyName)
  1343. };
  1344. }
  1345.  
  1346. hookMethod = new Proxy(originMethod, handler);
  1347. } else {
  1348. hookMethod = function () {
  1349. /**
  1350. * 注意此处不能通过 context = context || this
  1351. * 然后通过把context当ctx传递过去
  1352. * 这将导致ctx引用错误
  1353. */
  1354. const ctx = context || this;
  1355. return t._runHooks(parentObj, methodName, originMethod, hookMethod, originMethod, ctx, arguments, classHook, t.hookPropertiesKeyName)
  1356. };
  1357.  
  1358. /* 确保子对象和原型链跟originMethod保持一致 */
  1359. const keys = Reflect.ownKeys(originMethod);
  1360. keys.forEach(keyName => {
  1361. try {
  1362. Object.defineProperty(hookMethod, keyName, {
  1363. get: function () {
  1364. return originMethod[keyName]
  1365. },
  1366. set: function (val) {
  1367. originMethod[keyName] = val;
  1368. }
  1369. });
  1370. } catch (err) {
  1371. // 设置defineProperty的时候出现异常,可能导致hookMethod部分功能确实,也可能不受影响
  1372. util.debug.log(`[proxyMethodcGenerator] hookMethod defineProperty abnormal. hookMethod:${methodName}, definePropertyName:${keyName}`, err);
  1373. }
  1374. });
  1375. hookMethod.prototype = originMethod.prototype;
  1376. }
  1377.  
  1378. const hookMethodProperties = hookMethod[t.hookPropertiesKeyName] = {};
  1379.  
  1380. hookMethodProperties.originMethod = originMethod;
  1381. hookMethodProperties.hookMethod = hookMethod;
  1382. hookMethodProperties.isHook = true;
  1383. hookMethodProperties.classHook = classHook;
  1384.  
  1385. util.debug.log(`[hook method] ${util.toStr(parentObj)} ${methodName}`);
  1386.  
  1387. return hookMethod
  1388. }
  1389.  
  1390. _getObjKeysByRule (obj, rule) {
  1391. let excludeRule = null;
  1392. let result = rule;
  1393.  
  1394. if (util.isObj(rule) && rule.include) {
  1395. excludeRule = rule.exclude;
  1396. rule = rule.include;
  1397. result = rule;
  1398. }
  1399.  
  1400. /**
  1401. * for in、Object.keys与Reflect.ownKeys的区别见:
  1402. * https://es6.ruanyifeng.com/#docs/object#%E5%B1%9E%E6%80%A7%E7%9A%84%E9%81%8D%E5%8E%86
  1403. */
  1404. if (rule === '*') {
  1405. result = Object.keys(obj);
  1406. } else if (rule === '**') {
  1407. result = Reflect.ownKeys(obj);
  1408. } else if (rule === '***') {
  1409. result = util.getAllKeys(obj);
  1410. } else if (util.isReg(rule)) {
  1411. result = util.getAllKeys(obj).filter(keyName => rule.test(keyName));
  1412. }
  1413.  
  1414. /* 如果存在排除规则,则需要进行排除 */
  1415. if (excludeRule) {
  1416. result = Array.isArray(result) ? result : [result];
  1417. if (util.isReg(excludeRule)) {
  1418. result = result.filter(keyName => !excludeRule.test(keyName));
  1419. } else if (Array.isArray(excludeRule)) {
  1420. result = result.filter(keyName => !excludeRule.includes(keyName));
  1421. } else {
  1422. result = result.filter(keyName => excludeRule !== keyName);
  1423. }
  1424. }
  1425.  
  1426. return util.toArr(result)
  1427. }
  1428.  
  1429. /**
  1430. * 判断某个函数是否已经被hook
  1431. * @param fn {Function} -必选 要判断的函数
  1432. * @returns {boolean}
  1433. */
  1434. isHook (fn) {
  1435. if (!fn || !fn[this.hookPropertiesKeyName]) {
  1436. return false
  1437. }
  1438. const hookMethodProperties = fn[this.hookPropertiesKeyName];
  1439. return util.isFn(hookMethodProperties.originMethod) && fn !== hookMethodProperties.originMethod
  1440. }
  1441.  
  1442. /**
  1443. * 判断对象下的某个值是否具备hook的条件
  1444. * 注意:具备hook条件和能否直接修改值是两回事,
  1445. * 在进行hook的时候还要检查descriptor.writable是否为false
  1446. * 如果为false则要修改成true才能hook成功
  1447. * @param parentObj
  1448. * @param keyName
  1449. * @returns {boolean}
  1450. */
  1451. isAllowHook (parentObj, keyName) {
  1452. /* 有些对象会设置getter,让读取值的时候就抛错,所以需要try catch 判断能否正常读取属性 */
  1453. try { if (!parentObj[keyName]) return false } catch (e) { return false }
  1454. const descriptor = Object.getOwnPropertyDescriptor(parentObj, keyName);
  1455. return !(descriptor && descriptor.configurable === false)
  1456. }
  1457.  
  1458. /**
  1459. * hook 核心函数
  1460. * @param parentObj {Object} -必选 被hook函数依赖的父对象
  1461. * @param hookMethods {Object|Array|RegExp|string} -必选 被hook函数的函数名或函数名的匹配规则
  1462. * @param fn {Function} -必选 hook之后的回调方法
  1463. * @param type {String} -可选 默认before,指定运行hook函数回调的时机,可选字符串:before、after、replace、error、hangUp
  1464. * @param classHook {Boolean} -可选 默认false,指定是否为针对new(class)操作的hook
  1465. * @param context {Object} -可选 指定运行被hook函数时的上下文对象
  1466. * @param proxyHandler {Object} -可选 仅当用Proxy进行hook时有效,默认使用的是Proxy的apply handler进行hook,如果你有特殊需求也可以配置自己的handler以实现更复杂的功能
  1467. * 附注:不使用Proxy进行hook,可以获得更高性能,但也意味着通用性更差些,对于要hook HTMLElement.prototype、EventTarget.prototype这些对象里面的非实例的函数往往会失败而导致被hook函数执行出错
  1468. * @returns {boolean}
  1469. */
  1470. hook (parentObj, hookMethods, fn, type, classHook, context, proxyHandler) {
  1471. classHook = toBoolean(classHook);
  1472. type = type || 'before';
  1473.  
  1474. if ((!util.isRef(parentObj) && !util.isFn(parentObj)) || !util.isFn(fn) || !hookMethods) {
  1475. return false
  1476. }
  1477.  
  1478. const t = this;
  1479.  
  1480. hookMethods = t._getObjKeysByRule(parentObj, hookMethods);
  1481. hookMethods.forEach(methodName => {
  1482. if (!t.isAllowHook(parentObj, methodName)) {
  1483. util.debug.log(`${util.toStr(parentObj)} [${methodName}] does not support modification`);
  1484. return false
  1485. }
  1486.  
  1487. const descriptor = Object.getOwnPropertyDescriptor(parentObj, methodName);
  1488. if (descriptor && descriptor.writable === false) {
  1489. Object.defineProperty(parentObj, methodName, { writable: true });
  1490. }
  1491.  
  1492. const originMethod = parentObj[methodName];
  1493. let hookMethod = null;
  1494.  
  1495. /* 非函数无法进行hook操作 */
  1496. if (!util.isFn(originMethod)) {
  1497. return false
  1498. }
  1499.  
  1500. hookMethod = t._proxyMethodcGenerator(parentObj, methodName, originMethod, classHook, context, proxyHandler);
  1501.  
  1502. const hookMethodProperties = hookMethod[t.hookPropertiesKeyName];
  1503. if (hookMethodProperties.classHook !== classHook) {
  1504. util.debug.log(`${util.toStr(parentObj)} [${methodName}] Cannot support functions hook and classes hook at the same time `);
  1505. return false
  1506. }
  1507.  
  1508. /* 使用hookMethod接管需要被hook的方法 */
  1509. if (parentObj[methodName] !== hookMethod) {
  1510. parentObj[methodName] = hookMethod;
  1511. }
  1512.  
  1513. t._addHook(hookMethod, fn, type, classHook);
  1514. });
  1515. }
  1516.  
  1517. /* 专门针对new操作的hook,本质上是hook函数的别名,可以少传classHook这个参数,并且明确语义 */
  1518. hookClass (parentObj, hookMethods, fn, type, context, proxyHandler) {
  1519. return this.hook(parentObj, hookMethods, fn, type, true, context, proxyHandler)
  1520. }
  1521.  
  1522. /**
  1523. * 取消对某个函数的hook
  1524. * @param parentObj {Object} -必选 要取消被hook函数依赖的父对象
  1525. * @param hookMethods {Object|Array|RegExp|string} -必选 要取消被hook函数的函数名或函数名的匹配规则
  1526. * @param type {String} -可选 默认before,指定要取消的hook类型,可选字符串:before、after、replace、error、hangUp,如果不指定该选项则取消所有类型下的所有回调
  1527. * @param fn {Function} -必选 取消指定的hook回调函数,如果不指定该选项则取消对应type类型下的所有回调
  1528. * @returns {boolean}
  1529. */
  1530. unHook (parentObj, hookMethods, type, fn) {
  1531. if (!util.isRef(parentObj) || !hookMethods) {
  1532. return false
  1533. }
  1534.  
  1535. const t = this;
  1536. hookMethods = t._getObjKeysByRule(parentObj, hookMethods);
  1537. hookMethods.forEach(methodName => {
  1538. if (!t.isAllowHook(parentObj, methodName)) {
  1539. return false
  1540. }
  1541.  
  1542. const hookMethod = parentObj[methodName];
  1543.  
  1544. if (!t.isHook(hookMethod)) {
  1545. return false
  1546. }
  1547.  
  1548. const hookMethodProperties = hookMethod[t.hookPropertiesKeyName];
  1549. const originMethod = hookMethodProperties.originMethod;
  1550.  
  1551. if (type) {
  1552. const hookKeyName = type + 'Hooks';
  1553. const hooks = hookMethodProperties[hookKeyName] || [];
  1554.  
  1555. if (fn) {
  1556. /* 删除指定类型下的指定hook函数 */
  1557. for (let i = 0; i < hooks.length; i++) {
  1558. if (fn === hooks[i]) {
  1559. hookMethodProperties[hookKeyName].splice(i, 1);
  1560. util.debug.log(`[unHook ${hookKeyName} func] ${util.toStr(parentObj)} ${methodName}`, fn);
  1561. break
  1562. }
  1563. }
  1564. } else {
  1565. /* 删除指定类型下的所有hook函数 */
  1566. if (Array.isArray(hookMethodProperties[hookKeyName])) {
  1567. hookMethodProperties[hookKeyName] = [];
  1568. util.debug.log(`[unHook all ${hookKeyName}] ${util.toStr(parentObj)} ${methodName}`);
  1569. }
  1570. }
  1571. } else {
  1572. /* 彻底还原被hook的函数 */
  1573. if (util.isFn(originMethod)) {
  1574. parentObj[methodName] = originMethod;
  1575. delete parentObj[methodName][t.hookPropertiesKeyName];
  1576.  
  1577. // Object.keys(hookMethod).forEach(keyName => {
  1578. // if (/Hooks$/.test(keyName) && Array.isArray(hookMethod[keyName])) {
  1579. // hookMethod[keyName] = []
  1580. // }
  1581. // })
  1582. //
  1583. // hookMethod.isHook = false
  1584. // parentObj[methodName] = originMethod
  1585. // delete parentObj[methodName].originMethod
  1586. // delete parentObj[methodName].hookMethod
  1587. // delete parentObj[methodName].isHook
  1588. // delete parentObj[methodName].isClassHook
  1589.  
  1590. util.debug.log(`[unHook method] ${util.toStr(parentObj)} ${methodName}`);
  1591. }
  1592. }
  1593. });
  1594. }
  1595.  
  1596. /* 源函数运行前的hook */
  1597. before (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1598. return this.hook(obj, hookMethods, fn, 'before', classHook, context, proxyHandler)
  1599. }
  1600.  
  1601. /* 源函数运行后的hook */
  1602. after (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1603. return this.hook(obj, hookMethods, fn, 'after', classHook, context, proxyHandler)
  1604. }
  1605.  
  1606. /* 替换掉要hook的函数,不再运行源函数,换成运行其他逻辑 */
  1607. replace (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1608. return this.hook(obj, hookMethods, fn, 'replace', classHook, context, proxyHandler)
  1609. }
  1610.  
  1611. /* 源函数运行出错时的hook */
  1612. error (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1613. return this.hook(obj, hookMethods, fn, 'error', classHook, context, proxyHandler)
  1614. }
  1615.  
  1616. /* 底层实现逻辑与replace一样,都是替换掉要hook的函数,不再运行源函数,只不过是为了明确语义,将源函数挂起不再执行,原则上也不再执行其他逻辑,如果要执行其他逻辑请使用replace hook */
  1617. hangUp (obj, hookMethods, fn, classHook, context, proxyHandler) {
  1618. return this.hook(obj, hookMethods, fn, 'hangUp', classHook, context, proxyHandler)
  1619. }
  1620. }
  1621.  
  1622. var hookJs = new HookJs();
  1623.  
  1624. /*!
  1625. * @name vueHooks.js
  1626. * @description 对Vue对象进行的hooks封装
  1627. * @version 0.0.1
  1628. * @author xxxily
  1629. * @date 2022/05/10 14:11
  1630. * @github https://github.com/xxxily
  1631. */
  1632.  
  1633. const hookJsPro = hookJs.hookJsPro();
  1634.  
  1635. let vueComponentHook = null;
  1636.  
  1637. const vueHooks = {
  1638. /* 对extend进行hooks封装,以便进行组件阻断 */
  1639. blockComponents (Vue, config) {
  1640. hookJsPro.before(Vue, 'extend', (args, parentObj, methodName, originMethod, execInfo, ctx) => {
  1641. const extendOpts = args[0];
  1642. // extendOpts.__file && debug.info(`[extendOptions:${extendOpts.name}]`, extendOpts.__file)
  1643.  
  1644. const hasBlockFilter = config.blockFilters && config.blockFilters.length;
  1645. if (hasBlockFilter && extendOpts.name && filtersMatch(config.blockFilters, extendOpts.name)) {
  1646. debug.info(`[block component]: name: ${extendOpts.name}`);
  1647. return 'STOP-INVOKE'
  1648. }
  1649. });
  1650.  
  1651. /* 禁止因为阻断组件的创建而导致的错误提示输出,减少不必要的信息噪音 */
  1652. hookJsPro.before(Vue.util, 'warn', (args) => {
  1653. const msg = args[0];
  1654. if (msg.includes('STOP-INVOKE')) {
  1655. return 'STOP-INVOKE'
  1656. }
  1657. });
  1658. },
  1659.  
  1660. hackVueComponent (Vue, callback) {
  1661. if (vueComponentHook) {
  1662. debug.warn('[Vue.component] you have already hacked');
  1663. return
  1664. }
  1665.  
  1666. vueComponentHook = (args, parentObj, methodName, originMethod, execInfo, ctx) => {
  1667. const name = args[0];
  1668. const opts = args[1];
  1669.  
  1670. if (callback instanceof Function) {
  1671. callback.apply(Vue, args);
  1672. } else {
  1673. /* 打印全局组件的注册信息 */
  1674. if (Vue.options.components[name]) {
  1675. debug.warn(`[Vue.component][REPEAT][old-cid:${Vue.options.components[name].cid}]`, name, opts);
  1676. } else {
  1677. debug.log('[Vue.component]', name, opts);
  1678. }
  1679. }
  1680. };
  1681.  
  1682. hookJsPro.before(Vue, 'component', vueComponentHook);
  1683. debug.log(i18n.t('debugHelper.hackVueComponent.hack') + ' (success)');
  1684. },
  1685.  
  1686. unHackVueComponent (Vue) {
  1687. if (vueComponentHook) {
  1688. hookJsPro.unHook(Vue, 'component', 'before', vueComponentHook);
  1689. vueComponentHook = null;
  1690. debug.log(i18n.t('debugHelper.hackVueComponent.unhack') + ' (success)');
  1691. } else {
  1692. debug.warn('[Vue.component] you have not hack vue component, not need to unhack');
  1693. }
  1694. },
  1695.  
  1696. hackVueUpdate () {
  1697. //
  1698. }
  1699. };
  1700.  
  1701. /*
  1702. * author: wendux
  1703. * email: 824783146@qq.com
  1704. * source code: https://github.com/wendux/Ajax-hook
  1705. */
  1706.  
  1707. // Save original XMLHttpRequest as _rxhr
  1708. var realXhr = '_rxhr';
  1709.  
  1710. var events = ['load', 'loadend', 'timeout', 'error', 'readystatechange', 'abort'];
  1711.  
  1712. function configEvent (event, xhrProxy) {
  1713. var e = {};
  1714. for (var attr in event) e[attr] = event[attr];
  1715. // xhrProxy instead
  1716. e.target = e.currentTarget = xhrProxy;
  1717. return e
  1718. }
  1719.  
  1720. function hook (proxy, win) {
  1721. win = win || window;
  1722. // Avoid double hookAjax
  1723. win[realXhr] = win[realXhr] || win.XMLHttpRequest;
  1724.  
  1725. win.XMLHttpRequest = function () {
  1726. // We shouldn't hookAjax XMLHttpRequest.prototype because we can't
  1727. // guarantee that all attributes are on the prototype。
  1728. // Instead, hooking XMLHttpRequest instance can avoid this problem.
  1729.  
  1730. var xhr = new win[realXhr]();
  1731.  
  1732. // Generate all callbacks(eg. onload) are enumerable (not undefined).
  1733. for (var i = 0; i < events.length; ++i) {
  1734. if (xhr[events[i]] === undefined) xhr[events[i]] = null;
  1735. }
  1736.  
  1737. for (var attr in xhr) {
  1738. var type = '';
  1739. try {
  1740. type = typeof xhr[attr]; // May cause exception on some browser
  1741. } catch (e) {
  1742. }
  1743. if (type === 'function') {
  1744. // hookAjax methods of xhr, such as `open`、`send` ...
  1745. this[attr] = hookFunction(attr);
  1746. } else {
  1747. Object.defineProperty(this, attr, {
  1748. get: getterFactory(attr),
  1749. set: setterFactory(attr),
  1750. enumerable: true
  1751. });
  1752. }
  1753. }
  1754. var that = this;
  1755. xhr.getProxy = function () {
  1756. return that
  1757. };
  1758. this.xhr = xhr;
  1759. };
  1760.  
  1761. Object.assign(win.XMLHttpRequest, { UNSENT: 0, OPENED: 1, HEADERS_RECEIVED: 2, LOADING: 3, DONE: 4 });
  1762.  
  1763. // Generate getter for attributes of xhr
  1764. function getterFactory (attr) {
  1765. return function () {
  1766. var v = this.hasOwnProperty(attr + '_') ? this[attr + '_'] : this.xhr[attr];
  1767. var attrGetterHook = (proxy[attr] || {}).getter;
  1768. return attrGetterHook && attrGetterHook(v, this) || v
  1769. }
  1770. }
  1771.  
  1772. // Generate setter for attributes of xhr; by this we have an opportunity
  1773. // to hookAjax event callbacks (eg: `onload`) of xhr;
  1774. function setterFactory (attr) {
  1775. return function (v) {
  1776. var xhr = this.xhr;
  1777. var that = this;
  1778. var hook = proxy[attr];
  1779. // hookAjax event callbacks such as `onload`、`onreadystatechange`...
  1780. if (attr.substring(0, 2) === 'on') {
  1781. that[attr + '_'] = v;
  1782. xhr[attr] = function (e) {
  1783. e = configEvent(e, that);
  1784. var ret = proxy[attr] && proxy[attr].call(that, xhr, e);
  1785. ret || v.call(that, e);
  1786. };
  1787. } else {
  1788. // If the attribute isn't writable, generate proxy attribute
  1789. var attrSetterHook = (hook || {}).setter;
  1790. v = attrSetterHook && attrSetterHook(v, that) || v;
  1791. this[attr + '_'] = v;
  1792. try {
  1793. // Not all attributes of xhr are writable(setter may undefined).
  1794. xhr[attr] = v;
  1795. } catch (e) {
  1796. }
  1797. }
  1798. }
  1799. }
  1800.  
  1801. // Hook methods of xhr.
  1802. function hookFunction (fun) {
  1803. return function () {
  1804. var args = [].slice.call(arguments);
  1805. if (proxy[fun]) {
  1806. var ret = proxy[fun].call(this, args, this.xhr);
  1807. // If the proxy return value exists, return it directly,
  1808. // otherwise call the function of xhr.
  1809. if (ret) return ret
  1810. }
  1811. return this.xhr[fun].apply(this.xhr, args)
  1812. }
  1813. }
  1814.  
  1815. // Return the real XMLHttpRequest
  1816. return win[realXhr]
  1817. }
  1818.  
  1819. function unHook (win) {
  1820. win = win || window;
  1821. if (win[realXhr]) win.XMLHttpRequest = win[realXhr];
  1822. win[realXhr] = undefined;
  1823. }
  1824.  
  1825. /*
  1826. * author: wendux
  1827. * email: 824783146@qq.com
  1828. * source code: https://github.com/wendux/Ajax-hook
  1829. */
  1830.  
  1831. var eventLoad = events[0];
  1832. var eventLoadEnd = events[1];
  1833. var eventTimeout = events[2];
  1834. var eventError = events[3];
  1835. var eventReadyStateChange = events[4];
  1836. var eventAbort = events[5];
  1837.  
  1838. var singleton;
  1839. var prototype = 'prototype';
  1840.  
  1841. function proxy (proxy, win) {
  1842. if (singleton) {
  1843. throw new Error('Proxy already exists')
  1844. }
  1845.  
  1846. singleton = new Proxy$1(proxy, win);
  1847. return singleton
  1848. }
  1849.  
  1850. function unProxy (win) {
  1851. singleton = null;
  1852. unHook(win);
  1853. }
  1854.  
  1855. function trim (str) {
  1856. return str.replace(/^\s+|\s+$/g, '')
  1857. }
  1858.  
  1859. function getEventTarget (xhr) {
  1860. return xhr.watcher || (xhr.watcher = document.createElement('a'))
  1861. }
  1862.  
  1863. function triggerListener (xhr, name) {
  1864. var xhrProxy = xhr.getProxy();
  1865. var callback = 'on' + name + '_';
  1866. var event = configEvent({ type: name }, xhrProxy);
  1867. xhrProxy[callback] && xhrProxy[callback](event);
  1868. var evt;
  1869. if (typeof (Event) === 'function') {
  1870. evt = new Event(name, { bubbles: false });
  1871. } else {
  1872. // https://stackoverflow.com/questions/27176983/dispatchevent-not-working-in-ie11
  1873. evt = document.createEvent('Event');
  1874. evt.initEvent(name, false, true);
  1875. }
  1876. getEventTarget(xhr).dispatchEvent(evt);
  1877. }
  1878.  
  1879. function Handler (xhr) {
  1880. this.xhr = xhr;
  1881. this.xhrProxy = xhr.getProxy();
  1882. }
  1883.  
  1884. Handler[prototype] = Object.create({
  1885. resolve: function resolve (response) {
  1886. var xhrProxy = this.xhrProxy;
  1887. var xhr = this.xhr;
  1888. xhrProxy.readyState = 4;
  1889. xhr.resHeader = response.headers;
  1890. xhrProxy.response = xhrProxy.responseText = response.response;
  1891. xhrProxy.statusText = response.statusText;
  1892. xhrProxy.status = response.status;
  1893. triggerListener(xhr, eventReadyStateChange);
  1894. triggerListener(xhr, eventLoad);
  1895. triggerListener(xhr, eventLoadEnd);
  1896. },
  1897. reject: function reject (error) {
  1898. this.xhrProxy.status = 0;
  1899. triggerListener(this.xhr, error.type);
  1900. triggerListener(this.xhr, eventLoadEnd);
  1901. }
  1902. });
  1903.  
  1904. function makeHandler (next) {
  1905. function sub (xhr) {
  1906. Handler.call(this, xhr);
  1907. }
  1908.  
  1909. sub[prototype] = Object.create(Handler[prototype]);
  1910. sub[prototype].next = next;
  1911. return sub
  1912. }
  1913.  
  1914. var RequestHandler = makeHandler(function (rq) {
  1915. var xhr = this.xhr;
  1916. rq = rq || xhr.config;
  1917. xhr.withCredentials = rq.withCredentials;
  1918. xhr.open(rq.method, rq.url, rq.async !== false, rq.user, rq.password);
  1919. for (var key in rq.headers) {
  1920. xhr.setRequestHeader(key, rq.headers[key]);
  1921. }
  1922. xhr.send(rq.body);
  1923. });
  1924.  
  1925. var ResponseHandler = makeHandler(function (response) {
  1926. this.resolve(response);
  1927. });
  1928.  
  1929. var ErrorHandler = makeHandler(function (error) {
  1930. this.reject(error);
  1931. });
  1932.  
  1933. function Proxy$1 (proxy, win) {
  1934. var onRequest = proxy.onRequest;
  1935. var onResponse = proxy.onResponse;
  1936. var onError = proxy.onError;
  1937.  
  1938. function handleResponse (xhr, xhrProxy) {
  1939. var handler = new ResponseHandler(xhr);
  1940. var ret = {
  1941. response: xhrProxy.response,
  1942. status: xhrProxy.status,
  1943. statusText: xhrProxy.statusText,
  1944. config: xhr.config,
  1945. headers: xhr.resHeader || xhr.getAllResponseHeaders().split('\r\n').reduce(function (ob, str) {
  1946. if (str === '') return ob
  1947. var m = str.split(':');
  1948. ob[m.shift()] = trim(m.join(':'));
  1949. return ob
  1950. }, {})
  1951. };
  1952. if (!onResponse) return handler.resolve(ret)
  1953. onResponse(ret, handler);
  1954. }
  1955.  
  1956. function onerror (xhr, xhrProxy, error, errorType) {
  1957. var handler = new ErrorHandler(xhr);
  1958. error = { config: xhr.config, error: error, type: errorType };
  1959. if (onError) {
  1960. onError(error, handler);
  1961. } else {
  1962. handler.next(error);
  1963. }
  1964. }
  1965.  
  1966. function preventXhrProxyCallback () {
  1967. return true
  1968. }
  1969.  
  1970. function errorCallback (errorType) {
  1971. return function (xhr, e) {
  1972. onerror(xhr, this, e, errorType);
  1973. return true
  1974. }
  1975. }
  1976.  
  1977. function stateChangeCallback (xhr, xhrProxy) {
  1978. if (xhr.readyState === 4 && xhr.status !== 0) {
  1979. handleResponse(xhr, xhrProxy);
  1980. } else if (xhr.readyState !== 4) {
  1981. triggerListener(xhr, eventReadyStateChange);
  1982. }
  1983. return true
  1984. }
  1985.  
  1986. return hook({
  1987. onload: preventXhrProxyCallback,
  1988. onloadend: preventXhrProxyCallback,
  1989. onerror: errorCallback(eventError),
  1990. ontimeout: errorCallback(eventTimeout),
  1991. onabort: errorCallback(eventAbort),
  1992. onreadystatechange: function (xhr) {
  1993. return stateChangeCallback(xhr, this)
  1994. },
  1995. open: function open (args, xhr) {
  1996. var _this = this;
  1997. var config = xhr.config = { headers: {} };
  1998. config.method = args[0];
  1999. config.url = args[1];
  2000. config.async = args[2];
  2001. config.user = args[3];
  2002. config.password = args[4];
  2003. config.xhr = xhr;
  2004. var evName = 'on' + eventReadyStateChange;
  2005. if (!xhr[evName]) {
  2006. xhr[evName] = function () {
  2007. return stateChangeCallback(xhr, _this)
  2008. };
  2009. }
  2010.  
  2011. // 如果有请求拦截器,则在调用onRequest后再打开链接。因为onRequest最佳调用时机是在send前,
  2012. // 所以我们在send拦截函数中再手动调用open,因此返回true阻止xhr.open调用。
  2013. //
  2014. // 如果没有请求拦截器,则不用阻断xhr.open调用
  2015. if (onRequest) return true
  2016. },
  2017. send: function (args, xhr) {
  2018. var config = xhr.config;
  2019. config.withCredentials = xhr.withCredentials;
  2020. config.body = args[0];
  2021. if (onRequest) {
  2022. // In 'onRequest', we may call XHR's event handler, such as `xhr.onload`.
  2023. // However, XHR's event handler may not be set until xhr.send is called in
  2024. // the user's code, so we use `setTimeout` to avoid this situation
  2025. var req = function () {
  2026. onRequest(config, new RequestHandler(xhr));
  2027. };
  2028. config.async === false ? req() : setTimeout(req);
  2029. return true
  2030. }
  2031. },
  2032. setRequestHeader: function (args, xhr) {
  2033. // Collect request headers
  2034. xhr.config.headers[args[0].toLowerCase()] = args[1];
  2035. return true
  2036. },
  2037. addEventListener: function (args, xhr) {
  2038. var _this = this;
  2039. if (events.indexOf(args[0]) !== -1) {
  2040. var handler = args[1];
  2041. getEventTarget(xhr).addEventListener(args[0], function (e) {
  2042. var event = configEvent(e, _this);
  2043. event.type = args[0];
  2044. event.isTrusted = true;
  2045. handler.call(_this, event);
  2046. });
  2047. return true
  2048. }
  2049. },
  2050. getAllResponseHeaders: function (_, xhr) {
  2051. var headers = xhr.resHeader;
  2052. if (headers) {
  2053. var header = '';
  2054. for (var key in headers) {
  2055. header += key + ': ' + headers[key] + '\r\n';
  2056. }
  2057. return header
  2058. }
  2059. },
  2060. getResponseHeader: function (args, xhr) {
  2061. var headers = xhr.resHeader;
  2062. if (headers) {
  2063. return headers[(args[0] || '').toLowerCase()]
  2064. }
  2065. }
  2066. }, win)
  2067. }
  2068.  
  2069. /*!
  2070. * @name cacheStore.js
  2071. * @description 接口请求缓存存储管理模块
  2072. * @version 0.0.1
  2073. * @author xxxily
  2074. * @date 2022/05/13 09:36
  2075. * @github https://github.com/xxxily
  2076. */
  2077. const localforage = window.localforage;
  2078. const CryptoJS = window.CryptoJS;
  2079.  
  2080. function md5 (str) {
  2081. return CryptoJS.MD5(str).toString()
  2082. }
  2083.  
  2084. function createHash (config) {
  2085. if (config._hash_) {
  2086. return config._hash_
  2087. }
  2088.  
  2089. let url = config.url || '';
  2090.  
  2091. /**
  2092. * 如果检测到url使用了时间戳来防止缓存,则进行替换,进行缓存
  2093. * TODO
  2094. * 注意,这很可能会导致误伤,例如url上的时间戳并不是用来清理缓存的,而是某个时间点的参数
  2095. */
  2096. if (/=\d{13}/.test(url)) {
  2097. url = url.replace(/=\d{13}/, '=cache');
  2098. }
  2099.  
  2100. let hashStr = url;
  2101.  
  2102. if (config.method.toUpperCase() === 'POST') {
  2103. hashStr += JSON.stringify(config.data) + JSON.stringify(config.body);
  2104. }
  2105.  
  2106. const hash = md5(hashStr);
  2107. config._hash_ = hash;
  2108.  
  2109. return hash
  2110. }
  2111.  
  2112. class CacheStore {
  2113. constructor (opts = {
  2114. localforageConfig: {}
  2115. }) {
  2116. this.store = localforage.createInstance(Object.assign({
  2117. name: 'vue-debug-helper-cache',
  2118. storeName: 'ajax-cache'
  2119. }, opts.localforageConfig));
  2120.  
  2121. /* 外部应该使用同样的hash生成方法,否则无法正常命中缓存规则 */
  2122. this.createHash = createHash;
  2123. }
  2124.  
  2125. async getCache (config) {
  2126. const hash = createHash(config);
  2127. const data = await this.store.getItem(hash);
  2128. return data
  2129. }
  2130.  
  2131. async setCache (response, filter) {
  2132. const headers = response.headers || {};
  2133. if (String(headers['content-type']).includes(filter || 'application/json')) {
  2134. const hash = createHash(response.config);
  2135. await this.store.setItem(hash, response.response);
  2136.  
  2137. /* 设置缓存的时候顺便更新缓存相关的基础信息,注意,该信息并不能100%被同步到本地 */
  2138. await this.updateCacheInfo(response.config);
  2139.  
  2140. debug.log(`[cacheStore setCache] ${response.config.url}`, response);
  2141. }
  2142. }
  2143.  
  2144. async getCacheInfo (config) {
  2145. const hash = config ? this.createHash(config) : '';
  2146. if (this._cacheInfo_) {
  2147. return hash ? this._cacheInfo_[hash] : this._cacheInfo_
  2148. }
  2149.  
  2150. /* 在没将cacheInfo加载到内存前,只能单线程获取cacheInfo,防止多线程获取cacheInfo时出现问题 */
  2151. if (this._takeingCacheInfo_) {
  2152. const getCacheInfoHanderList = this._getCacheInfoHanderList_ || [];
  2153. const P = new Promise((resolve, reject) => {
  2154. getCacheInfoHanderList.push({
  2155. resolve,
  2156. config
  2157. });
  2158. });
  2159. this._getCacheInfoHanderList_ = getCacheInfoHanderList;
  2160. return P
  2161. }
  2162.  
  2163. this._takeingCacheInfo_ = true;
  2164. const cacheInfo = await this.store.getItem('ajaxCacheInfo') || {};
  2165. this._cacheInfo_ = cacheInfo;
  2166.  
  2167. delete this._takeingCacheInfo_;
  2168. if (this._getCacheInfoHanderList_) {
  2169. this._getCacheInfoHanderList_.forEach(async (handler) => {
  2170. handler.resolve(await this.getCacheInfo(handler.config));
  2171. });
  2172. delete this._getCacheInfoHanderList_;
  2173. }
  2174.  
  2175. return hash ? cacheInfo[hash] : cacheInfo
  2176. }
  2177.  
  2178. async updateCacheInfo (config) {
  2179. const cacheInfo = await this.getCacheInfo();
  2180.  
  2181. if (config) {
  2182. const hash = createHash(config);
  2183. if (hash && config) {
  2184. const info = {
  2185. url: config.url,
  2186. cacheTime: Date.now()
  2187. };
  2188.  
  2189. // 增加或更新缓存的基本信息
  2190. cacheInfo[hash] = info;
  2191. }
  2192. }
  2193.  
  2194. if (!this._updateCacheInfoIsWorking_) {
  2195. this._updateCacheInfoIsWorking_ = true;
  2196. await this.store.setItem('ajaxCacheInfo', cacheInfo);
  2197. this._updateCacheInfoIsWorking_ = false;
  2198. }
  2199. }
  2200.  
  2201. /**
  2202. * 清理已过期的缓存数据
  2203. * @param {number} expires 指定过期时间,单位:毫秒
  2204. * @returns
  2205. */
  2206. async cleanCache (expires) {
  2207. if (!expires) {
  2208. return
  2209. }
  2210.  
  2211. const cacheInfo = await this.getCacheInfo();
  2212. const cacheInfoKeys = Object.keys(cacheInfo);
  2213. const now = Date.now();
  2214.  
  2215. const storeKeys = await this.store.keys();
  2216.  
  2217. const needKeepKeys = cacheInfoKeys.filter(key => now - cacheInfo[key].cacheTime < expires);
  2218. needKeepKeys.push('ajaxCacheInfo');
  2219.  
  2220. const clearResult = [];
  2221.  
  2222. /* 清理不需要的数据 */
  2223. storeKeys.forEach((key) => {
  2224. if (!needKeepKeys.includes(key)) {
  2225. clearResult.push(this._cacheInfo_[key] || key);
  2226.  
  2227. this.store.removeItem(key);
  2228. delete this._cacheInfo_[key];
  2229. }
  2230. });
  2231.  
  2232. /* 更新缓存信息 */
  2233. if (clearResult.length) {
  2234. await this.updateCacheInfo();
  2235. debug.log('[cacheStore cleanCache] clearResult:', clearResult);
  2236. }
  2237. }
  2238.  
  2239. async get (key) {
  2240. const data = await this.store.getItem(key);
  2241. debug.log('[cacheStore]', key, data);
  2242. return data
  2243. }
  2244.  
  2245. async set (key, data) {
  2246. await this.store.setItem(key, data);
  2247. debug.log('[cacheStore]', key, data);
  2248. }
  2249.  
  2250. async remove (key) {
  2251. await this.store.removeItem(key);
  2252. debug.log('[cacheStore]', key);
  2253. }
  2254.  
  2255. async clear () {
  2256. await this.store.clear();
  2257. debug.log('[cacheStore] clear');
  2258. }
  2259.  
  2260. async keys () {
  2261. const keys = await this.store.keys();
  2262. debug.log('[cacheStore] keys', keys);
  2263. return keys
  2264. }
  2265. }
  2266.  
  2267. var cacheStore = new CacheStore();
  2268.  
  2269. /*!
  2270. * @name ajaxHooks.js
  2271. * @description 底层请求hook
  2272. * @version 0.0.1
  2273. * @author xxxily
  2274. * @date 2022/05/12 17:46
  2275. * @github https://github.com/xxxily
  2276. */
  2277.  
  2278. /**
  2279. * 判断是否符合进行缓存控制操作的条件
  2280. * @param {object} config
  2281. * @returns {boolean}
  2282. */
  2283. function useCache (config) {
  2284. const ajaxCache = helper.config.ajaxCache;
  2285. if (ajaxCache.enabled) {
  2286. return filtersMatch(ajaxCache.filters, config.url)
  2287. } else {
  2288. return false
  2289. }
  2290. }
  2291.  
  2292. let ajaxHooksWin = window;
  2293.  
  2294. const ajaxHooks = {
  2295. hook (win = ajaxHooksWin) {
  2296. proxy({
  2297. onRequest: async (config, handler) => {
  2298. let hitCache = false;
  2299.  
  2300. if (useCache(config)) {
  2301. const cacheInfo = await cacheStore.getCacheInfo(config);
  2302. const cache = await cacheStore.getCache(config);
  2303.  
  2304. if (cache && cacheInfo) {
  2305. const isExpires = Date.now() - cacheInfo.cacheTime > helper.config.ajaxCache.expires;
  2306.  
  2307. if (!isExpires) {
  2308. handler.resolve({
  2309. config: config,
  2310. status: 200,
  2311. headers: { 'content-type': 'application/json' },
  2312. response: cache
  2313. });
  2314.  
  2315. hitCache = true;
  2316. }
  2317. }
  2318. }
  2319.  
  2320. if (hitCache) {
  2321. debug.warn(`[ajaxHooks] use cache:${config.method} ${config.url}`, config);
  2322. } else {
  2323. handler.next(config);
  2324. }
  2325. },
  2326.  
  2327. onError: (err, handler) => {
  2328. handler.next(err);
  2329. },
  2330.  
  2331. onResponse: async (response, handler) => {
  2332. if (useCache(response.config)) {
  2333. // 加入缓存
  2334. cacheStore.setCache(response, 'application/json');
  2335. }
  2336.  
  2337. handler.next(response);
  2338. }
  2339. }, win);
  2340. },
  2341.  
  2342. unHook (win = ajaxHooksWin) {
  2343. unProxy(win);
  2344. },
  2345.  
  2346. init (win) {
  2347. ajaxHooksWin = win;
  2348.  
  2349. if (helper.config.ajaxCache.enabled) {
  2350. ajaxHooks.hook(ajaxHooksWin);
  2351. }
  2352.  
  2353. /* 定时清除接口的缓存数据,防止不断堆积 */
  2354. setTimeout(() => {
  2355. cacheStore.cleanCache(helper.config.ajaxCache.expires);
  2356. }, 1000 * 10);
  2357. }
  2358. };
  2359.  
  2360. /*!
  2361. * @name performanceObserver.js
  2362. * @description 进行性能监测结果的打印
  2363. * @version 0.0.1
  2364. * @author xxxily
  2365. * @date 2022/05/11 10:39
  2366. * @github https://github.com/xxxily
  2367. */
  2368.  
  2369. const performanceObserver = {
  2370. observer: null,
  2371. init () {
  2372. if (typeof PerformanceObserver === 'undefined') {
  2373. debug.log(i18n.t('debugHelper.performanceObserver.notSupport'));
  2374. return false
  2375. }
  2376.  
  2377. if (performanceObserver.observer && performanceObserver.observer.disconnect) {
  2378. performanceObserver.observer.disconnect();
  2379. }
  2380.  
  2381. /* 不进行性能观察 */
  2382. if (!helper.config.performanceObserver.enabled) {
  2383. performanceObserver.observer = null;
  2384. return false
  2385. }
  2386.  
  2387. // https://developer.mozilla.org/zh-CN/docs/Web/API/PerformanceObserver/observe
  2388. performanceObserver.observer = new PerformanceObserver(function (list, observer) {
  2389. if (!helper.config.performanceObserver.enabled) {
  2390. return
  2391. }
  2392.  
  2393. const entries = list.getEntries();
  2394. for (let i = 0; i < entries.length; i++) {
  2395. const entry = entries[i];
  2396. debug.info(`[performanceObserver ${entry.entryType}]`, entry);
  2397. }
  2398. });
  2399.  
  2400. // https://runebook.dev/zh-CN/docs/dom/performanceentry/entrytype
  2401. performanceObserver.observer.observe({ entryTypes: helper.config.performanceObserver.entryTypes });
  2402. }
  2403. };
  2404.  
  2405. /*!
  2406. * @name inspect.js
  2407. * @description vue组件审查模块
  2408. * @version 0.0.1
  2409. * @author xxxily
  2410. * @date 2022/05/10 18:25
  2411. * @github https://github.com/xxxily
  2412. */
  2413.  
  2414. const $ = window.$;
  2415. let currentComponent = null;
  2416. // let parentComponent = null
  2417. // let grandParentComponent = null
  2418. // let greatGrandParentComponent = null
  2419.  
  2420. const inspect = {
  2421. findComponentsByElement (el) {
  2422. let result = null;
  2423. let deep = 0;
  2424. let parent = el;
  2425. while (parent) {
  2426. if (deep >= 50) {
  2427. break
  2428. }
  2429.  
  2430. if (parent.__vue__) {
  2431. result = parent;
  2432. break
  2433. }
  2434.  
  2435. deep++;
  2436. parent = parent.parentNode;
  2437. }
  2438.  
  2439. return result
  2440. },
  2441.  
  2442. initContextMenu () {
  2443. if (this._hasInitContextMenu_) {
  2444. return
  2445. }
  2446.  
  2447. function createComponentMenuItem (vueComponent, deep = 0) {
  2448. let componentMenu = {};
  2449. if (vueComponent) {
  2450. componentMenu = {
  2451. consoleComponent: {
  2452. name: `查看组件:${vueComponent._componentName}`,
  2453. icon: 'fa-eye',
  2454. callback: function (key, options) {
  2455. debug.log(`[vueComponent] ${vueComponent._componentTag}`, vueComponent);
  2456. }
  2457. },
  2458. consoleComponentData: {
  2459. name: `查看组件数据:${vueComponent._componentName}`,
  2460. icon: 'fa-eye',
  2461. callback: function (key, options) {
  2462. debug.log(`[vueComponentData] ${vueComponent._componentTag}`, vueComponent.$data);
  2463. }
  2464. },
  2465. consoleComponentProps: {
  2466. name: `查看组件props${vueComponent._componentName}`,
  2467. icon: 'fa-eye',
  2468. callback: function (key, options) {
  2469. debug.log(`[vueComponentProps] ${vueComponent._componentTag}`, vueComponent.$props);
  2470. }
  2471. },
  2472. consoleComponentChain: {
  2473. name: `查看组件调用链:${vueComponent._componentName}`,
  2474. icon: 'fa-eye',
  2475. callback: function (key, options) {
  2476. debug.log(`[vueComponentMethods] ${vueComponent._componentTag}`, vueComponent._componentChain);
  2477. }
  2478. }
  2479. };
  2480. }
  2481.  
  2482. if (vueComponent.$parent && deep <= 10) {
  2483. componentMenu.parentComponent = {
  2484. name: `查看父组件:${vueComponent.$parent._componentName}`,
  2485. icon: 'fa-eye',
  2486. items: createComponentMenuItem(vueComponent.$parent, deep + 1)
  2487. };
  2488. }
  2489.  
  2490. const file = vueComponent.options?.__file || vueComponent.$options?.__file || '';
  2491. let copyFilePath = {};
  2492. if (file) {
  2493. copyFilePath = {
  2494. copyFilePath: {
  2495. name: '复制组件文件路径',
  2496. icon: 'fa-copy',
  2497. callback: function (key, options) {
  2498. copyToClipboard(file);
  2499. }
  2500. }
  2501. };
  2502. }
  2503.  
  2504. componentMenu.componentAction = {
  2505. name: `相关操作:${vueComponent._componentName}`,
  2506. icon: 'fa-cog',
  2507. items: {
  2508. ...copyFilePath,
  2509. copyComponentName: {
  2510. name: `复制组件名称:${vueComponent._componentName}`,
  2511. icon: 'fa-copy',
  2512. callback: function (key, options) {
  2513. copyToClipboard(vueComponent._componentName);
  2514. }
  2515. },
  2516. copyComponentData: {
  2517. name: `复制组件$data${vueComponent._componentName}`,
  2518. icon: 'fa-copy',
  2519. callback: function (key, options) {
  2520. const data = JSON.stringify(vueComponent.$data, null, 2);
  2521. copyToClipboard(data);
  2522. debug.log(`[vueComponentData] ${vueComponent._componentName}`, JSON.parse(data));
  2523. debug.log(data);
  2524. }
  2525. },
  2526. copyComponentProps: {
  2527. name: `复制组件$props${vueComponent._componentName}`,
  2528. icon: 'fa-copy',
  2529. callback: function (key, options) {
  2530. const props = JSON.stringify(vueComponent.$props, null, 2);
  2531. copyToClipboard(props);
  2532. debug.log(`[vueComponentProps] ${vueComponent._componentName}`, JSON.parse(props));
  2533. debug.log(props);
  2534. }
  2535. },
  2536. // copyComponentTag: {
  2537. // name: `复制组件标签:${vueComponent._componentTag}`,
  2538. // icon: 'fa-copy',
  2539. // callback: function (key, options) {
  2540. // copyToClipboard(vueComponent._componentTag)
  2541. // }
  2542. // },
  2543. copyComponentUid: {
  2544. name: `复制组件uid${vueComponent._uid}`,
  2545. icon: 'fa-copy',
  2546. callback: function (key, options) {
  2547. copyToClipboard(vueComponent._uid);
  2548. }
  2549. },
  2550. copyComponentChian: {
  2551. name: '复制组件调用链',
  2552. icon: 'fa-copy',
  2553. callback: function (key, options) {
  2554. copyToClipboard(vueComponent._componentChain);
  2555. debug.log(`[vueComponentChain] ${vueComponent._componentName}`, vueComponent._componentChain);
  2556. }
  2557. },
  2558. findComponents: {
  2559. name: `查找组件:${vueComponent._componentName}`,
  2560. icon: 'fa-search',
  2561. callback: function (key, options) {
  2562. functionCall.findComponents(vueComponent._componentName);
  2563. }
  2564. },
  2565. printLifeCycleInfo: {
  2566. name: `打印生命周期信息:${vueComponent._componentName}`,
  2567. icon: 'fa-print',
  2568. callback: function (key, options) {
  2569. functionCall.printLifeCycleInfo(vueComponent._componentName);
  2570. }
  2571. },
  2572. blockComponents: {
  2573. name: `阻断组件:${vueComponent._componentName}`,
  2574. icon: 'fa-ban',
  2575. callback: function (key, options) {
  2576. functionCall.blockComponents(vueComponent._componentName);
  2577. }
  2578. }
  2579. }
  2580. };
  2581.  
  2582. return componentMenu
  2583. }
  2584.  
  2585. $.contextMenu({
  2586. selector: 'body.vue-debug-helper-inspect-mode',
  2587. zIndex: 2147483647,
  2588. build: function ($trigger, e) {
  2589. const conf = helper.config;
  2590. const vueComponent = currentComponent ? currentComponent.__vue__ : null;
  2591.  
  2592. let componentMenu = {};
  2593. if (vueComponent) {
  2594. componentMenu = createComponentMenuItem(vueComponent);
  2595. componentMenu.componentMenuSeparator = '---------';
  2596. }
  2597.  
  2598. const commonMenu = {
  2599. componentsStatistics: {
  2600. name: i18n.t('debugHelper.componentsStatistics'),
  2601. icon: 'fa-thin fa-info-circle',
  2602. callback: functionCall.componentsStatistics
  2603. },
  2604. componentsSummaryStatisticsSort: {
  2605. name: i18n.t('debugHelper.componentsSummaryStatisticsSort'),
  2606. icon: 'fa-thin fa-info-circle',
  2607. callback: functionCall.componentsSummaryStatisticsSort
  2608. },
  2609. destroyStatisticsSort: {
  2610. name: i18n.t('debugHelper.destroyStatisticsSort'),
  2611. icon: 'fa-regular fa-trash',
  2612. callback: functionCall.destroyStatisticsSort
  2613. },
  2614. clearAll: {
  2615. name: i18n.t('debugHelper.clearAll'),
  2616. icon: 'fa-regular fa-close',
  2617. callback: functionCall.clearAll
  2618. },
  2619. statisticsSeparator: '---------',
  2620. findComponents: {
  2621. name: i18n.t('debugHelper.findComponents'),
  2622. icon: 'fa-regular fa-search',
  2623. callback: functionCall.findComponents
  2624. },
  2625. blockComponents: {
  2626. name: i18n.t('debugHelper.blockComponents'),
  2627. icon: 'fa-regular fa-ban',
  2628. callback: functionCall.blockComponents
  2629. },
  2630. printLifeCycleInfo: {
  2631. name: conf.lifecycle.show ? i18n.t('debugHelper.notPrintLifeCycleInfo') : i18n.t('debugHelper.printLifeCycleInfo'),
  2632. icon: 'fa-regular fa-life-ring',
  2633. callback: conf.lifecycle.show ? functionCall.notPrintLifeCycleInfo : functionCall.printLifeCycleInfo
  2634. },
  2635. dd: {
  2636. name: conf.dd.enabled ? i18n.t('debugHelper.undd') : i18n.t('debugHelper.dd'),
  2637. icon: 'fa-regular fa-arrows-alt',
  2638. callback: conf.dd.enabled ? functionCall.undd : functionCall.dd
  2639. },
  2640. toggleHackVueComponent: {
  2641. name: conf.hackVueComponent ? i18n.t('debugHelper.hackVueComponent.unhack') : i18n.t('debugHelper.hackVueComponent.hack'),
  2642. icon: 'fa-regular fa-bug',
  2643. callback: functionCall.toggleHackVueComponent
  2644. },
  2645. togglePerformanceObserver: {
  2646. name: conf.performanceObserver.enabled ? i18n.t('debugHelper.performanceObserverStatus.off') : i18n.t('debugHelper.performanceObserverStatus.on'),
  2647. icon: 'fa-regular fa-paint-brush',
  2648. callback: functionCall.togglePerformanceObserver
  2649. },
  2650. toggleAjaxCache: {
  2651. name: conf.ajaxCache.enabled ? i18n.t('debugHelper.ajaxCacheStatus.off') : i18n.t('debugHelper.ajaxCacheStatus.on'),
  2652. icon: 'fa-regular fa-database',
  2653. callback: functionCall.toggleAjaxCache
  2654. },
  2655. clearAjaxCache: {
  2656. name: i18n.t('debugHelper.clearAjaxCache'),
  2657. icon: 'fa-regular fa-database',
  2658. callback: functionCall.clearAjaxCache
  2659. },
  2660. measureSelectorInterval: {
  2661. name: i18n.t('debugHelper.measureSelectorInterval'),
  2662. icon: 'fa-regular fa-clock-o',
  2663. callback: functionCall.measureSelectorInterval
  2664. },
  2665. commonEndSeparator: '---------',
  2666. toggleInspect: {
  2667. name: conf.inspect.enabled ? i18n.t('debugHelper.inspectStatus.off') : i18n.t('debugHelper.inspectStatus.on'),
  2668. icon: 'fa-regular fa-eye',
  2669. callback: functionCall.toggleInspect
  2670. }
  2671. };
  2672.  
  2673. const menu = {
  2674. callback: function (key, options) {
  2675. debug.log(`[contextMenu] ${key}`);
  2676. },
  2677. items: {
  2678. refresh: {
  2679. name: i18n.t('refreshPage'),
  2680. icon: 'fa-refresh',
  2681. callback: function (key, options) {
  2682. window.location.reload();
  2683. }
  2684. },
  2685. sep0: '---------',
  2686. ...componentMenu,
  2687. ...commonMenu,
  2688. quit: {
  2689. name: i18n.t('quit'),
  2690. icon: 'fa-close',
  2691. callback: function ($element, key, item) {
  2692. return 'context-menu-icon context-menu-icon-quit'
  2693. }
  2694. }
  2695. }
  2696. };
  2697.  
  2698. return menu
  2699. }
  2700. });
  2701.  
  2702. this._hasInitContextMenu_ = true;
  2703. },
  2704.  
  2705. setOverlay (el) {
  2706. let overlay = document.querySelector('#vue-debugger-overlay');
  2707. if (!overlay) {
  2708. overlay = document.createElement('div');
  2709. overlay.id = 'vue-debugger-overlay';
  2710. overlay.style.position = 'fixed';
  2711. overlay.style.backgroundColor = 'rgba(65, 184, 131, 0.35)';
  2712. overlay.style.zIndex = 2147483647;
  2713. overlay.style.pointerEvents = 'none';
  2714. document.body.appendChild(overlay);
  2715. }
  2716.  
  2717. const rect = el.getBoundingClientRect();
  2718.  
  2719. overlay.style.width = rect.width + 'px';
  2720. overlay.style.height = rect.height + 'px';
  2721. overlay.style.left = rect.x + 'px';
  2722. overlay.style.top = rect.y + 'px';
  2723. overlay.style.display = 'block';
  2724.  
  2725. // overlay.parentElement.addEventListener('contextmenu', function (e) {
  2726. // debug.log('overlay contextmenu')
  2727. // e.preventDefault()
  2728. // e.stopPropagation()
  2729. // }, true)
  2730.  
  2731. $(document.body).addClass('vue-debug-helper-inspect-mode');
  2732.  
  2733. inspect.initContextMenu();
  2734. // console.log(el, rect, el.__vue__._componentTag)
  2735. },
  2736.  
  2737. clearOverlay () {
  2738. $(document.body).removeClass('vue-debug-helper-inspect-mode');
  2739. const overlay = document.querySelector('#vue-debugger-overlay');
  2740. if (overlay) {
  2741. overlay.style.display = 'none';
  2742. }
  2743. },
  2744.  
  2745. init (Vue) {
  2746. document.body.addEventListener('mouseover', (event) => {
  2747. if (!helper.config.inspect.enabled) {
  2748. return
  2749. }
  2750.  
  2751. const componentEl = inspect.findComponentsByElement(event.target);
  2752.  
  2753. if (componentEl) {
  2754. currentComponent = componentEl;
  2755. inspect.setOverlay(componentEl);
  2756. } else {
  2757. currentComponent = null;
  2758. }
  2759. });
  2760. }
  2761. };
  2762.  
  2763. /**
  2764. * 元素监听器
  2765. * @param selector -必选
  2766. * @param fn -必选,元素存在时的回调
  2767. * @param shadowRoot -可选 指定监听某个shadowRoot下面的DOM元素
  2768. * 参考:https://javascript.ruanyifeng.com/dom/mutationobserver.html
  2769. */
  2770. function ready (selector, fn, shadowRoot) {
  2771. const win = window;
  2772. const docRoot = shadowRoot || win.document.documentElement;
  2773. if (!docRoot) return false
  2774. const MutationObserver = win.MutationObserver || win.WebKitMutationObserver;
  2775. const listeners = docRoot._MutationListeners || [];
  2776.  
  2777. function $ready (selector, fn) {
  2778. // 储存选择器和回调函数
  2779. listeners.push({
  2780. selector: selector,
  2781. fn: fn
  2782. });
  2783.  
  2784. /* 增加监听对象 */
  2785. if (!docRoot._MutationListeners || !docRoot._MutationObserver) {
  2786. docRoot._MutationListeners = listeners;
  2787. docRoot._MutationObserver = new MutationObserver(() => {
  2788. for (let i = 0; i < docRoot._MutationListeners.length; i++) {
  2789. const item = docRoot._MutationListeners[i];
  2790. check(item.selector, item.fn);
  2791. }
  2792. });
  2793.  
  2794. docRoot._MutationObserver.observe(docRoot, {
  2795. childList: true,
  2796. subtree: true
  2797. });
  2798. }
  2799.  
  2800. // 检查节点是否已经在DOM中
  2801. check(selector, fn);
  2802. }
  2803.  
  2804. function check (selector, fn) {
  2805. const elements = docRoot.querySelectorAll(selector);
  2806. for (let i = 0; i < elements.length; i++) {
  2807. const element = elements[i];
  2808. element._MutationReadyList_ = element._MutationReadyList_ || [];
  2809. if (!element._MutationReadyList_.includes(fn)) {
  2810. element._MutationReadyList_.push(fn);
  2811. fn.call(element, element);
  2812. }
  2813. }
  2814. }
  2815.  
  2816. const selectorArr = Array.isArray(selector) ? selector : [selector];
  2817. selectorArr.forEach(selector => $ready(selector, fn));
  2818. }
  2819.  
  2820. /*!
  2821. * @name functionCall.js
  2822. * @description 统一的提供外部功能调用管理模块
  2823. * @version 0.0.1
  2824. * @author xxxily
  2825. * @date 2022/04/27 17:42
  2826. * @github https://github.com/xxxily
  2827. */
  2828.  
  2829. const functionCall = {
  2830. viewVueDebugHelperObject () {
  2831. debug.log(i18n.t('debugHelper.viewVueDebugHelperObject'), helper);
  2832. },
  2833. componentsStatistics () {
  2834. const result = helper.methods.componentsStatistics();
  2835. let total = 0;
  2836.  
  2837. /* 提供友好的可视化展示方式 */
  2838. console.table && console.table(result.map(item => {
  2839. total += item.componentInstance.length;
  2840. return {
  2841. componentName: item.componentName,
  2842. count: item.componentInstance.length
  2843. }
  2844. }));
  2845.  
  2846. debug.log(`${i18n.t('debugHelper.componentsStatistics')} (total:${total})`, result);
  2847. },
  2848. destroyStatisticsSort () {
  2849. const result = helper.methods.destroyStatisticsSort();
  2850. let total = 0;
  2851.  
  2852. /* 提供友好的可视化展示方式 */
  2853. console.table && console.table(result.map(item => {
  2854. const durationList = item.destroyList.map(item => item.duration);
  2855. const maxDuration = Math.max(...durationList);
  2856. const minDuration = Math.min(...durationList);
  2857. const durationRange = maxDuration - minDuration;
  2858. total += item.destroyList.length;
  2859.  
  2860. return {
  2861. componentName: item.componentName,
  2862. count: item.destroyList.length,
  2863. avgDuration: durationList.reduce((pre, cur) => pre + cur, 0) / durationList.length,
  2864. maxDuration,
  2865. minDuration,
  2866. durationRange,
  2867. durationRangePercent: (1000 - minDuration) / durationRange
  2868. }
  2869. }));
  2870.  
  2871. debug.log(`${i18n.t('debugHelper.destroyStatisticsSort')} (total:${total})`, result);
  2872. },
  2873. componentsSummaryStatisticsSort () {
  2874. const result = helper.methods.componentsSummaryStatisticsSort();
  2875. let total = 0;
  2876.  
  2877. /* 提供友好的可视化展示方式 */
  2878. console.table && console.table(result.map(item => {
  2879. total += item.componentsSummary.length;
  2880. return {
  2881. componentName: item.componentName,
  2882. count: item.componentsSummary.length
  2883. }
  2884. }));
  2885.  
  2886. debug.log(`${i18n.t('debugHelper.componentsSummaryStatisticsSort')} (total:${total})`, result);
  2887. },
  2888. getDestroyByDuration () {
  2889. const destroyInfo = helper.methods.getDestroyByDuration();
  2890. console.table && console.table(destroyInfo.destroyList);
  2891. debug.log(i18n.t('debugHelper.getDestroyByDuration'), destroyInfo);
  2892. },
  2893. clearAll () {
  2894. helper.methods.clearAll();
  2895. debug.log(i18n.t('debugHelper.clearAll'));
  2896. },
  2897.  
  2898. printLifeCycleInfo (str) {
  2899. const lifecycleFilters = window.prompt(i18n.t('debugHelper.printLifeCycleInfoPrompt.lifecycleFilters'), helper.config.lifecycle.filters.join(','));
  2900. const componentFilters = window.prompt(i18n.t('debugHelper.printLifeCycleInfoPrompt.componentFilters'), str || helper.config.lifecycle.componentFilters.join(','));
  2901.  
  2902. if (lifecycleFilters !== null && componentFilters !== null) {
  2903. debug.log(i18n.t('debugHelper.printLifeCycleInfo'));
  2904. helper.methods.printLifeCycleInfo(lifecycleFilters, componentFilters);
  2905. }
  2906. },
  2907.  
  2908. notPrintLifeCycleInfo () {
  2909. debug.log(i18n.t('debugHelper.notPrintLifeCycleInfo'));
  2910. helper.methods.notPrintLifeCycleInfo();
  2911. },
  2912.  
  2913. findComponents (str) {
  2914. const filters = window.prompt(i18n.t('debugHelper.findComponentsPrompt.filters'), str || helper.config.findComponentsFilters.join(','));
  2915. if (filters !== null) {
  2916. debug.log(i18n.t('debugHelper.findComponents'), helper.methods.findComponents(filters));
  2917. }
  2918. },
  2919.  
  2920. findNotContainElementComponents () {
  2921. debug.log(i18n.t('debugHelper.findNotContainElementComponents'), helper.methods.findNotContainElementComponents());
  2922. },
  2923.  
  2924. blockComponents (str) {
  2925. const filters = window.prompt(i18n.t('debugHelper.blockComponentsPrompt.filters'), str || helper.config.blockFilters.join(','));
  2926. if (filters !== null) {
  2927. helper.methods.blockComponents(filters);
  2928. debug.log(i18n.t('debugHelper.blockComponents'), filters);
  2929. }
  2930. },
  2931.  
  2932. dd () {
  2933. const filter = window.prompt(i18n.t('debugHelper.ddPrompt.filter'), helper.config.dd.filters.join(','));
  2934. const count = window.prompt(i18n.t('debugHelper.ddPrompt.count'), helper.config.dd.count);
  2935.  
  2936. if (filter !== null && count !== null) {
  2937. debug.log(i18n.t('debugHelper.dd'));
  2938. helper.methods.dd(filter, Number(count));
  2939. }
  2940. },
  2941.  
  2942. undd () {
  2943. debug.log(i18n.t('debugHelper.undd'));
  2944. helper.methods.undd();
  2945. },
  2946.  
  2947. toggleHackVueComponent () {
  2948. helper.config.hackVueComponent ? vueHooks.unHackVueComponent() : vueHooks.hackVueComponent();
  2949. helper.config.hackVueComponent = !helper.config.hackVueComponent;
  2950. },
  2951.  
  2952. toggleInspect () {
  2953. helper.config.inspect.enabled = !helper.config.inspect.enabled;
  2954. debug.log(`${i18n.t('debugHelper.toggleInspect')} success (${helper.config.inspect.enabled})`);
  2955.  
  2956. if (!helper.config.inspect.enabled) {
  2957. inspect.clearOverlay();
  2958. }
  2959. },
  2960.  
  2961. togglePerformanceObserver () {
  2962. helper.config.performanceObserver.enabled = !helper.config.performanceObserver.enabled;
  2963.  
  2964. if (helper.config.performanceObserver.enabled) {
  2965. let entryTypes = window.prompt(i18n.t('debugHelper.performanceObserverPrompt.entryTypes'), helper.config.performanceObserver.entryTypes.join(','));
  2966. if (entryTypes) {
  2967. const entryTypesArr = toArrFilters(entryTypes);
  2968. const supportEntryTypes = ['element', 'navigation', 'resource', 'mark', 'measure', 'paint', 'longtask'];
  2969.  
  2970. /* 过滤出支持的entryTypes */
  2971. entryTypes = entryTypesArr.filter(item => supportEntryTypes.includes(item));
  2972.  
  2973. if (entryTypes.length !== entryTypesArr.length) {
  2974. debug.warn(`some entryTypes not support, only support: ${supportEntryTypes.join(',')}`);
  2975. }
  2976.  
  2977. helper.config.performanceObserver.entryTypes = entryTypes;
  2978.  
  2979. performanceObserver.init();
  2980. } else {
  2981. alert('entryTypes is empty');
  2982. }
  2983. }
  2984.  
  2985. debug.log(`${i18n.t('debugHelper.togglePerformanceObserver')} success (${helper.config.performanceObserver.enabled})`);
  2986. },
  2987.  
  2988. useAjaxCache () {
  2989. helper.config.ajaxCache.enabled = true;
  2990.  
  2991. const filters = window.prompt(i18n.t('debugHelper.jaxCachePrompt.filters'), helper.config.ajaxCache.filters.join(','));
  2992. const expires = window.prompt(i18n.t('debugHelper.jaxCachePrompt.expires'), helper.config.ajaxCache.expires / 1000 / 60);
  2993.  
  2994. if (filters && expires) {
  2995. helper.config.ajaxCache.filters = toArrFilters(filters);
  2996.  
  2997. if (!isNaN(Number(expires))) {
  2998. helper.config.ajaxCache.expires = Number(expires) * 1000 * 60;
  2999. }
  3000.  
  3001. ajaxHooks.hook();
  3002.  
  3003. debug.log(`${i18n.t('debugHelper.enableAjaxCacheTips')}`);
  3004. }
  3005. },
  3006.  
  3007. disableAjaxCache () {
  3008. helper.config.ajaxCache.enabled = false;
  3009. ajaxHooks.unHook();
  3010. debug.log(`${i18n.t('debugHelper.disableAjaxCacheTips')}`);
  3011. },
  3012.  
  3013. toggleAjaxCache () {
  3014. if (helper.config.ajaxCache.enabled) {
  3015. functionCall.disableAjaxCache();
  3016. } else {
  3017. functionCall.useAjaxCache();
  3018. }
  3019. },
  3020.  
  3021. async clearAjaxCache () {
  3022. await cacheStore.store.clear();
  3023. debug.log(`${i18n.t('debugHelper.clearAjaxCacheTips')}`);
  3024. },
  3025.  
  3026. addMeasureSelectorInterval (selector1, selector2) {
  3027. let result = {};
  3028. if (!functionCall._measureSelectorArr) {
  3029. functionCall._measureSelectorArr = [];
  3030. }
  3031.  
  3032. function measure (element) {
  3033. // debug.log(`[measure] ${i18n.t('debugHelper.measureSelectorInterval')}`, element)
  3034.  
  3035. const selector1 = helper.config.measureSelectorInterval.selector1;
  3036. const selector2 = helper.config.measureSelectorInterval.selector2;
  3037. const selectorArr = [selector1, selector2];
  3038. selectorArr.forEach(selector => {
  3039. if (selector && element.parentElement && element.parentElement.querySelector(selector)) {
  3040. result[selector] = {
  3041. time: Date.now(),
  3042. element: element
  3043. };
  3044.  
  3045. debug.info(`${i18n.t('debugHelper.selectorReadyTips')}: ${selector}`, element);
  3046. }
  3047. });
  3048.  
  3049. if (Object.keys(result).length >= 2) {
  3050. const time = ((result[selector2].time - result[selector1].time) / 1000).toFixed(2);
  3051.  
  3052. debug.info(`[[${selector1}] -> [${selector2}]] time: ${time}s`);
  3053. result = {};
  3054. }
  3055. }
  3056.  
  3057. if (selector1 && selector2) {
  3058. helper.config.measureSelectorInterval.selector1 = selector1;
  3059. helper.config.measureSelectorInterval.selector2 = selector2;
  3060.  
  3061. const selectorArr = [selector1, selector2];
  3062. selectorArr.forEach(selector => {
  3063. if (!functionCall._measureSelectorArr.includes(selector)) {
  3064. // 防止重复注册
  3065. functionCall._measureSelectorArr.push(selector);
  3066.  
  3067. ready(selector, measure);
  3068. }
  3069. });
  3070. } else {
  3071. debug.log('selector is empty, please input selector');
  3072. }
  3073. },
  3074.  
  3075. initMeasureSelectorInterval () {
  3076. const selector1 = helper.config.measureSelectorInterval.selector1;
  3077. const selector2 = helper.config.measureSelectorInterval.selector2;
  3078. if (selector1 && selector2) {
  3079. functionCall.addMeasureSelectorInterval(selector1, selector2);
  3080. debug.log('[measureSelectorInterval] init success');
  3081. }
  3082. },
  3083.  
  3084. measureSelectorInterval () {
  3085. const selector1 = window.prompt(i18n.t('debugHelper.measureSelectorIntervalPrompt.selector1'), helper.config.measureSelectorInterval.selector1);
  3086. const selector2 = window.prompt(i18n.t('debugHelper.measureSelectorIntervalPrompt.selector2'), helper.config.measureSelectorInterval.selector2);
  3087.  
  3088. if (!selector1 && !selector2) {
  3089. helper.config.measureSelectorInterval.selector1 = '';
  3090. helper.config.measureSelectorInterval.selector2 = '';
  3091. }
  3092.  
  3093. functionCall.addMeasureSelectorInterval(selector1, selector2);
  3094. }
  3095. };
  3096.  
  3097. /*!
  3098. * @name menu.js
  3099. * @description vue-debug-helper的菜单配置
  3100. * @version 0.0.1
  3101. * @author xxxily
  3102. * @date 2022/04/25 22:28
  3103. * @github https://github.com/xxxily
  3104. */
  3105.  
  3106. function menuRegister (Vue) {
  3107. if (!Vue) {
  3108. monkeyMenu.on('not detected ' + i18n.t('issues'), () => {
  3109. window.GM_openInTab('https://github.com/xxxily/vue-debug-helper/issues', {
  3110. active: true,
  3111. insert: true,
  3112. setParent: true
  3113. });
  3114. });
  3115. return false
  3116. }
  3117.  
  3118. /* 批量注册菜单 */
  3119. Object.keys(functionCall).forEach(key => {
  3120. const text = i18n.t(`debugHelper.${key}`);
  3121. if (text && functionCall[key] instanceof Function) {
  3122. monkeyMenu.on(text, functionCall[key]);
  3123. }
  3124. });
  3125.  
  3126. /* 是否开启vue-devtools的菜单 */
  3127. const devtoolsText = helper.config.devtools ? i18n.t('debugHelper.devtools.disable') : i18n.t('debugHelper.devtools.enabled');
  3128. monkeyMenu.on(devtoolsText, helper.methods.toggleDevtools);
  3129.  
  3130. // monkeyMenu.on('i18n.t('setting')', () => {
  3131. // window.alert('功能开发中,敬请期待...')
  3132. // })
  3133.  
  3134. monkeyMenu.on(i18n.t('issues'), () => {
  3135. window.GM_openInTab('https://github.com/xxxily/vue-debug-helper/issues', {
  3136. active: true,
  3137. insert: true,
  3138. setParent: true
  3139. });
  3140. });
  3141.  
  3142. // monkeyMenu.on(i18n.t('donate'), () => {
  3143. // window.GM_openInTab('https://cdn.jsdelivr.net/gh/xxxily/vue-debug-helper@main/donate.png', {
  3144. // active: true,
  3145. // insert: true,
  3146. // setParent: true
  3147. // })
  3148. // })
  3149. }
  3150.  
  3151. const isff = typeof navigator !== 'undefined' ? navigator.userAgent.toLowerCase().indexOf('firefox') > 0 : false;
  3152.  
  3153. // 绑定事件
  3154. function addEvent (object, event, method) {
  3155. if (object.addEventListener) {
  3156. object.addEventListener(event, method, false);
  3157. } else if (object.attachEvent) {
  3158. object.attachEvent(`on${event}`, () => { method(window.event); });
  3159. }
  3160. }
  3161.  
  3162. // 修饰键转换成对应的键码
  3163. function getMods (modifier, key) {
  3164. const mods = key.slice(0, key.length - 1);
  3165. for (let i = 0; i < mods.length; i++) mods[i] = modifier[mods[i].toLowerCase()];
  3166. return mods
  3167. }
  3168.  
  3169. // 处理传的key字符串转换成数组
  3170. function getKeys (key) {
  3171. if (typeof key !== 'string') key = '';
  3172. key = key.replace(/\s/g, ''); // 匹配任何空白字符,包括空格、制表符、换页符等等
  3173. const keys = key.split(','); // 同时设置多个快捷键,以','分割
  3174. let index = keys.lastIndexOf('');
  3175.  
  3176. // 快捷键可能包含',',需特殊处理
  3177. for (; index >= 0;) {
  3178. keys[index - 1] += ',';
  3179. keys.splice(index, 1);
  3180. index = keys.lastIndexOf('');
  3181. }
  3182.  
  3183. return keys
  3184. }
  3185.  
  3186. // 比较修饰键的数组
  3187. function compareArray (a1, a2) {
  3188. const arr1 = a1.length >= a2.length ? a1 : a2;
  3189. const arr2 = a1.length >= a2.length ? a2 : a1;
  3190. let isIndex = true;
  3191.  
  3192. for (let i = 0; i < arr1.length; i++) {
  3193. if (arr2.indexOf(arr1[i]) === -1) isIndex = false;
  3194. }
  3195. return isIndex
  3196. }
  3197.  
  3198. // Special Keys
  3199. const _keyMap = {
  3200. backspace: 8,
  3201. tab: 9,
  3202. clear: 12,
  3203. enter: 13,
  3204. return: 13,
  3205. esc: 27,
  3206. escape: 27,
  3207. space: 32,
  3208. left: 37,
  3209. up: 38,
  3210. right: 39,
  3211. down: 40,
  3212. del: 46,
  3213. delete: 46,
  3214. ins: 45,
  3215. insert: 45,
  3216. home: 36,
  3217. end: 35,
  3218. pageup: 33,
  3219. pagedown: 34,
  3220. capslock: 20,
  3221. num_0: 96,
  3222. num_1: 97,
  3223. num_2: 98,
  3224. num_3: 99,
  3225. num_4: 100,
  3226. num_5: 101,
  3227. num_6: 102,
  3228. num_7: 103,
  3229. num_8: 104,
  3230. num_9: 105,
  3231. num_multiply: 106,
  3232. num_add: 107,
  3233. num_enter: 108,
  3234. num_subtract: 109,
  3235. num_decimal: 110,
  3236. num_divide: 111,
  3237. '⇪': 20,
  3238. ',': 188,
  3239. '.': 190,
  3240. '/': 191,
  3241. '`': 192,
  3242. '-': isff ? 173 : 189,
  3243. '=': isff ? 61 : 187,
  3244. ';': isff ? 59 : 186,
  3245. '\'': 222,
  3246. '[': 219,
  3247. ']': 221,
  3248. '\\': 220
  3249. };
  3250.  
  3251. // Modifier Keys
  3252. const _modifier = {
  3253. // shiftKey
  3254. '⇧': 16,
  3255. shift: 16,
  3256. // altKey
  3257. '⌥': 18,
  3258. alt: 18,
  3259. option: 18,
  3260. // ctrlKey
  3261. '⌃': 17,
  3262. ctrl: 17,
  3263. control: 17,
  3264. // metaKey
  3265. '⌘': 91,
  3266. cmd: 91,
  3267. command: 91
  3268. };
  3269. const modifierMap = {
  3270. 16: 'shiftKey',
  3271. 18: 'altKey',
  3272. 17: 'ctrlKey',
  3273. 91: 'metaKey',
  3274.  
  3275. shiftKey: 16,
  3276. ctrlKey: 17,
  3277. altKey: 18,
  3278. metaKey: 91
  3279. };
  3280. const _mods = {
  3281. 16: false,
  3282. 18: false,
  3283. 17: false,
  3284. 91: false
  3285. };
  3286. const _handlers = {};
  3287.  
  3288. // F1~F12 special key
  3289. for (let k = 1; k < 20; k++) {
  3290. _keyMap[`f${k}`] = 111 + k;
  3291. }
  3292.  
  3293. // https://github.com/jaywcjlove/hotkeys
  3294.  
  3295. let _downKeys = []; // 记录摁下的绑定键
  3296. let winListendFocus = false; // window是否已经监听了focus事件
  3297. let _scope = 'all'; // 默认热键范围
  3298. const elementHasBindEvent = []; // 已绑定事件的节点记录
  3299.  
  3300. // 返回键码
  3301. const code = (x) => _keyMap[x.toLowerCase()] ||
  3302. _modifier[x.toLowerCase()] ||
  3303. x.toUpperCase().charCodeAt(0);
  3304.  
  3305. // 设置获取当前范围(默认为'所有')
  3306. function setScope (scope) {
  3307. _scope = scope || 'all';
  3308. }
  3309. // 获取当前范围
  3310. function getScope () {
  3311. return _scope || 'all'
  3312. }
  3313. // 获取摁下绑定键的键值
  3314. function getPressedKeyCodes () {
  3315. return _downKeys.slice(0)
  3316. }
  3317.  
  3318. // 表单控件控件判断 返回 Boolean
  3319. // hotkey is effective only when filter return true
  3320. function filter (event) {
  3321. const target = event.target || event.srcElement;
  3322. const { tagName } = target;
  3323. let flag = true;
  3324. // ignore: isContentEditable === 'true', <input> and <textarea> when readOnly state is false, <select>
  3325. if (
  3326. target.isContentEditable ||
  3327. ((tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT') && !target.readOnly)
  3328. ) {
  3329. flag = false;
  3330. }
  3331. return flag
  3332. }
  3333.  
  3334. // 判断摁下的键是否为某个键,返回true或者false
  3335. function isPressed (keyCode) {
  3336. if (typeof keyCode === 'string') {
  3337. keyCode = code(keyCode); // 转换成键码
  3338. }
  3339. return _downKeys.indexOf(keyCode) !== -1
  3340. }
  3341.  
  3342. // 循环删除handlers中的所有 scope(范围)
  3343. function deleteScope (scope, newScope) {
  3344. let handlers;
  3345. let i;
  3346.  
  3347. // 没有指定scope,获取scope
  3348. if (!scope) scope = getScope();
  3349.  
  3350. for (const key in _handlers) {
  3351. if (Object.prototype.hasOwnProperty.call(_handlers, key)) {
  3352. handlers = _handlers[key];
  3353. for (i = 0; i < handlers.length;) {
  3354. if (handlers[i].scope === scope) handlers.splice(i, 1);
  3355. else i++;
  3356. }
  3357. }
  3358. }
  3359.  
  3360. // 如果scope被删除,将scope重置为all
  3361. if (getScope() === scope) setScope(newScope || 'all');
  3362. }
  3363.  
  3364. // 清除修饰键
  3365. function clearModifier (event) {
  3366. let key = event.keyCode || event.which || event.charCode;
  3367. const i = _downKeys.indexOf(key);
  3368.  
  3369. // 从列表中清除按压过的键
  3370. if (i >= 0) {
  3371. _downKeys.splice(i, 1);
  3372. }
  3373. // 特殊处理 cmmand 键,在 cmmand 组合快捷键 keyup 只执行一次的问题
  3374. if (event.key && event.key.toLowerCase() === 'meta') {
  3375. _downKeys.splice(0, _downKeys.length);
  3376. }
  3377.  
  3378. // 修饰键 shiftKey altKey ctrlKey (command||metaKey) 清除
  3379. if (key === 93 || key === 224) key = 91;
  3380. if (key in _mods) {
  3381. _mods[key] = false;
  3382.  
  3383. // 将修饰键重置为false
  3384. for (const k in _modifier) if (_modifier[k] === key) hotkeys[k] = false;
  3385. }
  3386. }
  3387.  
  3388. function unbind (keysInfo, ...args) {
  3389. // unbind(), unbind all keys
  3390. if (!keysInfo) {
  3391. Object.keys(_handlers).forEach((key) => delete _handlers[key]);
  3392. } else if (Array.isArray(keysInfo)) {
  3393. // support like : unbind([{key: 'ctrl+a', scope: 's1'}, {key: 'ctrl-a', scope: 's2', splitKey: '-'}])
  3394. keysInfo.forEach((info) => {
  3395. if (info.key) eachUnbind(info);
  3396. });
  3397. } else if (typeof keysInfo === 'object') {
  3398. // support like unbind({key: 'ctrl+a, ctrl+b', scope:'abc'})
  3399. if (keysInfo.key) eachUnbind(keysInfo);
  3400. } else if (typeof keysInfo === 'string') {
  3401. // support old method
  3402. // eslint-disable-line
  3403. let [scope, method] = args;
  3404. if (typeof scope === 'function') {
  3405. method = scope;
  3406. scope = '';
  3407. }
  3408. eachUnbind({
  3409. key: keysInfo,
  3410. scope,
  3411. method,
  3412. splitKey: '+'
  3413. });
  3414. }
  3415. }
  3416.  
  3417. // 解除绑定某个范围的快捷键
  3418. const eachUnbind = ({
  3419. key, scope, method, splitKey = '+'
  3420. }) => {
  3421. const multipleKeys = getKeys(key);
  3422. multipleKeys.forEach((originKey) => {
  3423. const unbindKeys = originKey.split(splitKey);
  3424. const len = unbindKeys.length;
  3425. const lastKey = unbindKeys[len - 1];
  3426. const keyCode = lastKey === '*' ? '*' : code(lastKey);
  3427. if (!_handlers[keyCode]) return
  3428. // 判断是否传入范围,没有就获取范围
  3429. if (!scope) scope = getScope();
  3430. const mods = len > 1 ? getMods(_modifier, unbindKeys) : [];
  3431. _handlers[keyCode] = _handlers[keyCode].filter((record) => {
  3432. // 通过函数判断,是否解除绑定,函数相等直接返回
  3433. const isMatchingMethod = method ? record.method === method : true;
  3434. return !(
  3435. isMatchingMethod &&
  3436. record.scope === scope &&
  3437. compareArray(record.mods, mods)
  3438. )
  3439. });
  3440. });
  3441. };
  3442.  
  3443. // 对监听对应快捷键的回调函数进行处理
  3444. function eventHandler (event, handler, scope, element) {
  3445. if (handler.element !== element) {
  3446. return
  3447. }
  3448. let modifiersMatch;
  3449.  
  3450. // 看它是否在当前范围
  3451. if (handler.scope === scope || handler.scope === 'all') {
  3452. // 检查是否匹配修饰符(如果有返回true)
  3453. modifiersMatch = handler.mods.length > 0;
  3454.  
  3455. for (const y in _mods) {
  3456. if (Object.prototype.hasOwnProperty.call(_mods, y)) {
  3457. if (
  3458. (!_mods[y] && handler.mods.indexOf(+y) > -1) ||
  3459. (_mods[y] && handler.mods.indexOf(+y) === -1)
  3460. ) {
  3461. modifiersMatch = false;
  3462. }
  3463. }
  3464. }
  3465.  
  3466. // 调用处理程序,如果是修饰键不做处理
  3467. if (
  3468. (handler.mods.length === 0 &&
  3469. !_mods[16] &&
  3470. !_mods[18] &&
  3471. !_mods[17] &&
  3472. !_mods[91]) ||
  3473. modifiersMatch ||
  3474. handler.shortcut === '*'
  3475. ) {
  3476. if (handler.method(event, handler) === false) {
  3477. if (event.preventDefault) event.preventDefault();
  3478. else event.returnValue = false;
  3479. if (event.stopPropagation) event.stopPropagation();
  3480. if (event.cancelBubble) event.cancelBubble = true;
  3481. }
  3482. }
  3483. }
  3484. }
  3485.  
  3486. // 处理keydown事件
  3487. function dispatch (event, element) {
  3488. const asterisk = _handlers['*'];
  3489. let key = event.keyCode || event.which || event.charCode;
  3490.  
  3491. // 表单控件过滤 默认表单控件不触发快捷键
  3492. if (!hotkeys.filter.call(this, event)) return
  3493.  
  3494. // Gecko(Firefox)的command键值224,在Webkit(Chrome)中保持一致
  3495. // Webkit左右 command 键值不一样
  3496. if (key === 93 || key === 224) key = 91;
  3497.  
  3498. /**
  3499. * Collect bound keys
  3500. * If an Input Method Editor is processing key input and the event is keydown, return 229.
  3501. * https://stackoverflow.com/questions/25043934/is-it-ok-to-ignore-keydown-events-with-keycode-229
  3502. * http://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
  3503. */
  3504. if (_downKeys.indexOf(key) === -1 && key !== 229) _downKeys.push(key);
  3505. /**
  3506. * Jest test cases are required.
  3507. * ===============================
  3508. */
  3509. ['ctrlKey', 'altKey', 'shiftKey', 'metaKey'].forEach((keyName) => {
  3510. const keyNum = modifierMap[keyName];
  3511. if (event[keyName] && _downKeys.indexOf(keyNum) === -1) {
  3512. _downKeys.push(keyNum);
  3513. } else if (!event[keyName] && _downKeys.indexOf(keyNum) > -1) {
  3514. _downKeys.splice(_downKeys.indexOf(keyNum), 1);
  3515. } else if (keyName === 'metaKey' && event[keyName] && _downKeys.length === 3) {
  3516. /**
  3517. * Fix if Command is pressed:
  3518. * ===============================
  3519. */
  3520. if (!(event.ctrlKey || event.shiftKey || event.altKey)) {
  3521. _downKeys = _downKeys.slice(_downKeys.indexOf(keyNum));
  3522. }
  3523. }
  3524. });
  3525. /**
  3526. * -------------------------------
  3527. */
  3528.  
  3529. if (key in _mods) {
  3530. _mods[key] = true;
  3531.  
  3532. // 将特殊字符的key注册到 hotkeys 上
  3533. for (const k in _modifier) {
  3534. if (_modifier[k] === key) hotkeys[k] = true;
  3535. }
  3536.  
  3537. if (!asterisk) return
  3538. }
  3539.  
  3540. // 将 modifierMap 里面的修饰键绑定到 event 中
  3541. for (const e in _mods) {
  3542. if (Object.prototype.hasOwnProperty.call(_mods, e)) {
  3543. _mods[e] = event[modifierMap[e]];
  3544. }
  3545. }
  3546. /**
  3547. * https://github.com/jaywcjlove/hotkeys/pull/129
  3548. * This solves the issue in Firefox on Windows where hotkeys corresponding to special characters would not trigger.
  3549. * An example of this is ctrl+alt+m on a Swedish keyboard which is used to type μ.
  3550. * Browser support: https://caniuse.com/#feat=keyboardevent-getmodifierstate
  3551. */
  3552. if (event.getModifierState && (!(event.altKey && !event.ctrlKey) && event.getModifierState('AltGraph'))) {
  3553. if (_downKeys.indexOf(17) === -1) {
  3554. _downKeys.push(17);
  3555. }
  3556.  
  3557. if (_downKeys.indexOf(18) === -1) {
  3558. _downKeys.push(18);
  3559. }
  3560.  
  3561. _mods[17] = true;
  3562. _mods[18] = true;
  3563. }
  3564.  
  3565. // 获取范围 默认为 `all`
  3566. const scope = getScope();
  3567. // 对任何快捷键都需要做的处理
  3568. if (asterisk) {
  3569. for (let i = 0; i < asterisk.length; i++) {
  3570. if (
  3571. asterisk[i].scope === scope &&
  3572. ((event.type === 'keydown' && asterisk[i].keydown) ||
  3573. (event.type === 'keyup' && asterisk[i].keyup))
  3574. ) {
  3575. eventHandler(event, asterisk[i], scope, element);
  3576. }
  3577. }
  3578. }
  3579. // key 不在 _handlers 中返回
  3580. if (!(key in _handlers)) return
  3581.  
  3582. for (let i = 0; i < _handlers[key].length; i++) {
  3583. if (
  3584. (event.type === 'keydown' && _handlers[key][i].keydown) ||
  3585. (event.type === 'keyup' && _handlers[key][i].keyup)
  3586. ) {
  3587. if (_handlers[key][i].key) {
  3588. const record = _handlers[key][i];
  3589. const { splitKey } = record;
  3590. const keyShortcut = record.key.split(splitKey);
  3591. const _downKeysCurrent = []; // 记录当前按键键值
  3592. for (let a = 0; a < keyShortcut.length; a++) {
  3593. _downKeysCurrent.push(code(keyShortcut[a]));
  3594. }
  3595. if (_downKeysCurrent.sort().join('') === _downKeys.sort().join('')) {
  3596. // 找到处理内容
  3597. eventHandler(event, record, scope, element);
  3598. }
  3599. }
  3600. }
  3601. }
  3602. }
  3603.  
  3604. // 判断 element 是否已经绑定事件
  3605. function isElementBind (element) {
  3606. return elementHasBindEvent.indexOf(element) > -1
  3607. }
  3608.  
  3609. function hotkeys (key, option, method) {
  3610. _downKeys = [];
  3611. const keys = getKeys(key); // 需要处理的快捷键列表
  3612. let mods = [];
  3613. let scope = 'all'; // scope默认为all,所有范围都有效
  3614. let element = document; // 快捷键事件绑定节点
  3615. let i = 0;
  3616. let keyup = false;
  3617. let keydown = true;
  3618. let splitKey = '+';
  3619.  
  3620. // 对为设定范围的判断
  3621. if (method === undefined && typeof option === 'function') {
  3622. method = option;
  3623. }
  3624.  
  3625. if (Object.prototype.toString.call(option) === '[object Object]') {
  3626. if (option.scope) scope = option.scope; // eslint-disable-line
  3627. if (option.element) element = option.element; // eslint-disable-line
  3628. if (option.keyup) keyup = option.keyup; // eslint-disable-line
  3629. if (option.keydown !== undefined) keydown = option.keydown; // eslint-disable-line
  3630. if (typeof option.splitKey === 'string') splitKey = option.splitKey; // eslint-disable-line
  3631. }
  3632.  
  3633. if (typeof option === 'string') scope = option;
  3634.  
  3635. // 对于每个快捷键进行处理
  3636. for (; i < keys.length; i++) {
  3637. key = keys[i].split(splitKey); // 按键列表
  3638. mods = [];
  3639.  
  3640. // 如果是组合快捷键取得组合快捷键
  3641. if (key.length > 1) mods = getMods(_modifier, key);
  3642.  
  3643. // 将非修饰键转化为键码
  3644. key = key[key.length - 1];
  3645. key = key === '*' ? '*' : code(key); // *表示匹配所有快捷键
  3646.  
  3647. // 判断key是否在_handlers中,不在就赋一个空数组
  3648. if (!(key in _handlers)) _handlers[key] = [];
  3649. _handlers[key].push({
  3650. keyup,
  3651. keydown,
  3652. scope,
  3653. mods,
  3654. shortcut: keys[i],
  3655. method,
  3656. key: keys[i],
  3657. splitKey,
  3658. element
  3659. });
  3660. }
  3661. // 在全局document上设置快捷键
  3662. if (typeof element !== 'undefined' && !isElementBind(element) && window) {
  3663. elementHasBindEvent.push(element);
  3664. addEvent(element, 'keydown', (e) => {
  3665. dispatch(e, element);
  3666. });
  3667. if (!winListendFocus) {
  3668. winListendFocus = true;
  3669. addEvent(window, 'focus', () => {
  3670. _downKeys = [];
  3671. });
  3672. }
  3673. addEvent(element, 'keyup', (e) => {
  3674. dispatch(e, element);
  3675. clearModifier(e);
  3676. });
  3677. }
  3678. }
  3679.  
  3680. function trigger (shortcut, scope = 'all') {
  3681. Object.keys(_handlers).forEach((key) => {
  3682. const data = _handlers[key].find((item) => item.scope === scope && item.shortcut === shortcut);
  3683. if (data && data.method) {
  3684. data.method();
  3685. }
  3686. });
  3687. }
  3688.  
  3689. const _api = {
  3690. setScope,
  3691. getScope,
  3692. deleteScope,
  3693. getPressedKeyCodes,
  3694. isPressed,
  3695. filter,
  3696. trigger,
  3697. unbind,
  3698. keyMap: _keyMap,
  3699. modifier: _modifier,
  3700. modifierMap
  3701. };
  3702. for (const a in _api) {
  3703. if (Object.prototype.hasOwnProperty.call(_api, a)) {
  3704. hotkeys[a] = _api[a];
  3705. }
  3706. }
  3707.  
  3708. if (typeof window !== 'undefined') {
  3709. const _hotkeys = window.hotkeys;
  3710. hotkeys.noConflict = (deep) => {
  3711. if (deep && window.hotkeys === hotkeys) {
  3712. window.hotkeys = _hotkeys;
  3713. }
  3714. return hotkeys
  3715. };
  3716. window.hotkeys = hotkeys;
  3717. }
  3718.  
  3719. /*!
  3720. * @name hotKeyRegister.js
  3721. * @description vue-debug-helper的快捷键配置
  3722. * @version 0.0.1
  3723. * @author xxxily
  3724. * @date 2022/04/26 14:37
  3725. * @github https://github.com/xxxily
  3726. */
  3727.  
  3728. function hotKeyRegister () {
  3729. const hotKeyMap = {
  3730. 'shift+alt+i': functionCall.toggleInspect,
  3731. 'shift+alt+a,shift+alt+ctrl+a': functionCall.componentsSummaryStatisticsSort,
  3732. 'shift+alt+l': functionCall.componentsStatistics,
  3733. 'shift+alt+d': functionCall.destroyStatisticsSort,
  3734. 'shift+alt+c': functionCall.clearAll,
  3735. 'shift+alt+e': function (event, handler) {
  3736. if (helper.config.dd.enabled) {
  3737. functionCall.undd();
  3738. } else {
  3739. functionCall.dd();
  3740. }
  3741. }
  3742. };
  3743.  
  3744. Object.keys(hotKeyMap).forEach(key => {
  3745. hotkeys(key, hotKeyMap[key]);
  3746. });
  3747. }
  3748.  
  3749. /*!
  3750. * @name vueDetector.js
  3751. * @description 检测页面是否存在Vue对象
  3752. * @version 0.0.1
  3753. * @author xxxily
  3754. * @date 2022/04/27 11:43
  3755. * @github https://github.com/xxxily
  3756. */
  3757.  
  3758. function mutationDetector (callback, shadowRoot) {
  3759. const win = window;
  3760. const MutationObserver = win.MutationObserver || win.WebKitMutationObserver;
  3761. const docRoot = shadowRoot || win.document.documentElement;
  3762. const maxDetectTries = 1500;
  3763. const timeout = 1000 * 10;
  3764. const startTime = Date.now();
  3765. let detectCount = 0;
  3766. let detectStatus = false;
  3767.  
  3768. if (!MutationObserver) {
  3769. debug.warn('MutationObserver is not supported in this browser');
  3770. return false
  3771. }
  3772.  
  3773. let mObserver = null;
  3774. const mObserverCallback = (mutationsList, observer) => {
  3775. if (detectStatus) {
  3776. return
  3777. }
  3778.  
  3779. /* 超时或检测次数过多,取消监听 */
  3780. if (Date.now() - startTime > timeout || detectCount > maxDetectTries) {
  3781. debug.warn('mutationDetector timeout or detectCount > maxDetectTries, stop detect');
  3782. if (mObserver && mObserver.disconnect) {
  3783. mObserver.disconnect();
  3784. mObserver = null;
  3785. }
  3786. }
  3787.  
  3788. for (let i = 0; i < mutationsList.length; i++) {
  3789. detectCount++;
  3790. const mutation = mutationsList[i];
  3791. if (mutation.target && mutation.target.__vue__) {
  3792. let Vue = Object.getPrototypeOf(mutation.target.__vue__).constructor;
  3793. while (Vue.super) {
  3794. Vue = Vue.super;
  3795. }
  3796.  
  3797. /* 检测成功后销毁观察对象 */
  3798. if (mObserver && mObserver.disconnect) {
  3799. mObserver.disconnect();
  3800. mObserver = null;
  3801. }
  3802.  
  3803. detectStatus = true;
  3804. callback && callback(Vue);
  3805. break
  3806. }
  3807. }
  3808. };
  3809.  
  3810. mObserver = new MutationObserver(mObserverCallback);
  3811. mObserver.observe(docRoot, {
  3812. attributes: true,
  3813. childList: true,
  3814. subtree: true
  3815. });
  3816. }
  3817.  
  3818. /**
  3819. * 检测页面是否存在Vue对象,方法参考:https://github.com/vuejs/devtools/blob/main/packages/shell-chrome/src/detector.js
  3820. * @param {window} win windwod对象
  3821. * @param {function} callback 检测到Vue对象后的回调函数
  3822. */
  3823. function vueDetect (win, callback) {
  3824. let delay = 1000;
  3825. let detectRemainingTries = 10;
  3826. let detectSuc = false;
  3827.  
  3828. // Method 1: MutationObserver detector
  3829. mutationDetector((Vue) => {
  3830. if (!detectSuc) {
  3831. debug.info(`------------- Vue mutation detected (${Vue.version}) -------------`);
  3832. detectSuc = true;
  3833. callback(Vue);
  3834. }
  3835. });
  3836.  
  3837. function runDetect () {
  3838. if (detectSuc) {
  3839. return false
  3840. }
  3841.  
  3842. // Method 2: Check Vue 3
  3843. const vueDetected = !!(win.__VUE__);
  3844. if (vueDetected) {
  3845. debug.info(`------------- Vue global detected (${win.__VUE__.version}) -------------`);
  3846. detectSuc = true;
  3847. callback(win.__VUE__);
  3848. return
  3849. }
  3850.  
  3851. // Method 3: Scan all elements inside document
  3852. const all = document.querySelectorAll('*');
  3853. let el;
  3854. for (let i = 0; i < all.length; i++) {
  3855. if (all[i].__vue__) {
  3856. el = all[i];
  3857. break
  3858. }
  3859. }
  3860. if (el) {
  3861. let Vue = Object.getPrototypeOf(el.__vue__).constructor;
  3862. while (Vue.super) {
  3863. Vue = Vue.super;
  3864. }
  3865. debug.info(`------------- Vue dom detected (${Vue.version}) -------------`);
  3866. detectSuc = true;
  3867. callback(Vue);
  3868. return
  3869. }
  3870.  
  3871. if (detectRemainingTries > 0) {
  3872. detectRemainingTries--;
  3873.  
  3874. if (detectRemainingTries >= 7) {
  3875. setTimeout(() => {
  3876. runDetect();
  3877. }, 40);
  3878. } else {
  3879. setTimeout(() => {
  3880. runDetect();
  3881. }, delay);
  3882. delay *= 5;
  3883. }
  3884. }
  3885. }
  3886.  
  3887. setTimeout(() => {
  3888. runDetect();
  3889. }, 40);
  3890. }
  3891.  
  3892. /*!
  3893. * @name vueConfig.js
  3894. * @description 对Vue的配置进行修改
  3895. * @version 0.0.1
  3896. * @author xxxily
  3897. * @date 2022/05/10 15:15
  3898. * @github https://github.com/xxxily
  3899. */
  3900.  
  3901. function vueConfigInit (Vue, config) {
  3902. if (Vue.config) {
  3903. /* 自动开启Vue的调试模式 */
  3904. if (config.devtools) {
  3905. Vue.config.debug = true;
  3906. Vue.config.devtools = true;
  3907. Vue.config.performance = true;
  3908.  
  3909. setTimeout(() => {
  3910. const devtools = getVueDevtools();
  3911. if (devtools) {
  3912. if (!devtools.enabled) {
  3913. devtools.emit('init', Vue);
  3914. debug.info('vue devtools init emit.');
  3915. }
  3916. } else {
  3917. // debug.info(
  3918. // 'Download the Vue Devtools extension for a better development experience:\n' +
  3919. // 'https://github.com/vuejs/vue-devtools'
  3920. // )
  3921. debug.info('vue devtools check failed.');
  3922. }
  3923. }, 200);
  3924. } else {
  3925. Vue.config.debug = false;
  3926. Vue.config.devtools = false;
  3927. Vue.config.performance = false;
  3928. }
  3929. } else {
  3930. debug.log('Vue.config is not defined');
  3931. }
  3932. }
  3933.  
  3934. /**
  3935. * 判断是否处于Iframe中
  3936. * @returns {boolean}
  3937. */
  3938. function isInIframe () {
  3939. return window !== window.top
  3940. }
  3941.  
  3942. /**
  3943. * 由于tampermonkey对window对象进行了封装,我们实际访问到的window并非页面真实的window
  3944. * 这就导致了如果我们需要将某些对象挂载到页面的window进行调试的时候就无法挂载了
  3945. * 所以必须使用特殊手段才能访问到页面真实的window对象,于是就有了下面这个函数
  3946. * @returns {Promise<void>}
  3947. */
  3948. async function getPageWindow () {
  3949. return new Promise(function (resolve, reject) {
  3950. if (window._pageWindow) {
  3951. return resolve(window._pageWindow)
  3952. }
  3953.  
  3954. const listenEventList = ['load', 'mousemove', 'scroll', 'get-page-window-event'];
  3955.  
  3956. function getWin (event) {
  3957. window._pageWindow = this;
  3958. // debug.log('getPageWindow succeed', event)
  3959. listenEventList.forEach(eventType => {
  3960. window.removeEventListener(eventType, getWin, true);
  3961. });
  3962. resolve(window._pageWindow);
  3963. }
  3964.  
  3965. listenEventList.forEach(eventType => {
  3966. window.addEventListener(eventType, getWin, true);
  3967. });
  3968.  
  3969. /* 自行派发事件以便用最短的时候获得pageWindow对象 */
  3970. window.dispatchEvent(new window.Event('get-page-window-event'));
  3971. })
  3972. }
  3973. // getPageWindow()
  3974.  
  3975. /**
  3976. * 通过同步的方式获取pageWindow
  3977. * 注意同步获取的方式需要将脚本写入head,部分网站由于安全策略会导致写入失败,而无法正常获取
  3978. * @returns {*}
  3979. */
  3980. function getPageWindowSync () {
  3981. if (document._win_) return document._win_
  3982.  
  3983. const head = document.head || document.querySelector('head');
  3984. const script = document.createElement('script');
  3985. script.appendChild(document.createTextNode('document._win_ = window'));
  3986. head.appendChild(script);
  3987.  
  3988. return document._win_
  3989. }
  3990.  
  3991. let registerStatus = 'init';
  3992. window._debugMode_ = true;
  3993.  
  3994. /* 注入相关样式到页面 */
  3995. if (window.GM_getResourceText && window.GM_addStyle) {
  3996. const contextMenuCss = window.GM_getResourceText('contextMenuCss');
  3997. window.GM_addStyle(contextMenuCss);
  3998. }
  3999.  
  4000. function init (win) {
  4001. if (isInIframe()) {
  4002. debug.log('running in iframe, skip init', window.location.href);
  4003. return false
  4004. }
  4005.  
  4006. if (registerStatus === 'initing') {
  4007. return false
  4008. }
  4009.  
  4010. registerStatus = 'initing';
  4011.  
  4012. vueDetect(win, function (Vue) {
  4013. /* 挂载到window上,方便通过控制台调用调试 */
  4014. helper.Vue = Vue;
  4015. win.vueDebugHelper = helper;
  4016.  
  4017. /* 注册阻断Vue组件的功能 */
  4018. vueHooks.blockComponents(Vue, helper.config);
  4019.  
  4020. /* 注册打印全局组件注册信息的功能 */
  4021. if (helper.config.hackVueComponent) {
  4022. vueHooks.hackVueComponent(Vue);
  4023. }
  4024.  
  4025. /* 注册接口拦截功能和接近数据缓存功能 */
  4026. ajaxHooks.init(win);
  4027.  
  4028. /* 注册性能观察的功能 */
  4029. performanceObserver.init();
  4030.  
  4031. /* 注册选择器测量辅助功能 */
  4032. functionCall.initMeasureSelectorInterval();
  4033.  
  4034. /* 对Vue相关配置进行初始化 */
  4035. vueConfigInit(Vue, helper.config);
  4036.  
  4037. mixinRegister(Vue);
  4038. menuRegister(Vue);
  4039. hotKeyRegister();
  4040.  
  4041. inspect.init(Vue);
  4042.  
  4043. debug.log('vue debug helper register success');
  4044. registerStatus = 'success';
  4045. });
  4046.  
  4047. setTimeout(() => {
  4048. if (registerStatus !== 'success') {
  4049. menuRegister(null);
  4050. debug.warn('vue debug helper register failed, please check if vue is loaded .', win.location.href);
  4051. }
  4052. }, 1000 * 10);
  4053. }
  4054.  
  4055. let win$1 = null;
  4056. try {
  4057. win$1 = getPageWindowSync();
  4058. if (win$1) {
  4059. init(win$1);
  4060. debug.log('getPageWindowSync success');
  4061. }
  4062. } catch (e) {
  4063. debug.error('getPageWindowSync failed', e);
  4064. }
  4065. (async function () {
  4066. if (!win$1) {
  4067. win$1 = await getPageWindow();
  4068. init(win$1);
  4069. }
  4070. })();