Files
kit/assets/core/core.min.js
T
2024-11-16 21:12:09 +03:00

1 line
14 KiB
JavaScript

var kit,kit=window.kit=window.kit||{};kit.service=kit.service||{},kit.config=kit.config||{},!function(global){var defaultConfig={version:"2.0",assetsPath:"",requiredDependencies:[],autoloadPluginList:[],debug:!0},stateList={undefined:0,registered:1,loading:3,loaded:4,installing:5,installed:6},MD_TYPE={ES:"ES",UMD:"UMD",HMD:"HMD",default:"default"};function Plugin(e,t={}){this.id=e,this.state=stateList.undefined,this.state2=stateList.undefined,this.module={code:"",exports:{}},this.config={autoRequire:!1,loadJsAfterModule:!1,isSetTimestamp:!0,path:"",module:"",type:"default",handler:void 0,onRegister:function(e){},onLoad:function(e){},onInstall:function(e){},js:[],css:[],alias:[],deps:[],debug:!1},this.pluginManager=void 0,this.promise=new Promise(function(e,t){e()}),this.errors=[],this.register(t)}function isAssetLoaded(e){return e=e.match(/^[^#?]*/)[0],document.querySelector('script[src^="'+e+'"]')||document.querySelector('link[href^="'+e+'"]')||document.querySelector('meta[property="kit:file-load"][content="'+e+'"]')}function getUrlWithTimestamp(t){var i=3600*((new Date).getTime()/1e3/3600>>0);try{var e=new URL(t);e.searchParams.append("__pm",String(i)),t=e.toString()}catch(e){t=(t=String(t).split("?")[0])+"?__pm"+i}return t}Plugin.prototype.setPluginManager=function(e){this.pluginManager=e},Plugin.prototype.queuePush=function(i,n=[]){"function"==typeof i&&(this.promise=this.promise.then(function(e){var t=i.apply(this,n);if(t)return t}))},Plugin.prototype.__queue=function(e,i,n=[],o=void 0){var t=this;void 0===o&&(o=t),t.__checkState(e)?i.apply(o,n):t.promise=t.promise.then(function(){return new Promise(function(e,t){i.apply(o,n),e()})}.bind(t))},Plugin.prototype.__exec=function(e,t,i=[],n=void 0){var o=this;void 0===n&&(n=o),o.__checkState(e)?t.apply(n,i):o.promise=o.promise.then(function(){t.apply(n,i)}.bind(o))},Plugin.prototype.__checkState=function(e,t=void 0){return void 0===t?this.state>=e:this.state>=e&&this.state<=t},Plugin.prototype.__check2State=function(e,t=void 0){return void 0===t?this.state2>=e:this.state2>=e&&this.state2<=t},Plugin.prototype.__getValidConfig=function(e={}){e=Object.assign({},e);return"function"!=typeof e.onLoad&&(e.onLoad=function(e){}),"function"!=typeof e.onInstall&&(e.onInstall=function(e){}),"function"!=typeof e.onRegister&&(e.onRegister=function(e){}),"string"!=typeof e.path&&(e.path=""),"string"==typeof e.js?e.js=[e.js]:Array.isArray(e.js)||(e.js=[]),"string"==typeof e.css?e.css=[e.css]:Array.isArray(e.css)||(e.css=[]),"string"==typeof e.alias?e.alias=[e.alias]:Array.isArray(e.alias)||(e.alias=[]),e.autoRequire=!!e.hasOwnProperty("autoRequire")&&!!e.autoRequire,e.loadJsAfterModule=!!e.hasOwnProperty("loadJsAfterModule")&&!!e.loadJsAfterModule,e.isSetTimestamp=!e.hasOwnProperty("isSetTimestamp")||!!e.isSetTimestamp,e.type=e.type||"default","string"==typeof e.deps?e.deps=[e.deps]:Array.isArray(e.deps)||(e.deps=[]),e},Plugin.prototype.__setState=function(e,t=!1){var i=this;(t||i.__checkState(e))&&(i.state=e)},Plugin.prototype.register=function(e={}){var t,i=this,n=i.id;if(this.__checkState(stateList.installed))throw new Error("Plugin "+n+" уже невозможно конфигурировать ("+i.state+"/"+i.state2+")");if("function"==typeof e)t=e,(e=this.config).handler=t,e.type=MD_TYPE.HMD;else{if(this.__checkState(stateList.loaded)||this.__check2State(stateList.loading))throw new Error("Plugin "+n+" уже невозможно конфигурировать ("+i.state+")");if("object"!=typeof e)throw new Error("Plugin.register: plugin "+n+" is not a valid format");e=this.__getValidConfig(e),Object.assign(this.config,e)}this.__checkState(stateList.registered)||(i.config.debug&&console.log(`Plugin ${i.id}: onRegister + event.`),this.state=stateList.registered,this.config.onRegister(this),t=new CustomEvent("onRegister"+this.id+"Plugin",{detail:{plugin:this}}),document.dispatchEvent(t)),e.autoRequire},Plugin.prototype.load=function(e){var n,t,i,o,s,r=this,l=("function"!=typeof e&&(e=function(){}),r.id);return r.__checkState(stateList.registered)?r.__checkState(stateList.loaded)?e():r.__check2State(stateList.loading)?r.__exec(stateList.loaded,e):(r.state2=stateList.loading,(n=r.config).css.forEach(function(e,t,i){r.getStylePromise(n.path+e)}),r.pluginManager&&(t=r.pluginManager.__getDepsPromiseCallback(r.config.deps),r.queuePush(t)),o=n.path+n.module,i="string"==typeof n.module&&""!==n.module&&"ES"===n.type?function(){return r.getESModulePromise(o).then(function(e){e.__esModule=!0,r.module.exports=e}.bind(r))}:"string"==typeof n.module&&""!==n.module&&"UMD"===n.type?isAssetLoaded(o)?void(r.config.debug&&console.warn(`Plugin ${r.id}: Скрипт ${o} уже загружен!`)):function(){return r.httpGet(o).then(function(e){r.module.code=e}.bind(r))}:"HMD"!==n.type||n.hasOwnProperty("handler")&&"function"==typeof n.handler?"string"==typeof n.module&&""!==n.module&&"default"===n.type?isAssetLoaded(o)?void(r.config.debug&&console.warn(`Plugin ${r.id}: Скрипт ${o} уже загружен!`)):function(){return r.getScriptPromise(o)}:void 0:function(){return r.getScriptPromise(o)},s=r.getJsAssetsPromiseCallback(n.js),n.loadJsAfterModule?(r.queuePush(i),r.queuePush(s)):(r.queuePush(s),r.queuePush(i)),t||i||s||(r.state=stateList.loaded),r.__queue(stateList.loaded,function(){r.config.debug&&console.log(`Plugin ${r.id}: onLoad + event.`),r.isLoaded()||(r.state=stateList.loaded),n.onLoad.call(r,r);var e=new CustomEvent("onLoad"+r.id+"Plugin",{detail:{plugin:r}});document.dispatchEvent(e)}),r.__exec(stateList.loaded,function(){e()}.bind(r))):console.warn(`Plugin.load(${l}): is not register!.`),r},Plugin.prototype.install=function(callback){var self=this,global=self.pluginManager.global,require=self.pluginManager.require.bind(self.pluginManager),pluginId=("function"!=typeof callback&&(callback=function(){}),self.id),setGlobals,module,installer;return self.__checkState(stateList.registered)?self.__checkState(stateList.installed)?callback():self.__check2State(stateList.installing)?self.__exec(stateList.installed,callback):(self.__checkState(stateList.loaded)||this.load(),self.state2=stateList.installing,setGlobals=function(t,i){var e,n;void 0!==i&&(e=self.id,n=self.config.alias,t.hasOwnProperty(e)||(t[e]=i),Array.isArray(n))&&n.length&&n.forEach(function(e){t.hasOwnProperty(e)||(t[e]=i)})},module=self.module,installer=function(){var __exports=void 0,event=("ES"===self.config.type&&"string"==typeof self.config.module&&""!==self.config.module?__exports="object"==typeof self.module.exports&&void 0!==self.module.exports.default?self.module.exports.default:self.module.exports:"UMD"===self.config.type&&"string"==typeof self.config.module&&""!==self.config.module?(function(require,exports,module,global){var self=global;eval(module.code)}.bind(global).call(global,require,self.module.exports,module,global),__exports="object"==typeof self.module.exports&&void 0!==self.module.exports.default?self.module.exports.default:self.module.exports):"HMD"===self.config.type&&"function"==typeof self.config.handler&&(__exports=self.config.handler.bind(global).call(global,require,self.module.exports,module,global),void 0===__exports)&&self.module.exports&&(__exports=self.module.exports),"object"==typeof global&&setGlobals(global,__exports),self.state=stateList.installed,console.log(`%cPlugin ${pluginId}: installed.`,"color: green;"),self.config.onInstall.call(self,self),new CustomEvent("onInstall"+self.id+"Plugin",{detail:{plugin:self}}));return document.dispatchEvent(event),!0}.bind(this),this.__queue(stateList.loaded,installer),this.__exec(stateList.loaded,function(){callback()})):console.warn(`Plugin ${pluginId}: is not register!`),self},Plugin.prototype.exec=function(e,t=[],i=void 0){var n=this;void 0===i&&(i=n),n.__checkState(stateList.installed)||(n.load(),n.install()),n.__exec(stateList.installed,e,t,i)},Plugin.prototype.getESModulePromise=function(e){var n=this;return new Promise(function(t,i){import(e).then(function(e){t(e)},function(e){n.errors.push(e),console.log(`%cPlugin ${n.id}: error import module!`,"color: red;"),i(e)})})},Plugin.prototype.httpGet=function(o){var s=this;return new Promise(function(t,i){s.config.debug&&console.log(`Plugin ${s.id}: httpGet `+o);var e=new XMLHttpRequest,n=o;s.config.isSetTimestamp&&(n=getUrlWithTimestamp(o)),e.open("GET",n,!0),e.onload=function(){var e;200==this.status?t(this.response):(console.log(`%cPlugin.load(${s.id}): error load file!`,"color: red;"),(e=new Error(this.statusText)).code=this.status,i(e))},e.onerror=function(){console.log(`%cPlugin.load(${s.id}): error load file!`,"color: red;"),i(new Error("Network Error"))},e.send()})},Plugin.prototype.getScriptPromise=function(n){var o=this;if(!isAssetLoaded(n))return new Promise(function(e,t){o.config.debug&&console.log(`Plugin ${o.id}: load script `+n);var i=document.createElement("script");i.src=n,o.config.isSetTimestamp&&(i.src=getUrlWithTimestamp(n)),i.onload=function(){e(i)},i.onerror=function(){var e=new Error("Ошибка загрузки скрипта "+n);o.errors.push(e),console.log(`%cPlugin.load(${o.id}): error load script ${n}!`,"color: red;"),t(e)},document.head.append(i)});o.config.debug&&console.warn(`Plugin ${o.id}: Скрипт ${n} уже загружен!`)},Plugin.prototype.getStylePromise=function(n){var o=this;return new Promise(function(e,t){var i;isAssetLoaded(n)?(o.config.debug&&console.warn(`Plugin ${o.id}: Стиль ${n} уже загружен`),e()):((i=document.createElement("link")).rel="stylesheet",i.type="text/css",i.media="all",i.href=n,o.config.isSetTimestamp&&(i.href=getUrlWithTimestamp(n)),document.head.append(i),e(i))})},Plugin.prototype.getAsyncScriptListPromise=function(e){e=e.map(this.getScriptPromise.bind(this)).filter(e=>void 0!==e);if(e.length)return Promise.all(e)},Plugin.prototype.getJsAssetsPromiseCallback=function(e=[]){var o=this;if(e.length)return function(){var n=new Promise(function(e,t){e()});return e.forEach(function(e,t,i){n=Array.isArray(e)?n.then(function(){return o.getAsyncScriptListPromise(e.map(e=>o.config.path+e))}):n.then(function(){return o.getScriptPromise(o.config.path+e)})}),n}},Plugin.prototype.__getRealId=function(e){var t,i=e.toLowerCase();if(this.id.toLowerCase()===i)return this.id;for(t of this.config.alias)if(i===t.toLowerCase())return this.id},Plugin.prototype.__is=function(e){return this.id===this.__getRealId(e)},Plugin.prototype.isLoaded=function(){return this.__checkState(stateList.loaded)},Plugin.prototype.isInstalled=function(){return this.__checkState(stateList.installed)},Plugin.prototype.require=function(){return this.isInstalled()||this.config.debug&&console.warn(`Plugin ${this.id}: not instaled!`),this.module.exports};var PluginManager=function(e){this.plugins={},this.global=e},__proto=PluginManager.prototype;function init(e){var o=new PluginManager(e);e.ready=o.ready.bind(o),e.loaded=o.loaded.bind(o),e.exec=o.exec.bind(o),e.require=o.require.bind(o),o.register("pluginManager",{alias:"pm",type:MD_TYPE.HMD,handler:function(e,t,i,n){return n.PluginManagerClass=PluginManager,"object"==typeof window&&(window.__PluginManager__=o,window.__pmGlobal__=n),i.exports=o},onInstall:function(e){}}),o.install("pluginManager"),o.register("config",{type:MD_TYPE.HMD,handler:function(e,t,i,n){var o=document.currentScript;if(o)try{var s=new URL(o.src);defaultConfig.assetsPath=s.pathname.split("/").slice(0,-2).join("/")}catch(e){s=o.src.split("?")[0];defaultConfig.assetsPath=s.split("/").slice(0,-2).join("/")}o=n.config||{};n.config=Object.assign({},defaultConfig,o),"object"==typeof window&&(window.__pmConfig__=n.config),document.addEventListener("DOMContentLoaded",function(){console.log("%cDOMContentLoaded","color:#2053ff")}),window.addEventListener("load",e=>{console.log("%cWindowLoaded","color:#2053ff")})},onInstall:function(e){"object"==typeof window&&window.hasOwnProperty("__PluginManagerConfigHandler__")&&"function"==typeof __PluginManagerConfigHandler__&&o.registerPlugins(__PluginManagerConfigHandler__())}}),o.install("config")}PluginManager.prototype.registerPlugins=function(e){for(var t in e)e.hasOwnProperty(t)&&this.register(t,e[t]);return this},PluginManager.prototype.register=function(e,t={}){var i;"string"!=typeof e||""===e?console.warn("Invalid pluginId!",e):(i=this.__getPlugin(e))?i.register(t):((i=new Plugin(e,t)).setPluginManager(this),this.plugins[e]=i)},PluginManager.prototype.__getPlugin=function(e){var t,i;for(t in this.plugins)if(this.plugins.hasOwnProperty(t)&&(i=this.plugins[t]).__is(e))return i},PluginManager.prototype.__getDepsPromiseCallback=function(e=[]){var i=this,t=e.map(function(e){var t=i.__getPlugin(e);if(t)return t.install(),t.isInstalled()?void 0:t.promise;console.log(`%cPluginManager: plugin ${e} not found!`,"color: red;")}).filter(e=>void 0!==e);if(t.length)return function(){return Promise.all(t)}},PluginManager.prototype.__getRealIdList=function(e=[]){var t=this;return e.map(function(e){e=t.__getPlugin(e);if(e)return e.id})},PluginManager.prototype.exec=function(e,t,i=[],n=void 0){"function"==typeof e&&(n=i,i=t,t=e,e=[]),"string"==typeof e&&(e=[e]),void 0===n&&(n=this),void 0===i&&(i=[]),"function"==typeof t&&(global.config&&global.config.requiredDependencies&&(e=Array.from(new Set(e.concat(global.config.requiredDependencies)))),(e=this.__getDepsPromiseCallback(e))?e().then(function(){t.apply(n,i)}):t.apply(n,i))},__proto.exec2=function(e,t){var i=this,n=this,o=i.__getDepsPromiseCallback(e),s=function(){var t=[];return e.forEach(function(e){i.__getPlugin(e)?t.push(i.require(e)):t.push(void 0)}.bind(i)),t}.bind(i);o?o().then(function(){t.apply(n,s())}):t.apply(n,s())},__proto.ready=function(e,t=void 0){"function"==typeof e&&(t=e,e=[]),this.__ready(this.exec,[e,t="function"!=typeof t?function(){}:t],this)},__proto.__ready=function(e,t=[],i=window){i=i||this,/complete|interactive|loaded/.test(document.readyState)?e.apply(i,t):document.addEventListener("DOMContentLoaded",function(){e.apply(i,t)}.bind(this))},__proto.loaded=function(e,t=void 0){"function"==typeof e&&(t=e,e=[]),this.__loaded(this.exec,[e,t="function"!=typeof t?function(){}:t],this)},__proto.__loaded=function(e,t=[],i=window){i=i||this,/complete|interactive|loaded/.test(document.readyState)?e.apply(i,t):window.addEventListener("load",function(){e.apply(i,t)}.bind(this))},__proto.require=function(e,t){var i,n=this.__getPlugin(e);if(n)return e=n.id,i=n.module,n.install(t="function"!=typeof t?function(){}:t),i.exports;console.warn("PluginManager.require: plugin "+e+" not found!")},__proto.install=function(e,t){var i=this.__getPlugin(e);i?(e=i.id,i.module,i.install(t)):console.warn("PluginManager.install: plugin "+e+" not found!")},init(global)}(kit);