@ng1005/chrome-extension-common
Version:
chrome扩展通用库--消息与storage
2 lines (1 loc) • 28.5 kB
JavaScript
function e(e){return!!s(e)&&"AsyncFunction"===e.constructor.name}function t(e){return!!s(e)&&"Function"===e.constructor.name}function s(e){return void 0!==e}function n(){return!(!s(chrome)||!s(chrome.runtime))}function r(){return!!n()&&!(!chrome.tabs||t(chrome.extension.getBackgroundPage))}function i(){return!!n()&&!(!chrome.tabs||!t(chrome.extension.getBackgroundPage))}function o(){return!!n()&&!chrome.tabs}function c(e){return"[object String]"===Object.prototype.toString.call(e)}function a(e){var t=Object.prototype.toString.call(e);return"[object Array]"===t||"[object Object]"===t}function l(e){return"[object Object]"===Object.prototype.toString.call(e)}function h(e){return"[object Array]"===Object.prototype.toString.call(e)}function u(){return!("undefined"==typeof process||!process.versions||!process.versions.node)}function d(){return u()?"node":r()?"background":o()?"content":i()?"popup":""}function p(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}class m{_events;constructor(){this._events=new Map}$on(e,t){const s=this._events.get(e)||[];return s?s&&"function"==typeof s?this._events.set(e,[s,t]):(s.push(t),this._events.set(e,s)):this._events.set(e,t),this}$emit(t,...s){return new Promise((async(n,r)=>{let i=this._events.get(t);if(!i)return Promise.resolve("");if(Array.isArray(i))for(let t=0;t<i.length;++t)if(e(i[t])){n(await i[t].call(this,...s))}else{n(i[t].call(this,...s))}else if(e(i)){n(await i.call(this,...s))}else{n(i.call(this,...s))}return Promise.resolve("")}))}$off(e,t){const s=this._events.get(e);return s&&"function"==typeof s?this._events.delete(e):Array.isArray(s)&&s.splice(s.findIndex((e=>e===t)),1),this}$once(e,t){let s=this;return this.$on(e,(function n(){s.$off(e,n),t.apply(null,arguments)}))}}const g=new m;class f extends m{crossExtension=!1;getCurrentTabId(e){return this.getCurrentTabs((t=>{const s=t.length?t[0].id:null;s||Promise.reject("未找到激活的tab"),e(s)})),this}getTabs(e,t){let s=Object.assign({},t);return chrome.tabs.query(s,(function(t){e&&e(t)})),this}getCurrentTabs(e){return this.getTabs(e,{active:!0,currentWindow:!0})}}const y={success:(e,t="")=>({code:200,data:e,message:t}),error:(e,t={})=>({code:500,message:e,data:t}),isSuccess:e=>!(!e||200!=e.code)};class b extends f{script="content";types={content2AllTabs:"_message_bridge_content2AllTabs_"};constructor(e){super();let t="content";r()?t="background":i()&&(t="popup"),this.script=e||t,this.listener(),this.listenerBridge()}listener(){let e=this;chrome.runtime.onMessage.addListener((function(t,s,n){if(s.id!=chrome.runtime.id)return;let r=t.script;return e.script===r?(e.handler(t,s,n),!0):void 0}))}listenerBridge(){if("background"===this.script){let e=this;chrome.runtime.onMessage.addListener((function(t,s,n){if(s.id!=chrome.runtime.id&&!e.crossExtension)return;let r=t.script;if(e.script===r){if(t.bridgeType===e.types.content2AllTabs)e.$emitAllTabs(t.type,...t.message);return!0}}))}}async handler(t,s,n){let r=t.type||"",i=t.message,o=this,c=o._events.get(r);if(c)if(Array.isArray(c))for(let t=0;t<c.length;++t){let r="";e(c[t])?c[t].call(o,...i,s,n).then((e=>{n(y.success(e))})).catch((e=>{n(y.error(e))})):(r=c[t].call(o,...i,s,n),p(r)?r.then((e=>{n(y.success(e))})).catch((e=>{n(y.error(e))})):n(r?y.success(r):y.error("未知错误")))}else{let t="";e(c)?c.call(o,...i,s,n).then((e=>{n(y.success(e))})).catch((e=>{n(y.error(e))})):(t=c.call(o,...i,s,n),p(t)?t.then((e=>{n(y.success(e))})).catch((e=>{n(y.error(e))})):n(t?y.success(t):y.error("未知错误")))}}$emitContent(e,...t){let s=this,n="content";return s.script===n?new Promise(((s,n)=>{chrome.runtime.sendMessage({script:"content",type:e,message:t},(e=>{y.isSuccess(e)?s(e.data):n(e.message)}))})):new Promise(((r,i)=>{s.getCurrentTabs((s=>{const o=s.length?s[0].id:null;o||i("找到激活的tab");const c={script:n,type:e,message:t};chrome.tabs.sendMessage(o,c,(function(e){y.isSuccess(e)?r(e.data):i(e.message)}))}))}))}$emitBackground(e,...t){return new Promise(((s,n)=>{const r={script:"background",type:e,message:t};chrome.runtime.sendMessage(r,(e=>{y.isSuccess(e)?s(e.data):n(e.message)}))}))}$emitPopup(e,...t){return new Promise(((s,n)=>{const r={script:"popup",type:e,message:t};chrome.runtime.sendMessage(r,(e=>{y.isSuccess(e)?s(e.data):n(e.message)}))}))}$emitWindow(e,...t){if("content"===this.script)return new Promise(((s,n)=>{window.postMessage({script:"window",type:e,message:t})}));throw new Error("当前页面不支持发送消息给window.")}$emitAllTabs(e,...t){let s=this,n="content";return s.script===n?new Promise(((n,r)=>{chrome.runtime.sendMessage({bridgeType:s.types.content2AllTabs,script:"background",type:e,message:t},(e=>{y.isSuccess(e)?n(e.data):r(e.message)}))})):new Promise(((r,i)=>{s.getTabs((s=>{if(s&&Array.isArray(s)&&s.length>0)for(let o=0;o<s.length;o++){const c=s[o].id||null,a={script:n,type:e,message:t};chrome.tabs.sendMessage(c,a,(function(e){o===s.length&&(y.isSuccess(e)?r(e.data):i(e.message))}))}else i("找到激活的tab")}),{})}))}}const w=new b;class v extends f{script="content";port;portTab;popupListener=!1;constructor(e){super();let t="content";r()?t="background":i()&&(t="popup"),this.script=e||t,this.connect()}connect(){let e=this;["popup","background"].indexOf(e.script)>-1&&e.getCurrentTabs((t=>{const s=t.length?t[0].id:null;s?(e.portTab=chrome.tabs.connect(s,{name:e.script}),e.portTab.onMessage.addListener((function(t){e.handler(t)})),e.popupListener=!0):this.popListener()}));let t=chrome.runtime.connect({name:this.script});return this.port=t,this.port.onMessage.addListener((function(t){e.handler(t)})),this.listener(),this}popListener(){let e=this;return chrome.tabs.onActivated.addListener((()=>{this.popupListener||e.getCurrentTabs((t=>{const s=t.length?t[0].id:null;e.popupListener=!0,e.portTab=chrome.tabs.connect(s,{name:e.script}),e.portTab.onMessage.addListener((function(t){e.handler(t)}))}))})),this}listener(){let e=this;return chrome.runtime.onConnect.addListener((t=>{t.onMessage.addListener((t=>{e.handler(t)}))})),this}checkConnect(){return null!=this.port&&null!=this.portTab&&""!=this.port.name||this.connect(),this}async handler(e){let t=e.type||"",s=e.message;if(this.script!==e.script)return;let n=this,r=n._events.get(t);if(r){if(Array.isArray(r))for(let e=0;e<r.length;++e)await r[e].call(n,...s);else await r.call(n,...s);return this}}$emitContent(e,...t){return"content"==this.script?this.$emit(e,...t):new Promise(((s,n)=>{if(this.checkConnect(),this.portTab){{let s={script:"content",type:e,message:t};this.portTab.postMessage(s)}s("")}else n("portTab is undefine!")}))}$emitBackground(e,...t){return"background"===this.script?this.$emit(e,...t):new Promise(((s,n)=>{if(this.checkConnect(),this.port){let s={script:"background",type:e,message:t};this.port.postMessage(s)}else console.log("port is undefine!");s("")}))}$emitPopup(e,...t){return"popup"===this.script?this.$emit(e,...t):new Promise(((s,n)=>{if(this.checkConnect(),this.port){let s={script:"popup",type:e,message:t};this.port.postMessage(s)}else console.log("port is undefine!");s("")}))}$emitWindow(e,...t){throw new Error("Method not support.")}$emitAllTabs(e,...t){throw new Error("Method not support.")}}const _=new v;class $ extends f{script="window";constructor(e){super();let t="window";r()?t="background":i()&&(t="popup"),this.script=e||t,"window"===this.script&&this.listener()}listener(){let e=this;window.addEventListener("message",(function(t){e.handler(t.data)}))}async handler(e){let t=e.type||"",s=e.message,n=this,r=n._events.get(t);if(r){if(Array.isArray(r))for(let e=0;e<r.length;++e)await r[e].call(n,...s);else await r.call(n,...s);return this}}$emitContent(e,...t){let s=this;return new Promise(((n,r)=>{s.getCurrentTabs((s=>{const i=s.length?s[0].id:null;i||r("找到激活的tab");const o={script:"content",type:e,message:t};chrome.tabs.sendMessage(i,o,(function(e){n(e)}))}))}))}$emitBackground(e,...t){return new Promise(((s,n)=>{const r={script:"background",type:e,message:t};chrome.runtime.sendMessage(r,(e=>{y.isSuccess(e)?s(e.data):n(e.message)}))}))}$emitPopup(e,...t){return new Promise(((s,n)=>{const r={script:"popup",type:e,message:t};chrome.runtime.sendMessage(r,(e=>{y.isSuccess(e)?s(e.data):n(e.message)}))}))}$emitWindow(e,...t){return this.$emit(e,...t)}$emitAllTabs(e,...t){let s=this;return new Promise(((n,r)=>{s.getTabs((s=>{if(s&&Array.isArray(s)&&s.length>0)for(let r=0;r<s.length;r++){const i=s[r].id||null,o={script:"content",type:e,message:t};chrome.tabs.sendMessage(i,o,(function(e){r===s.length&&n(e)}))}else r("找到激活的tab")}),{windowType:"normal"})}))}}const k=new $;class x extends m{script="content";data={};keys={get:"_message_storage_data_service_get",set:"_message_storage_data_service_set",watch:"_message_storage_data_service_watch",listener:"_message_storage_data_service_listener"};watchKeys=[];$runtimeBus=w;constructor(e){super();let t="content";r()?t="background":i()&&(t="popup"),this.script=e||t,"background"===this.script&&this.listener(),this.listenerWatch()}$on(e,t){return e?"background"===this.script?(c(e)&&this.watchKeys.push(e),this):(this.$runtimeBus.$emitBackground(this.keys.watch,e),super.$on(e,t),this):this}$emit(e,...t){const[s,n]=t;if(e||Promise.reject("错误字段"),"background"===this.script){const t={key:e,oldVal:s,newVal:n};this.$runtimeBus.$emitAllTabs(this.keys.listener,t)}return Promise.resolve("")}listenerWatch(){let e=this;"background"===this.script?this.$runtimeBus.$on(this.keys.watch,((t,s,n)=>(c(t)&&e.watchKeys.push(t),!0))):this.$runtimeBus.$on(this.keys.listener,((t,s,n)=>new Promise(((r,i)=>{e.handler(t,s,n).then((e=>{r(e)})).catch((e=>{i(e||"监听失败")}))}))))}async handler(t,s,n){let r=this;const{key:i,oldVal:o,newVal:c}=t;if(!i)return;let a=r._events.get(i);if(a)if(Array.isArray(a))for(let t=0;t<a.length;++t){let i="";e(a)?a[t].call(r,o,c,s,n).then(n):(i=a[t].call(r,o,c,s,n),i&&n(i))}else{let t="";e(a)?a.call(r,o,c,s,n).then(n):(t=a.call(r,o,c,s,n),t&&n(t))}}listener(){let e=this;this.$runtimeBus.$on(this.keys.get,((t,s,n)=>new Promise(((s,n)=>{e.get(t).then((e=>{s(e)})).catch((e=>{n(e||"获取失败")}))})))),this.$runtimeBus.$on(this.keys.set,((t,s,n)=>new Promise(((s,n)=>{l(t)?e.set(t).then((e=>{s(e)})).catch((e=>{n(e||"设置失败")})):n("设置失败,data不是对象")}))))}get(e){return"background"!==this.script?this.$runtimeBus.$emitBackground(this.keys.get,e):new Promise(((t,s)=>{let n={};c(e)?(n[e]=this.data[e],t(n)):Array.isArray(e)?(e.forEach((e=>{n[e]=this.data[e]})),t(n)):s("error name")}))}set(e,t){if("background"!==this.script){let s={};return l(e)?s=e:s[e]=t,this.$runtimeBus.$emitBackground(this.keys.set,s)}return new Promise(((s,n)=>{let r={};c(e)?(r[e]=t,this.checkWatch(r),this.data[e]=t):l(e)?(r=e,this.checkWatch(r),this.data=Object.assign(this.data,e)):n("name error"),s(!0)}))}async checkWatch(e){let t=Object.keys(e),s=this;this.get(t).then((n=>{for(let r=0;r<t.length;r++){const i=t[r];s.watchKeys.includes(i)&&JSON.stringify(e[i])!=JSON.stringify(n[i])&&s.$runtimeBus.$emitAllTabs(s.keys.listener,{key:i,oldVal:e[i],newVal:n[i]})}})).catch((e=>{Promise.reject(e.message||"未知异常")}))}}class P extends m{script="content";_keys={local:{get:"_message_storage_local_service_get",set:"_message_storage_local_service_set",watch:"_message_storage_local_service_watch",listener:"_message_storage_local_service_listener"},managed:{get:"_message_storage_managed_service_get",set:"_message_storage_managed_service_set",watch:"_message_storage_managed_service_watch",listener:"_message_storage_managed_service_listener"},session:{get:"_message_storage_session_service_get",set:"_message_storage_session_service_set",watch:"_message_storage_session_service_watch",listener:"_message_storage_session_service_listener"},sync:{get:"_message_storage_sync_service_get",set:"_message_storage_sync_service_set",watch:"_message_storage_sync_service_watch",listener:"_message_storage_sync_service_listener"}};keys={};type="local";$runtimeBus=w;chromeVars={local:chrome.storage.local,managed:chrome.storage.managed,session:chrome.storage.session,sync:chrome.storage.sync};watchKeys=[];_events;chromeVar;constructor(e,t){super();let s="content";r()?s="background":i()&&(s="popup"),this._events=new Map,this.type=e||"local",this.type=this._keys[this.type]?this.type:"local",this.keys=this._keys[this.type],this.chromeVar=this.chromeVars[this.type],this.script=t||s,"background"===this.script&&this.listener(),this.listenerWatch()}$on(e,t){return e?"background"===this.script?(c(e)&&this.watchKeys.push(e),this):(this.$runtimeBus.$emitBackground(this.keys.watch,e),super.$on(e,t),this):this}$emit(e,...t){const[s,n]=t;if(e||Promise.reject("错误字段"),"background"===this.script){const t={key:e,oldVal:s,newVal:n};this.$runtimeBus.$emitAllTabs(this.keys.listener,t)}return Promise.resolve("")}listenerWatch(){let e=this;"background"===this.script?this.$runtimeBus.$on(this.keys.watch,((t,s,n)=>(c(t)&&e.watchKeys.push(t),!0))):this.$runtimeBus.$on(this.keys.listener,((t,s,n)=>new Promise(((r,i)=>{e.handler(t,s,n).then((e=>{r(e)})).catch((e=>{i(e||"监听失败")}))}))))}async handler(t,s,n){let r=this;const{key:i,oldVal:o,newVal:c}=t;if(!i)return;let a=r._events.get(i);if(a)if(Array.isArray(a))for(let t=0;t<a.length;++t){let i="";e(a)?a[t].call(r,o,c,s,n).then((e=>{n(y.success(e))})).catch((e=>{n(y.error(e))})):(i=a[t].call(r,o,c,s,n),p(i)?i.then((e=>{n(y.success(e))})).catch((e=>{n(y.error(e))})):n(i?y.success(i):y.error("未知错误")))}else{let t="";e(a)?a.call(r,o,c,s,n).then((e=>{n(y.success(e))})).catch((e=>{n(y.error(e))})):(t=a.call(r,o,c,s,n),p(t)?t.then((e=>{n(y.success(e))})).catch((e=>{n(y.error(e))})):n(t?y.success(t):y.error("未知错误")))}}listener(){let e=this;this.$runtimeBus.$on(this.keys.get,((t,s,n)=>new Promise(((s,n)=>{e.get(t).then((e=>{s(e)})).catch((e=>{n(e||"获取失败")}))})))),this.$runtimeBus.$on(this.keys.set,((t,s,n)=>new Promise(((s,n)=>{l(t)?e.set(t).then((e=>{s(e)})).catch((e=>{n(e||"设置失败")})):n("设置失败,data不是对象")}))))}get(e){return"background"!==this.script?this.$runtimeBus.$emitBackground(this.keys.get,e):new Promise(((t,s)=>{c(e)||h(e)?this.chromeVar.get(e).then((e=>{t(e)})).catch((e=>{s(e.message||"未知异常")})):s("error name")}))}set(e,t){if(e||Promise.reject("错误的字段"),"background"!==this.script){let s={};return l(e)?s=e:s[e]=t,this.$runtimeBus.$emitBackground(this.keys.set,s)}return new Promise((async(s,n)=>{let r={};l(e)?r=e:r[e]=t;this.checkWatch(r),this.chromeVar.set(r).then((()=>{s(!0)})).catch((e=>{n(e.message||"未知异常")}))}))}async checkWatch(e){let t=Object.keys(e),s=this;this.chromeVar.get(t).then((n=>{for(let r=0;r<t.length;r++){const i=t[r];s.watchKeys.includes(i)&&JSON.stringify(e[i])!=JSON.stringify(n[i])&&s.$runtimeBus.$emitAllTabs(s.keys.listener,{key:i,oldVal:e[i],newVal:n[i]})}})).catch((e=>{Promise.reject(e.message||"未知异常")}))}}class E extends P{constructor(){super("managed")}}class S extends P{constructor(){super("session")}}class A extends P{constructor(){super("sync")}}class T{$runtimeBus=w;script="content";keys={onClicked:"_message_action_service_onClicked",enable:"_message_action_service_enable",disable:"_message_action_service_disable"};constructor(e){let t="content";r()?t="background":i()&&(t="popup"),this.script=e||t,"background"===this.script&&this.listener()}listener(){let e=this;chrome.action.onClicked.addListener((t=>{e.$emit()}))}$emit(e){let t=e||this.keys.onClicked;this.$runtimeBus.$emitAllTabs(t,"action!!"+t),this.$runtimeBus.$emitBackground(t,"action!!"+t)}disable(e,t){if("background"===this.script||"popup"===this.script)return this.$emit(this.keys.disable),t&&t(),chrome.action.disable(e);let s=this;return new Promise(((e,n)=>{s.$runtimeBus.$on(this.keys.disable,(s=>{t&&t(),e(s)}))}))}enable(e,t){if("background"===this.script||"popup"===this.script)return this.$emit(this.keys.enable),t&&t(),chrome.action.enable(e);let s=this;return new Promise(((e,n)=>{s.$runtimeBus.$on(this.keys.enable,(s=>{t&&t(),e(s)}))}))}onClicked(e){if("background"===this.script||"popup"===this.script)return new Promise(((t,s)=>{chrome.action.onClicked.addListener((s=>{this.$emit(this.keys.onClicked),e&&e(s),t(s)}))}));let t=this;return new Promise(((s,n)=>{t.$runtimeBus.$on(this.keys.onClicked,(t=>{e&&e(t),s(t)}))}))}}const B=new T;class C{selector="";elements=[];constructor(e){this.selector=e||""}show(e,t={}){if(!(e=e||this.selector))return;if(this.check(e))return;const s=document.querySelectorAll(e);let{background:n,text:r,color:i}=t;s.forEach((t=>{const s="xxxxxxxx-xxxx-8xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}));if(t.querySelector(e))return;let o=t.cloneNode(!1);t.setAttribute("cover-uid",s),o.innerText=r||t.innerText;let c=t.getBoundingClientRect();var a=Math.max(document.documentElement.scrollTop,document.body.scrollTop),l=Math.max(document.documentElement.scrollLeft,document.body.scrollLeft);const h=c.left+l,u=c.top+a,d=c.right,p=c.bottom,m=c.width,g=c.height;o.style.width=m+"px",o.setAttribute("selector",e),o.style.height=g+"px",o.style.top=u+"px",o.style.left=h+"px",o.style.bottom=p+"px",o.style.right=d+"px",o.style.position="absolute",o.setAttribute("cover-id",s),r&&(i=i||"#1e80ff"),o.style.color=i||"rgba(255, 165, 0, 0)",o.style.backgroundColor=n||"rgba(255, 165, 0, 0.3)",o.style.zIndex="99999",document.body.appendChild(o),this.elements.push(o)}))}check(e){for(let t=0;t<this.elements.length;t++){if(this.elements[t].getAttribute("selector")===e)return!0}return!1}hide(e){for(let t=0;t<this.elements.length;t++){let s=this.elements[t];const n=s.getAttribute("selector");e&&e!=n||(document.body.removeChild(s),s.remove())}this.elements=this.elements.filter((t=>{const s=t.getAttribute("selector");if(e&&e!=s)return t}))}}var L=new C;const j=new C;class M extends m{doc;_events;bindFlag;disable;$emitKey;overlay;constructor(e){super(),this._events=new Map,this.bindFlag=!1,this.disable=!1,this.doc=e,this.$emitKey="selector_helper_click"}isValid(){return this.bindFlag&&!this.disable}disabled(){this.disable=!0,this.overlay&&this.overlay.setAttribute("style","")}enabled(){this.disable=!1}setOverlayOffset(e){e&&this.overlay&&this.overlay.setAttribute("style","z-index: 999999;background-color: rgba(255, 165, 0, 0.3);border: 1px solid #c00;position: absolute;pointer-events: none;top: "+(e.top-2)+"px;left:"+(e.left-2)+"px;width: "+(e.width+5)+"px;height: "+(e.height+5)+"px;")}bind(e){if(this.bindFlag)return;this.doc=this.doc||window.document,e||(e=this.doc.createElement("div"),this.doc.body.appendChild(e)),this.overlay=e;let t=this;this.doc.addEventListener("mouseover",(e=>{if(!t.doc)return;if(!t.isValid())return;let s=e.target;if(!s)return;let n=s.getBoundingClientRect();s.offsetLeft,s.offsetTop;let r=s.offsetWidth,i=s.offsetHeight;var o=Math.max(t.doc.documentElement.scrollTop,t.doc.body.scrollTop),c=Math.max(t.doc.documentElement.scrollLeft,t.doc.body.scrollLeft);const a={left:n.left+c,top:n.top+o,right:n.right,bottom:n.bottom,width:r,height:i};t.setOverlayOffset(a)})),this.doc.addEventListener("mousedown",(e=>{t.isValid()&&(e.preventDefault(),e.stopPropagation(),t.$emit(t.$emitKey,e.target),this.disabled())})),this.bindFlag=!0}$setKey(e){this.$emitKey=e}getSelector(e,t=!1,s="A"){this.bind();let n=this;return this.enabled(),e=e||"default_key",t&&j.show(s,{background:"rgba(999,999,99,0)"}),new Promise(((r,i)=>{n.$setKey(e),n.$on(e,(e=>{n.disabled();let i=null;if(t){j.hide(s);let t=e.getAttribute("cover-id")||"";t&&(i=document.querySelector(`[cover-uid='${t}']`))}return r(i||e),!0}))}))}}const O=new M;class N{move;isEnabled;el;constructor(e){this.move=!1,this.isEnabled=!1,this.el=null}disabled(){this.isEnabled=!1}enabled(){this.isEnabled=!0}drag(e){let t,s,n=this;if(this.isEnabled=!0,!(e=e||this.el))return;e.getBoundingClientRect();const r=r=>{!1!==n.isEnabled&&(e.getBoundingClientRect(),t=r.pageX-parseInt(e.offsetLeft.toString()),s=r.pageY-parseInt(e.offsetTop.toString()),n.move=!0)},i=r=>{!1!==n.isEnabled&&n.move&&(e.style.left=r.pageX-t+"px",e.style.top=r.pageY-s+"px")},o=e=>{!1!==n.isEnabled&&(n.move=!1)};n.el&&(n.el.addEventListener("mousedown",r),n.el.addEventListener("mousemove",i),n.el.addEventListener("mouseup",o),n.el=e),e.addEventListener("mousedown",r),e.addEventListener("mousemove",i),e.addEventListener("mouseup",o)}}const V=new N;class I{handlers;constructor(){this.handlers=[]}use(e,t){this.handlers.push({fulfilled:e,rejected:t})}}class R{interceptors;constructor(){this.interceptors={before:new I,after:new I}}request(e,t){const s=[t||(e=>e),void 0];this.interceptors.before.handlers.forEach((e=>{s.unshift(e.fulfilled,e.rejected)})),this.interceptors.after.handlers.forEach((e=>{s.push(e.fulfilled,e.rejected)}));let n=Promise.resolve(e);for(;s.length>0;)n=n.then(s.shift(),s.shift());return n}run(e,t){return this.request(e,t)}}function W(e,t=!1){if(!e||!e.tagName)return"";let s=e.tagName.toLowerCase(),n=e.id,r=e.getAttribute("class")||"",i=[];if(r.trim().split(" ").forEach((e=>{-1==e.indexOf("active")&&""!=e.trim()&&i.push(e)})),n&&!t)return s+"#"+n;if(r)return s+"."+i.join(".");{let n=function(e){let t=1,s=e.previousSibling;do{s&&3!=s.nodeType&&t++,s&&(s=s.previousSibling)}while(s);let n=!1,r=e.parentNode?.childNodes||[],i=0;for(let s=0;s<r.length;s++){let o=r[s];3!=o.nodeType&&i++,o.tagName==e.tagName&&i!=t&&(n=!0)}return n?t:-1}(e),r=K(e,t),i="";return-1==n&&(i=K(e.parentElement,t)),(i?i+">":"")+r+">"+s+(-1==n?"":`:nth-child(${n})`)}}function K(e,t=!1){let s=e;if(!s)return"";let n="";do{s=s.parentNode,s&&(n=W(s,t))}while(!n&&s);return n}const X={ignoreId:!1};function q(e,t){const s={...X,...t};let n=e;if(n&&n.id&&!s.ignoreId)return'//*[@id="'+n.id+'"]';let r=[];for(;n&&(1===n.nodeType||3===n.nodeType);){let e=0,t=!1,i=n.previousSibling;for(;i;)10!==i.nodeType&&i.nodeName===n.nodeName&&e++,i=i.previousSibling;for(i=n.nextSibling;i;){if(i.nodeName===n.nodeName){t=!0;break}i=i.nextSibling}let o=n.prefix?n.prefix+":":"",c=e||t?"["+(e+1)+"]":"",a=3!=n.nodeType?o+n.localName+c:"text()"+(c||"[1]");if(r.push(a),n=n.parentNode,n&&n.id&&!s.ignoreId){r.push('/*[@id="'+n.id+'"]');break}}return r.length?"/"+r.reverse().join("/"):""}function F(e){if(!e)throw new Error("Missing XPath expression");if(!(e=>void 0!==e&&""!==e.replace(/[\s-_=]/g,"")&&e.length===e.replace(/[-_\w:.]+\(\)\s*=|=\s*[-_\w:.]+\(\)|\sor\s|\sand\s|\[(?:[^\/\]]+[\/\[]\/?.+)+\]|starts-with\(|\[.*last\(\)\s*[-\+<>=].+\]|number\(\)|not\(|count\(|text\(|first\(|normalize-space|[^\/]following-sibling|concat\(|descendant::|parent::|self::|child::|/gi,"").length)(e=function(e){return e.replace(/contains\s*\(\s*concat\(["']\s+["']\s*,\s*@class\s*,\s*["']\s+["']\)\s*,\s*["']\s+([a-zA-Z0-9-_]+)\s+["']\)/gi,'@class="$1"')}(e)))throw new Error("Invalid or unsupported XPath: "+e);const t=e.split("|"),s=(()=>{let e="(?P<node>(^id\\([\"\\']?(?P<idvalue>%(value)s)[\"\\']?\\)|(?P<nav>//?(?:following-sibling::)?)(?P<tag>%(tag)s)(\\[((?P<matched>(?P<mattr>@?%(attribute)s=[\"\\'](?P<mvalue>%(value)s))[\"\\']|(?P<contained>contains\\((?P<cattr>@?%(attribute)s,\\s*[\"\\'](?P<cvalue>%(value)s)[\"\\']\\)))\\])?(\\[\\s*(?P<nth>\\d+|last\\(\\s*\\))\\s*\\])?))";const t={tag:"([a-zA-Z][a-zA-Z0-9:-]*|\\*)",attribute:"[.a-zA-Z_:][-\\w:.]*(\\(\\))?)",value:"\\s*[\\w/:][-/\\w\\s,:;.]*"};return Object.keys(t).forEach((s=>{e=e.replace(new RegExp("%\\("+s+"\\)s","gi"),t[s])})),e=e.replace(/\?P<node>|\?P<idvalue>|\?P<nav>|\?P<tag>|\?P<matched>|\?P<mattr>|\?P<mvalue>|\?P<contained>|\?P<cattr>|\?P<cvalue>|\?P<nth>/gi,""),new RegExp(e,"gi")})(),n=[];let r=0;for(;t[r];){const i=[];let o,c=0;for(;o=s.exec(t[r]);){let t;if(!o&&0===c)throw new Error("Invalid or unsupported XPath: "+e);const s={node:o[5],idvalue:o[12]||o[3],nav:o[4],tag:o[5],matched:o[7],mattr:o[10]||o[14],mvalue:o[12]||o[16],contained:o[13],cattr:o[14],cvalue:o[16],nth:o[18]};let n="";0!=c&&s.nav&&(n=~s.nav.indexOf("following-sibling::")?" + ":"//"==s.nav?" ":" > ");const r="*"===s.tag?"":s.tag||"";if(s.contained){if(0!==s.cattr.indexOf("@"))throw new Error("Invalid or unsupported XPath attribute: "+s.cattr);t="["+s.cattr.replace(/^@/,"")+'*="'+s.cvalue+'"]'}else if(s.matched)switch(s.mattr){case"@id":t="#"+s.mvalue.replace(/^\s+|\s+$/,"").replace(/\s/g,"#");break;case"@class":t="."+s.mvalue.replace(/^\s+|\s+$/,"").replace(/\s/g,".");break;case"text()":case".":throw new Error("Invalid or unsupported XPath attribute: "+s.mattr);default:if(0!==s.mattr.indexOf("@"))throw new Error("Invalid or unsupported XPath attribute: "+s.mattr);-1!==s.mvalue.indexOf(" ")&&(s.mvalue='"'+s.mvalue.replace(/^\s+|\s+$/,"")+'"'),t="["+s.mattr.replace("@","")+'="'+s.mvalue+'"]'}else t=s.idvalue?"#"+s.idvalue.replace(/\s/,"#"):"";let a="";if(s.nth)if(-1===s.nth.indexOf("last")){if(isNaN(parseInt(s.nth,10)))throw new Error("Invalid or unsupported XPath attribute: "+s.nth);a=1!==parseInt(s.nth,10)?":nth-of-type("+s.nth+")":":first-of-type"}else a=":last-of-type";i.push(n+r+t+a),c++}const a=i.join("");if(""===a)throw new Error("Invalid or unsupported XPath");n.push(a),r++}return n.join(", ")}var z={injectCss:function(e,t){if(window.self===window.top){if(e){const t=document.createElement("link");return t.rel="stylesheet",t.href=chrome.runtime.getURL(e),document.documentElement.appendChild(t),t}if(t){const e=document.createElement("style");return e.textContent=t,document.documentElement.appendChild(e),e}}},injectScript:function(e,t){if(window.self===window.top){const s=document.createElement("script");if(s.type="text/javascript",e&&(s.src=chrome.runtime.getURL(e)),t)try{s.appendChild(document.createTextNode(t))}catch(e){s.text=t}return document.head.appendChild(s),s.addEventListener("load",(()=>{console.log("load script-----")})),s}},injectedScript:function(e){if(window.self===window.top){const t=document.createElement("script");return t.src=chrome.runtime.getURL(e),document.documentElement.appendChild(t),t}}};const D=new class extends m{listener(){let e=this;window.addEventListener("message",(function(t){const{origin:s="*",data:n={}}=t,{key:r="",act:i="getList",params:o={}}=n;"_ajaxProxyInstance_receive_"==r&&e.$emitSuper(i,o)}))}async $emitSuper(e,...t){return super.$emit(e,...t)}async $emit(e,...t){return parent.postMessage({key:"_ajaxProxyInstance_listener_",act:e,params:t},"*"),!0}async $emitGetList(...e){this.$emit("getList",...e)}async $emitOnRequest(...e){this.$emit("onRequest",...e)}async $emitOnResponse(...e){this.$emit("onResponse",...e)}getList(e){this.$on("getList",e)}onRequest(e){this.$on("onRequest",e)}onResponse(e){this.$on("onResponse",e)}},J={data:new x,local:new class extends P{constructor(){super("local")}},managed:new E,session:new S,sync:new A};class U{constructor(){}init(){}initTest(){w.$on("background",((e,t,s)=>(console.log("background on message---",e),"background收到runtimeBus"+e))),w.$on("testSend",((e,t,s)=>(console.log("testSend background on message---",e),"background收到runtimeBus"+e))),_.$on("background",((e,t,s)=>(console.log("background on port message---",e),"background收到portBus")))}}var Z={$window:k,$runtime:w,$port:_,$demo:g,$action:B,$drag:V,$storage:J,$css:O,$cover:L,$inject:D,inject:z,CssSelectorService:M,DomDragService:N,SelectorCoverService:C,InterceptorRunner:R,WorkService:U,RuntimeEventBus:b,PortEventBus:v,EventBusDemo:m,WindowEventBus:$,StorageDataService:x,StorageManagedService:E,StorageSessionService:S,StorageSyncService:A,ActionService:T,isDefined:s,isExtension:n,isBackgroundScript:r,isContentScript:o,isPopupScript:i,isString:c,isObject:l,isArray:h,isObjectOrArray:a,isNodeEnvironment:u,getEnv:d,isFunction:t,isFunctionAsync:e,ResponseUtils:y,isPromise:p,getXPath:q,getSelector:W,xPathToCss:F};export{B as $action,L as $cover,O as $css,g as $demo,V as $drag,D as $inject,_ as $port,w as $runtime,J as $storage,k as $window,T as ActionService,M as CssSelectorService,N as DomDragService,m as EventBusDemo,R as InterceptorRunner,v as PortEventBus,y as ResponseUtils,b as RuntimeEventBus,C as SelectorCoverService,x as StorageDataService,E as StorageManagedService,S as StorageSessionService,A as StorageSyncService,$ as WindowEventBus,U as WorkService,Z as default,d as getEnv,W as getSelector,q as getXPath,z as inject,h as isArray,r as isBackgroundScript,o as isContentScript,s as isDefined,n as isExtension,t as isFunction,e as isFunctionAsync,u as isNodeEnvironment,l as isObject,a as isObjectOrArray,i as isPopupScript,p as isPromise,c as isString,F as xPathToCss};