-
Notifications
You must be signed in to change notification settings - Fork 4
/
ccm.min.js
2 lines (2 loc) · 40.7 KB
/
ccm.min.js
1
2
(()=>{const _components={};const Datastore=function(){const callbacks=[];let that;let user;this.init=async()=>{that=this;await prepareDB();await prepareRealtime();delete that.init;async function prepareDB(){if(!that.name||that.url)return;await openDB();await createStore();function openDB(){return new Promise(((resolve,reject)=>{if(db)return resolve();const idb=indexedDB.open("ccm");idb.onsuccess=function(){db=this.result;resolve()};idb.onerror=reject}))}function createStore(){return new Promise(((resolve,reject)=>{if(db.objectStoreNames.contains(that.name))return resolve();let version=parseInt(localStorage.getItem("ccm"));if(!version)version=1;db.close();const request=indexedDB.open("ccm",version+1);request.onupgradeneeded=function(){db=this.result;localStorage.setItem("ccm",db.version);db.createObjectStore(that.name,{keyPath:"key"})};request.onsuccess=resolve;request.onerror=reject}))}}};this.clear=()=>that.local={};this.source=()=>({name:that.name,url:that.url,db:that.db});this.get=(key_or_query={})=>new Promise(((resolve,reject)=>{key_or_query=ccm.helper.clone(key_or_query);if(!ccm.helper.isObject(key_or_query)&&!ccm.helper.isKey(key_or_query))return reject(new Error("invalid dataset key: "+key_or_query));that.url?serverDB():that.name?clientDB():localCache();function localCache(){resolve(ccm.helper.clone(ccm.helper.isObject(key_or_query)?runQuery(key_or_query):that.local[key_or_query]));function runQuery(query){const results=[];for(const key in that.local)ccm.helper.isSubset(query,that.local[key])&&results.push(that.local[key]);return results}}function clientDB(){const store=getStore();const request=ccm.helper.isObject(key_or_query)?store.getAll():store.get(key_or_query);request.onsuccess=event=>resolve(event.target.result||null);request.onerror=event=>reject(event.target.errorCode)}function serverDB(){(that.socket?useWebsocket:useHttp)(prepareParams({get:key_or_query})).then(resolve).catch((error=>checkError(error,reject)))}}));this.set=priodata=>new Promise(((resolve,reject)=>{priodata=ccm.helper.toJSON(priodata);if(!priodata.key)priodata.key=ccm.helper.generateKey();if(!ccm.helper.isKey(priodata.key)&&!ccm.helper.isObject(priodata.key))return reject(new Error("invalid dataset key: "+priodata.key));that.url?serverDB():that.name?clientDB():localCache();async function localCache(){if(that.local[priodata.key])that.local[priodata.key]=await ccm.helper.integrate(priodata,that.local[priodata.key]);else that.local[priodata.key]=priodata;resolve(priodata)}function clientDB(){const request=getStore().put(priodata);request.onsuccess=event=>resolve(event.target.result);request.onerror=event=>reject(event.target.errorCode)}function serverDB(){(that.socket?useWebsocket:useHttp)(prepareParams({set:priodata})).then(resolve).catch((error=>checkError(error,reject)))}}));this.del=key=>new Promise(((resolve,reject)=>{if(!ccm.helper.isKey(key))return reject(new Error("invalid dataset key: "+key));that.url?serverDB():that.name?clientDB():localCache();function localCache(){const dataset=that.local[key];delete that.local[key];resolve(dataset)}function clientDB(){const request=getStore().delete(key);request.onsuccess=event=>resolve(event.target.result);request.onerror=event=>reject(event.target.errorCode)}function serverDB(){(that.socket?useWebsocket:useHttp)(prepareParams({del:key})).then(resolve).catch((error=>checkError(error,reject)))}}));this.count=query=>new Promise(((resolve,reject)=>{that.url?serverDB():that.name?clientDB():localCache();function localCache(){resolve(query?that.get(query).then((datasets=>datasets.length)):Object.keys(that.local).length)}function clientDB(){const request=getStore().count();request.onsuccess=event=>(!isNaN(event.target.result)?resolve:reject)(event.target.result);request.onerror=event=>reject(event.target.errorCode)}function serverDB(){(that.socket?useWebsocket:useHttp)(prepareParams(query?{count:query}:{})).then((response=>!isNaN(response)?resolve(parseInt(response)):reject(response))).catch((error=>checkError(error,reject)))}}));function getStore(){return db.transaction([that.name],"readwrite").objectStore(that.name)}function prepareParams(params={}){if(that.db)params.db=that.db;params.store=that.name;if(that.realm===null)return params;user=ccm.context.find(that,"user");if(that.token&&that.realm){params.realm=that.realm;params.token=that.token}else if(user&&user.isLoggedIn()){params.realm=user.getRealm();params.token=(user.getValue?user.getValue():user.data()).token}return params}async function checkError(error,reject){if(error&&(error===401||error===403||error.data&&(error.data.status===401||error.data.status===403))&&user){try{await user.logout();await user.login();await ccm.context.root(user).start()}catch(e){await ccm.context.root(user).start()}}else reject(error)}function prepareRealtime(){return new Promise((resolve=>{if(!that.url||that.url.indexOf("ws")!==0)return resolve();if(!that.onchange&&that.parent)that.onchange=that.parent.start;let message=[that.db,that.name];if(that.dataset){that.observe=that.dataset;delete that.dataset}if(that.observe){if(!Array.isArray(that.observe))that.observe=[that.observe];that.observe=that.observe.map((key_or_query=>ccm.helper.isObject(key_or_query)?JSON.stringify(key_or_query):key_or_query));message=message.concat(that.observe)}that.socket=new WebSocket(that.url,"ccm-cloud");that.socket.onmessage=message=>{const{callback:callback,data:data}=ccm.helper.parse(message.data);if(callback){callbacks[callback](data);delete callbacks[callback]}else that.onchange&&that.onchange(data)};that.socket.onopen=()=>{that.socket.send(message);resolve()}}))}function useWebsocket(params){return new Promise(((resolve,reject)=>{const key=ccm.helper.generateKey();callbacks[key]=result=>Number.isInteger(result)?checkError(result,reject):resolve(result);params.callback=key;try{if(that.socket.readyState>1)prepareRealtime().then((()=>that.socket.send(ccm.helper.stringify(params))));else that.socket.send(ccm.helper.stringify(params))}catch(e){prepareRealtime().then((()=>that.socket.send(ccm.helper.stringify(params))))}}))}function useHttp(params){return ccm.load({url:that.url,params:params,method:that.method})}};let db;if(!window.ccm)window.ccm={callbacks:{},files:{}};const ccm={version:()=>"27.5.0",load:function(){const args=[...arguments];const call=args.slice(0);call.unshift(ccm.load);let results=[];let counter=1;let failed=false;return new Promise(((resolve,reject)=>{args.forEach(((resource,i)=>{counter++;resource=ccm.helper.clone(resource);if(Array.isArray(resource)){results[i]=[];serial(null);return}if(!ccm.helper.isObject(resource))resource={url:resource};const suffix=resource.url.split(".").pop().split("?").shift().split("#").shift().toLowerCase();if(resource.method)resource.method=resource.method.toLowerCase();if(!resource.context||resource.context==="head")resource.context=document.head;if(ccm.helper.isInstance(resource.context))resource.context=resource.context.element.parentNode;const operation=getOperation();let timeout;ccm.timeout&&window.setTimeout((()=>timeout===undefined&&(timeout=true)&&error("timeout")),ccm.timeout);operation();function serial(result){if(result!==null)results[i].push(result);if(resource.length===0)return check();let next=resource.shift();if(!Array.isArray(next))next=[next];ccm.load.apply(null,next).then(serial).catch(serial)}function getOperation(){switch(resource.type){case"html":return loadHTML;case"css":return loadCSS;case"image":return loadImage;case"js":return loadJS;case"module":return loadModule;case"json":return loadJSON;case"xml":return loadXML}switch(suffix){case"html":return loadHTML;case"css":return loadCSS;case"jpg":case"jpeg":case"gif":case"png":case"svg":case"bmp":return loadImage;case"js":return loadJS;case"mjs":return loadModule;case"xml":return loadXML;default:return loadJSON}}function loadHTML(){resource.type="html";resource.method="get";loadJSON()}function loadCSS(){if(resource.context.querySelector('link[rel="stylesheet"][type="text/css"][href="'+resource.url+'"]'))return success();let element={tag:"link",rel:"stylesheet",type:"text/css",href:resource.url};if(resource.attr)element=Object.assign(element,resource.attr);element=ccm.helper.html(element);element.onload=success;element.onerror=event=>{element.parentNode.removeChild(element);error(element,event)};resource.context.appendChild(element)}function loadImage(){const image=new Image;image.onload=success;image.onerror=event=>error(image,event);image.src=resource.url}function loadJS(){const filename=resource.url.split("/").pop().split("?").shift().replace(".min.",".");window.ccm.files[filename]=null;window.ccm.files["#"+filename]=window.ccm.files["#"+filename]?window.ccm.files["#"+filename]+1:1;let element={tag:"script",src:resource.url,async:true};if(resource.attr)element=Object.assign(element,resource.attr);element=ccm.helper.html(element);element.onload=()=>{const data=window.ccm.files[filename];if(!--window.ccm.files["#"+filename]){delete window.ccm.files[filename];delete window.ccm.files["#"+filename]}element.parentNode.removeChild(element);data!==null?successData(data):success()};element.onerror=event=>{element.parentNode.removeChild(element);error(element,event)};resource.context.appendChild(element)}function loadModule(){let[url,...keys]=resource.url.split("#");if(url.startsWith("./"))url=url.replace("./",location.href.substring(0,location.href.lastIndexOf("/")+1));import(url).then((result=>{if(keys.length===1)result=result[keys[0]];if(keys.length>1){const obj={};keys.forEach((key=>obj[key]=result[key]));result=obj}successData(result)}))}function loadJSON(){switch(resource.method){case"jsonp":jsonp();break;case"get":case"post":case"put":case"delete":ajax();break;case"fetch":fetchAPI();break;default:resource.method="post";ajax()}function jsonp(){const callback="callback"+ccm.helper.generateKey();if(!resource.params)resource.params={};resource.params.callback="window.ccm.callbacks."+callback;window.ccm.callbacks[callback]=data=>{element.parentNode.removeChild(element);delete window.ccm.callbacks[callback];successData(data)};let element={tag:"script",src:buildURL(resource.url,resource.params)};if(resource.attr)element=Object.assign(element,resource.attr);element=ccm.helper.html(element);element.onerror=event=>{element.parentNode.removeChild(element);error(element,event)};element.src=element.src.replace(/&/g,"&");resource.context.appendChild(element)}function ajax(){const request=new XMLHttpRequest;request.open(resource.method,resource.method==="get"&&resource.params?buildURL(resource.url,resource.params):resource.url,true);if(resource.headers)for(const key in resource.headers){request.setRequestHeader(key,resource.headers[key]);if(key.toLowerCase()==="authorization")request.withCredentials=true}(resource.method==="post"||resource.method==="put")&&request.setRequestHeader("Content-Type","application/json");request.onreadystatechange=()=>{if(request.readyState===4)request.status>=200&&request.status<300?successData(request.responseText):error(request)};request.send(resource.method==="post"||resource.method==="put"?ccm.helper.stringify(resource.params):undefined)}function fetchAPI(){if(!resource.init)resource.init={};if(resource.params)resource.init.method.toLowerCase()==="post"?resource.init.body=ccm.helper.stringify(resource.params):resource.url=buildURL(resource.url,resource.params);fetch(resource.url,resource.init).then((response=>response.text())).then(successData).catch(error)}function buildURL(url,data){if(ccm.helper.isObject(data.json))data.json=ccm.helper.stringify(data.json);return data?url+"?"+params(data).slice(0,-1):url;function params(obj,prefix){let result="";for(const i in obj){const key=prefix?prefix+"["+encodeURIComponent(i)+"]":encodeURIComponent(i);if(typeof obj[i]==="object")result+=params(obj[i],key);else result+=key+"="+encodeURIComponent(obj[i])+"&"}return result}}}function loadXML(){if(!resource.method)resource.method="post";const request=new XMLHttpRequest;request.overrideMimeType("text/xml");request.onreadystatechange=()=>{if(request.readyState===4)request.status===200?successData(request.responseXML):error(request)};request.open(resource.method,resource.url,true);request.send()}function successData(data){if(checkTimeout())return;try{if(typeof data!=="object")data=ccm.helper.parse(data)}catch(e){}if(resource.type==="html"){const regex=/<ccm-template key="(\w*?)">([^]*?)<\/ccm-template>/g;const result={};let array;while(array=regex.exec(data))result[array[1]]=array[2];if(Object.keys(result).length)data=result}results[i]=data;success()}function success(){if(checkTimeout())return;if(results[i]===undefined)results[i]=resource.url;check()}function checkTimeout(){return timeout?ccm.helper.log("loading of "+resource.url+" succeeded after timeout ("+ccm.timeout+"ms)")||true:timeout=false}function error(){failed=true;results[i]={error:new Error("loading of "+resource.url+" failed"),resource:resource,data:[...arguments],call:call};if(results[i].data.length<=1)results[i].data=results[i].data[0];check()}}));check();function check(){if(--counter)return;if(results.length===1)results=results[0];(failed?reject:resolve)(results)}}))},component:async(component,config)=>{component=await getComponentObject();if(!ccm.helper.isComponent(component))throw new Error("invalid component object");await changeVersion(component,config);const version=(ccm.helper.isCore(component.ccm)?component.ccm:await ccm.helper.loadVersion(component.ccm)).version();if(version!==ccm.version())return new Promise((async resolve=>{const result=await window.ccm[version].component(component,config,resolve);result&&resolve(result)}));component.index=component.name+(component.version?"-"+component.version.join("-"):"");if(!_components[component.index]){_components[component.index]=component;ccm.components[component.index]={};component.instances=0;component.ccm=window.ccm[version];component.ready&&await component.ready.call(component);delete component.ready;await defineCustomElement(component.index)}else component=_components[component.index];component=ccm.helper.clone(component);component.config=await prepareConfig(config,component.config);component.instance=async config=>await ccm.instance(component,await prepareConfig(config,component.config));component.start=async config=>await ccm.start(component,await prepareConfig(config,component.config));return component;async function getComponentObject(){if(typeof component==="string"){const index=component.endsWith(".js")?ccm.helper.convertComponentURL(component).index:component;if(_components[index])return ccm.helper.clone(_components[index]);if(ccm.helper.regex("filename").test(component.split("/").pop())){const response=await ccm.load(component);response.url=component;return response}return new Error("invalid component index or URL: "+component)}return component}},instance:async(component,config)=>{if(config&&config.root&&config.parent){config.root.innerHTML="";config.root.appendChild(ccm.helper.loading(config.parent))}component=await ccm.component(component,{ccm:config&&config.ccm});config&&delete config.ccm;config=await prepareConfig(config,component.config);config.beforeCreation&&await config.beforeCreation(config,ccm.helper.clone(component));delete config.beforeCreation;if(!ccm.helper.isComponent(component))return component;if(component.ccm.version()!==ccm.version())return new Promise((async resolve=>{const result=await window.ccm[component.ccm.version()].instance(component,config,resolve);result&&resolve(result)}));let instance=createInstance();config.afterCreation&&await config.afterCreation(config,ccm.helper.clone(component));delete config.afterCreation;instance.config=ccm.helper.stringify(config);if(!document.contains(instance.root)){instance.root.position=document.createElement("div");if(instance.root.parentNode)instance.root.parentNode.replaceChild(instance.root.position,instance.root);document.head.appendChild(instance.root)}config=await ccm.helper.solveDependencies(config,instance);if(document.head.contains(instance.root)){document.head.removeChild(instance.root);if(instance.root.position.parentNode)instance.root.position.parentNode.replaceChild(instance.root,instance.root.position);delete instance.root.placeholder}config.inner=ccm.helper.html(config.inner,undefined,{no_evaluation:true});Object.assign(instance,config);if(!instance.parent||!instance.parent.init)await initialize();instance.onReady&&await instance.onReady(instance);delete instance.onReady;return instance;function createInstance(){const instance=new component.Instance;instance.ccm=component.ccm;instance.component=component;instance.parent=config.parent;delete config.parent;instance.children={};instance.root=config.root;delete config.root;instance.id=++_components[component.index].instances;instance.index=component.index+"-"+instance.id;setElement();if(!instance.init)instance.init=async()=>{};if(instance.parent){if(!instance.parent.children)instance.parent.children={};instance.parent.children[instance.index]=instance}if(instance.root.id===instance.index&&instance.root.parentNode&&instance.root.parentNode.tagName.indexOf("CCM-")===0)watchAttributes();return instance;function setElement(){if(instance.root==="parent"&&instance.parent){instance.root=instance.parent.root;instance.element=instance.parent.element;return}if(typeof instance.root==="string")instance.root=instance.parent.element.querySelector("#"+(instance.root==="name"&&instance.parent?component.name:instance.root));const root=ccm.helper.html({id:instance.index});if(instance.root){instance.root.innerHTML="";instance.root.appendChild(root);instance.root=root}if(!config.shadow)config.shadow="closed";if(typeof config.shadow==="string"&&config.shadow!=="none"){instance.shadow=root.shadowRoot||root.attachShadow({mode:config.shadow});delete config.shadow}(instance.shadow||root).appendChild(instance.element=ccm.helper.html({id:"element"}));config.breakpoints!==false&&ccm.helper.responsive(instance.element,config.breakpoints,instance);config.focusable!==false&&instance.element.setAttribute("tabindex","-1");if(!instance.root)instance.root=root;if(instance.start){instance.element.innerHTML="";instance.element.appendChild(ccm.helper.loading(instance))}}function watchAttributes(){if(!instance.update)instance.update=(key,value)=>{switch(key){case"ccm":case"component":case"config":case"element":case"id":case"index":case"init":case"onfinish":case"parent":case"ready":case"root":case"start":case"update":break;case"key":if(ccm.helper.regex("json").test(value))value=ccm.helper.parse(value);if(ccm.helper.isObject(value))for(const key in value)if(value.hasOwnProperty(key))switch(key){case"ccm":case"component":case"dependency":case"parent":case"id":case"index":case"element":case"root":case"init":case"ready":case"start":case"update":case"key":break;default:instance[key]=value[key]}instance.start();break;default:instance[key]=value;instance.start()}};const MutationObserver=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver;const observer=new MutationObserver((mutations=>mutations.forEach((mutation=>{if(mutation.type!=="attributes")return;const key=mutation.attributeName;const value=instance.root.parentNode.getAttribute(key);instance.update(key,value)}))));observer.observe(instance.root.parentNode,{attributes:true})}}function initialize(){return new Promise((resolve=>{const instances=[instance];find(instance);let i=0;init();function find(obj){const relevant=[];for(const key in obj)if(obj.hasOwnProperty&&obj.hasOwnProperty(key)){const value=obj[key];if(ccm.helper.isInstance(value)&&key!=="parent"&&!ccm.helper.isProxy(value)){instances.push(value);relevant.push(value)}else if(Array.isArray(value)||ccm.helper.isObject(value)){if(ccm.helper.isSpecialObject(value))continue;relevant.push(value)}}relevant.map(find)}function init(){if(i===instances.length)return ready();const next=instances[i++];next.init?next.init().then((()=>{delete next.init;init()})):init()}function ready(){if(!instances.length)return resolve();const next=instances.pop();next.ready?next.ready().then((()=>{delete next.ready;proceed()})):proceed();function proceed(){if(next._start){delete next._start;next.start().then(ready)}else ready()}}}))}},proxy:async(component,config)=>{const obj={ccm:true,component:{Instance:true}};obj.start=async cfg=>await Object.assign(obj,await ccm.instance(component,await ccm.helper.integrate(cfg,config))).start();return obj},start:async(component,config={},element)=>{if(element)config.root=element;const instance=await ccm.instance(component,config);if(!ccm.helper.isInstance(instance))return instance;instance.init?instance._start=true:await instance.start();return instance},store:(config={})=>new Promise(((resolve,reject)=>{config=ccm.helper.clone(config);if(typeof config==="string")config=config.split("?").shift().endsWith(".js")?{local:["ccm.load",config]}:{name:config};if(!ccm.helper.isObject(config)||!config.local&&!config.name){config={local:config,parent:config.parent};delete config.local.parent}if(!config.local&&!config.name)config.local={};ccm.helper.solveDependency(config.local).then((result=>{config.local=result;if(Array.isArray(config.local))config.local=ccm.helper.arrToStore(config.local);let store=new Datastore;Object.assign(store,config);store.init().then((()=>resolve(store)))})).catch(reject)})),get:(config={},key_or_query={})=>ccm.store(config).then((store=>{let property;if(typeof key_or_query==="string"){property=key_or_query.split(".");key_or_query=property.shift();property=property.join(".")}return store.get(key_or_query).then((result=>property?ccm.helper.deepValue(result,property):result))})),components:{},context:{find:(instance,property,not_me)=>{const start=instance;if(not_me)instance=instance.parent;do{if(ccm.helper.isObject(instance)&&instance[property]!==undefined&&instance[property]!==start)return instance[property]}while(instance=instance.parent)},highestByProperty:(instance,property,not_me)=>{const start=instance;let result=null;if(not_me)instance=instance.parent;if(!instance)return null;do{if(ccm.helper.isObject(instance)&&instance[property]!==undefined&&instance[property]!==start)result=instance}while(instance=instance.parent);return result},nearestByProperty:(instance,property,not_me)=>{const start=instance;if(not_me)instance=instance.parent;if(!instance)return null;do{if(ccm.helper.isObject(instance)&&instance[property]!==undefined&&instance[property]!==start)return instance}while(instance=instance.parent);return null},root:function(instance){while(instance.parent)instance=instance.parent;return instance}},helper:{arrToStore:arr=>{if(!Array.isArray(arr))return;const obj={};arr.forEach((value=>{if(ccm.helper.isDataset(value))obj[value.key]=value}));return obj},clone:function(value){return recursive(value,true);function recursive(value,first){if(ccm.helper.isSpecialObject(value)&&!first)return value;if(Array.isArray(value)||ccm.helper.isObject(value)){var copy=Array.isArray(value)?[]:{};for(var i in value)copy[i]=recursive(value[i]);return copy}return value}},compareVersions:(a,b)=>{if(a===b)return 0;const a_arr=a.split(".");const b_arr=b.split(".");for(let i=0;i<3;i++){const x=parseInt(a_arr[i]);const y=parseInt(b_arr[i]);if(x<y)return-1;else if(x>y)return 1}return 0},convertComponentURL:url=>{const filename=url.split("/").pop();if(!ccm.helper.regex("filename").test(filename))throw new Error("invalid component filename: "+filename);const data={url:url};let tmp=filename.substring(4,filename.length-3);if(tmp.endsWith(".min")){data.minified=true;tmp=tmp.substr(0,tmp.length-4)}tmp=tmp.split("-");data.name=tmp.shift();if(tmp.length)data.version=tmp[0];data.index=data.name+(data.version?"-"+data.version.replace(/\./g,"-"):"");return data},deepValue:function(obj,key,value){return recursive(obj,key.split("."),value);function recursive(obj,key,value){if(!obj)return;var next=key.shift();if(key.length===0)return value!==undefined?obj[next]=value:obj[next];if(!obj[next]&&value!==undefined)obj[next]=isNaN(key[0])?{}:[];return recursive(obj[next],key,value)}},format:function(data,values){const temp=[[],[],{}];const obj_mode=ccm.helper.isObject(data);values=ccm.helper.clone([...arguments]);values.shift();data=ccm.helper.stringify(data,((key,val)=>{if(typeof val==="function"){temp[0].push(val);return"%$0%"}return val}));for(let i=0;i<values.length;i++){if(typeof values[i]==="object"){for(const key in values[i])if(values[i].hasOwnProperty(key)){if(typeof values[i][key]!=="string"&&obj_mode){temp[2][key]=values[i][key];values[i][key]=`%$2%${key}%`}if(typeof values[i][key]!=="string")continue;data=data.replace(new RegExp(`%${key}%`,"g"),values[i][key].replace(/"/g,'\\"'))}}else{if(typeof values[i]!=="string"&&obj_mode){temp[1].push(values[i]);values[i]="%$1%"}data=data.replace(/%%/,values[i].replace(/"/g,'\\"'))}}return ccm.helper.parse(data,((key,val)=>{if(val==="%$0%")return temp[0].shift();if(val==="%$1%")return temp[1].shift();if(typeof val==="string"){if(val.indexOf("%$2%")===0&&val.split("%")[3]==="")return temp[2][val.split("%")[2]];else for(const key in temp[2])val=val.replace(new RegExp(`%\\$2%${key}%`,"g"),temp[2][key])}return val}))},generateConfig:element=>{element=ccm.helper.html(element,undefined,{no_evaluation:true});if(ccm.helper.regex("json").test(element.innerHTML)){element.setAttribute("inner",element.innerHTML);element.innerHTML=""}const config={};catchAttributes(element,config);catchInnerTags(element);return config;function catchAttributes(element,obj){if(!element.attributes)return;[...element.attributes].forEach((attr=>{if(attr.name!=="src"||element.tagName.indexOf("CCM-COMPONENT")!==0&&element.tagName.indexOf("CCM-INSTANCE")!==0&&element.tagName.indexOf("CCM-PROXY")!==0)try{obj[attr.name]=attr.value.charAt(0)==="{"||attr.value.charAt(0)==="["?ccm.helper.parse(attr.value):prepareValue(attr.value)}catch(err){}}))}function catchInnerTags(element){if(!element.childNodes)return;config.childNodes=[];[...element.childNodes].forEach((child=>{if(child.tagName&&child.tagName.indexOf("CCM-")===0){const split=child.tagName.toLowerCase().split("-");if(split.length<3)split[2]=split[1];switch(split[1]){case"load":ccm.helper.deepValue(config,split[2],interpretLoadTag(child,split[2]));break;case"component":case"instance":case"proxy":ccm.helper.deepValue(config,split[2],["ccm."+split[1],child.getAttribute("src")||split[2],ccm.helper.generateConfig(child)]);break;case"store":case"get":const settings={};catchAttributes(child,settings);const key=settings.key;delete settings.key;ccm.helper.deepValue(config,split[2],["ccm."+split[1],settings,key]);break;case"list":let list=null;[...child.children].forEach((entry=>{if(entry.tagName&&entry.tagName.indexOf("CCM-ENTRY")===0){const value=prepareValue(entry.getAttribute("value"));const split=entry.tagName.toLowerCase().split("-");if(!list)list=split.length<3?[]:{};if(split.length<3)list.push(value);else ccm.helper.deepValue(list,split[2],value)}}));if(!list)list={};catchAttributes(child,list);if(list)ccm.helper.deepValue(config,split[2],list);break;default:config.childNodes.push(child);element.removeChild(child)}}else{config.childNodes.push(child);element.removeChild(child)}}));if(config.inner)return;config.inner=ccm.helper.html({});config.childNodes.forEach((child=>config.inner.appendChild(child)));delete config.childNodes;if(!config.inner.hasChildNodes())delete config.inner;function interpretLoadTag(node){let params=generateParameters(node);if(!Array.isArray(params))params=[params];params.unshift("ccm.load");if(node.hasAttribute("head"))params.push(true);return params;function generateParameters(node){if(node.hasAttribute("src")){if(node.children.length===0)return node.getAttribute("src");const data={};[...node.children].forEach((child=>{if(child.tagName&&child.tagName.indexOf("CCM-DATA-")===0)data[child.tagName.toLowerCase().split("-")[2]]=child.getAttribute("value")}));return[node.getAttribute("src"),data]}const params=[];[...node.children].forEach((child=>{if(child.tagName==="CCM-SERIAL"&&(node.tagName==="CCM-PARALLEL"||node.tagName.indexOf("CCM-LOAD")===0)||child.tagName==="CCM-PARALLEL"&&node.tagName==="CCM-SERIAL")params.push(generateParameters(child))}));return params}}}function prepareValue(value){if(value==="true")return true;if(value==="false")return false;if(value==="null")return null;if(value==="undefined")return undefined;if(value==="")return true;if(!isNaN(value))return parseInt(value);return value}},generateKey:function(){return crypto.randomUUID()},html:function(html,...values){if(!html||ccm.helper.isInstance(html))return html;if(ccm.helper.isElement(html)&&!values.length)return html;if(typeof html==="function")return html.apply(this,values);let advanced={};if(values.length>1&&ccm.helper.isObject(values[values.length-1])){advanced=values.pop();if(values[0]===undefined)values.shift()}html=ccm.helper.html2json(html);html=ccm.helper.clone(html);if(values.length){values.unshift(html);html=ccm.helper.format.apply(this,values)}if(Array.isArray(html)){const result=[];for(let i=0;i<html.length;i++)result.push(ccm.helper.html(html[i],undefined,advanced));return result}if(typeof html!=="object"||html===null)html={tag:"span",inner:html};if(html.tag==="svg")advanced.namespace_uri="http://www.w3.org/2000/svg";const element=advanced.namespace_uri?document.createElementNS(advanced.namespace_uri,html.tag||"div"):document.createElement(html.tag||"div");delete html.tag;if(!ccm.helper.regex("json").test(html.key))delete html.key;for(const key in html){const value=html[key];switch(key){case"async":case"autofocus":case"defer":case"disabled":case"ismap":case"multiple":case"required":case"selected":if(value)element[key]=true;break;case"checked":if(value){element[key]=true;element.setAttribute(key,"")}break;case"readonly":if(value)element.readOnly=true;break;case"inner":if(typeof value==="string"||typeof value==="number"||typeof value==="boolean"){element.innerHTML=value;break}let children=Array.isArray(value)?value:[value];children.forEach((child=>element.appendChild(this.html(child,undefined,advanced))));break;default:if(key.indexOf("on")===0&&typeof value==="function")element.addEventListener(key.substr(2),value);else element.setAttribute(key,value)}}if(element.tagName.startsWith("CCM-")&&!advanced.no_evaluation){const config=ccm.helper.generateConfig(element);config.root=element;(config.ccm&&config.ccm!=="latest"?window.ccm[config.ccm]:window.ccm).start(element.tagName==="CCM-APP"?element.getAttribute("component"):element.tagName.substr(4).toLowerCase(),config)}return element},html2json:html=>{const json={inner:[]};if(typeof html==="string"){const template=document.createElement("template");template.innerHTML=html;html=template.content}if(window.jQuery&&html instanceof jQuery){html=html.get();const fragment=document.createDocumentFragment();html.forEach((elem=>fragment.appendChild(elem)));html=fragment}if(html instanceof DocumentFragment){if(!html.children.length)return html.textContent;[...html.childNodes].forEach((child=>{if(child.nodeValue){child.nodeValue=child.nodeValue.trim();if(!child.nodeValue||child.nodeType===Node.COMMENT_NODE)child.parentNode.removeChild(child)}}));if(html.childNodes.length===1)html=html.firstChild}if(!ccm.helper.isElement(html))return html;if(html.tagName)json.tag=html.tagName.toLowerCase();if(json.tag==="div")delete json.tag;html.attributes&&[...html.attributes].forEach((attr=>json[attr.name]=attr.value===""&&attr.name!=="value"?true:attr.value));[...html.childNodes].forEach((child=>{if(child.nodeType===Node.COMMENT_NODE)return child.parentNode.removeChild(child);if(child.nodeValue&&!child.parentElement?.closest("pre"))child.nodeValue=child.nodeValue.replace(/\s+/g," ");if(ccm.helper.isElement(child)||child.nodeValue.trim())json.inner.push(ccm.helper.isElement(child)?ccm.helper.html2json(child):child.textContent)}));if(!json.inner.length)delete json.inner;else if(json.inner.length===1)json.inner=json.inner[0];return json},integrate:async(priodata,dataset,as_defaults)=>{dataset=ccm.helper.clone(dataset);if(!ccm.helper.isObject(priodata))return dataset;if(!ccm.helper.isObject(dataset))return ccm.helper.clone(priodata);for(let key in priodata){const split=key.split(".");let obj=dataset;for(let i=0;i<split.length;i++){const prop=split[i];if(ccm.helper.isDependency(obj[prop])&&obj[prop][0]==="ccm.get")obj[prop]=await ccm.helper.solveDependency(obj[prop]);obj=obj[prop];if(!obj)break}const value=ccm.helper.deepValue(dataset,key);if(!as_defaults||value===undefined||value==="")ccm.helper.deepValue(dataset,key,priodata[key])}return dataset},isComponent:function(value){return ccm.helper.isObject(value)&&value.Instance&&true},isDataset:value=>ccm.helper.isObject(value)&&ccm.helper.isKey(value.key),isDatastore:value=>ccm.helper.isObject(value)&&value.get&&value.set&&value.del&&value.source&&value.clear&&true,isDependency:function(value){if(Array.isArray(value))if(value.length>0)switch(value[0]){case"ccm.load":case"ccm.component":case"ccm.instance":case"ccm.proxy":case"ccm.start":case"ccm.store":case"ccm.get":case"ccm.set":case"ccm.del":return true}return false},isElement:function(value){return value instanceof Element||value instanceof DocumentFragment},isCore:value=>ccm.helper.isObject(value)&&value.components&&value.version&&true,isInstance:value=>ccm.helper.isObject(value)&&ccm.helper.isComponent(value.component)&&value.ccm&&true,isKey:value=>{if(typeof value==="string"||typeof value==="number")return ccm.helper.regex("key").test(value);if(Array.isArray(value)){for(let i=0;i<value.length;i++)if(!ccm.helper.regex("key").test(value[i]))return false;return true}return false},isNode:function(value){return value instanceof Node},isObject:function(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)},isProxy:function(value){return ccm.helper.isInstance(value)&&value.component===true},isSpecialObject:value=>!!(value===window||ccm.helper.isNode(value)||ccm.helper.isCore(value)||ccm.helper.isInstance(value)||ccm.helper.isComponent(value)||ccm.helper.isDatastore(value)||window.jQuery&&value instanceof jQuery),isSubset(obj,other){for(const key in obj)if(obj[key]===null){if(other[key]!==undefined)return false}else if(obj[key]===true){if(!other[key])return false}else if(typeof obj[key]==="string"&&obj[key].startsWith("/")&&obj[key].endsWith("/")){if(!new RegExp(obj[key].slice(1,-1)).test(other[key]&&typeof other[key]==="object"?other[key].toString():other[key]))return false}else if(typeof obj[key]==="object"&&typeof other[key]==="object"){if(JSON.stringify(obj[key])!==JSON.stringify(other[key]))return false}else if(key.includes(".")){if(ccm.helper.deepValue(other,key)!==obj[key])return false}else if(obj[key]!==other[key])return false;return true},loadVersion:async url=>{let resource={};if(ccm.helper.isObject(url)){url=ccm.helper.clone(url);resource.url=url.url;delete url.url;resource.attr=url}else resource={url:url};const version=(resource.url.match(/(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)/)||[""])[0];version&&!window.ccm[version]&&await ccm.load(resource);return version?window.ccm[version]:window.ccm},loading:instance=>{let element=instance?instance.element.parentNode:document.head;if(!element.querySelector("#ccm_keyframe")){const style=document.createElement("style");style.id="ccm_keyframe";style.appendChild(document.createTextNode("@keyframes ccm_loading { to { transform: rotate( 360deg ); } }"));element.appendChild(style)}element=document.createElement("div");element.classList.add("ccm_loading");element.setAttribute("style","display: grid; padding: 0.5em;");element.innerHTML='<div style="align-self: center; justify-self: center; display: inline-block; width: 2em; height: 2em; border: 0.3em solid #f3f3f3; border-top-color: #009ee0; border-left-color: #009ee0; border-radius: 50%; animation: ccm_loading 1.5s linear infinite;"></div>';return element},log:message=>console.log("[ccmjs]",message),parse:(string,reviver)=>JSON.parse(string.replace(/\\n/g,"\\n").replace(/\\'/g,"\\'").replace(/\\"/g,'\\"').replace(/\\&/g,"\\&").replace(/\\r/g,"\\r").replace(/\\t/g,"\\t").replace(/\\b/g,"\\b").replace(/\\f/g,"\\f").replace(/[\u0000-\u0019]+/g,""),reviver),regex:function(index){switch(index){case"filename":return/^ccm\.([a-z][a-z_0-9]*)(-(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*))?(\.min)?(\.js)$/;case"key":return/^[a-zA-Z0-9_-]+$/;case"json":return/^(({(.|\n)*})|(\[(.|\n)*])|true|false|null)$/}},responsive:(element,breakpoints={SM:384,MD:576,LG:768,XL:960},instance)=>{let init=true;if(window.ResizeObserver)new ResizeObserver(updateBreakpoints).observe(element);else{const observer=new MutationObserver((mutations=>mutations.forEach((mutation=>mutation.type==="attributes"&&mutation.attributeName==="style"&&updateBreakpoints()))));observer.observe(element,{attributes:true});document.body.querySelectorAll("*").forEach((element=>observer.observe(element,{attributes:true})));window.addEventListener("resize",updateBreakpoints,false);updateBreakpoints()}function updateBreakpoints(){const before=element.getAttribute("class");for(const key in breakpoints)element.classList[element.offsetWidth>=breakpoints[key]?"add":"remove"](key);const after=element.getAttribute("class");!init&&before!==after&&instance.onbreakpoint&&instance.onbreakpoint(breakpoints[after.split(" ").pop()]||0);init=false}},solveDependencies:(obj,instance)=>new Promise(((resolve,reject)=>{obj=ccm.helper.clone(obj);if(!ccm.helper.isObject(obj)&&!Array.isArray(obj))return resolve(obj);let failed=false;let counter=1;search(obj);check();function search(obj){if(ccm.helper.isSpecialObject(obj))return;for(const key in obj)if(obj.hasOwnProperty(key))if(key!=="ignore"){const value=obj[key];if(ccm.helper.isDependency(value)){counter++;ccm.helper.solveDependency(obj[key],instance).then((result=>{obj[key]=result;check()})).catch((result=>{failed=true;obj[key]=result;check()}))}else if(ccm.helper.isObject(value)||Array.isArray(value))search(value)}}function check(){!--counter&&(failed?reject:resolve)(obj)}})),solveDependency:async(dependency,instance)=>{if(!ccm.helper.isDependency(dependency))return dependency;dependency=ccm.helper.clone(dependency);const operation=dependency.shift().substr("ccm.".length);switch(operation){case"load":instance&&setContext(dependency);return await ccm.load.apply(null,dependency);case"component":case"instance":case"proxy":case"start":case"set":case"del":dependency[1]=await ccm.helper.solveDependency(dependency[1],instance);if(!dependency[operation==="store"?0:1])dependency[operation==="store"?0:1]={};if(instance)dependency[operation==="store"?0:1].parent=instance;return await ccm[operation].apply(null,dependency);case"store":case"get":if(!dependency[0])dependency[0]={};if(instance)dependency[0].parent=instance;return await ccm[operation].apply(null,dependency)}function setContext(resources){for(let i=0;i<resources.length;i++){if(Array.isArray(resources[i])){setContext(resources[i]);continue}if(!ccm.helper.isObject(resources[i]))resources[i]={url:resources[i]};if(!resources[i].context)resources[i].context=instance.element.parentNode}}},solveDotNotation:function(obj){obj=ccm.helper.clone(obj);for(const key in obj)if(key.indexOf(".")!==-1){ccm.helper.deepValue(obj,key,obj[key]);delete obj[key]}return obj},stringify:(value,replacer,space)=>JSON.stringify(value,((key,value)=>{if(typeof value==="function"||ccm.helper.isSpecialObject(value))value=null;return replacer?replacer(key,value):value}),space),toDotNotation:function(obj,all_levels){const result={};recursive(obj,"");return result;function recursive(obj,prefix){for(const key in obj){if(typeof obj[key]==="object"&&!ccm.helper.isSpecialObject(obj[key])){if(all_levels)result[prefix+key]=obj[key];recursive(obj[key],prefix+key+".")}else result[prefix+key]=obj[key]}}},toJSON:value=>ccm.helper.parse(ccm.helper.stringify(value))},timeout:0};if(ccm.version&&!window.ccm[ccm.version()])window.ccm[ccm.version()]=ccm;if(!window.ccm.version||ccm.helper.compareVersions(ccm.version(),window.ccm.version())>0)Object.assign(window.ccm,ccm.helper.clone(ccm));defineCustomElement("app");async function defineCustomElement(name){if(!("customElements"in window))await ccm.load({url:"https://ccmjs.github.io/ccm/polyfills/webcomponents-lite.js",attr:{integrity:"sha384-yEuTKRGFLhOAfHNxaZiiI23KhMelYudrPUNSUK6T5u1+deGEEKsQ89cS0sPIHjyj",crossorigin:"anonymous"}});if(customElements.get("ccm-"+name))return;window.customElements.define("ccm-"+name,class extends HTMLElement{async connectedCallback(){if(!document.body.contains(this))return;let node=this;while(node=node.parentNode)if(node.tagName&&node.tagName.indexOf("CCM-")===0)return;const config=ccm.helper.generateConfig(this);config.root=this;await(config.ccm&&config.ccm!=="latest"?window.ccm[config.ccm]:window.ccm).start(this.tagName==="CCM-APP"?config.component:name,config)}})}async function prepareConfig(config={},defaults={}){config=await ccm.helper.solveDependency(config);let result=defaults;const recursive=async config=>{if(!config.src)return;let source=await ccm.helper.solveDependency(config.src);delete config.src;await recursive(source);result=await ccm.helper.integrate(source,result)};await recursive(config);result=await ccm.helper.integrate(config,result);delete result.component;return result}async function changeVersion(component,config){const source=config&&config.ccm||component.config&&component.config.ccm;if(source){component.ccm=source==="latest"?window.ccm:window.ccm[source]||window.ccm[(await ccm.helper.loadVersion(source)).version()];component.ccm.url=ccm.helper.isObject(source)?source.url:source;config&&delete config.ccm;component.config&&delete component.config.ccm}}})();
//# sourceMappingURL=ccm.min.js.map