vaderjs 1.3.3-alpha-63 → 1.3.3-alpha-64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/runtime/router.js +1 -1
- package/runtime/vader.js +1 -1
- package/vader.js +16 -6
package/package.json
CHANGED
package/runtime/router.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Component}from"./vader.js";let middlewares=[];class VaderRouter{constructor(e,t){this.routes=[],this.middlewares=[],this.errorMiddlewares=[],this.listeners=[],this.basePath=e}get(e,t){this.routes.push({path:e,handler:t,method:"get"})}use(e){console.log(e),this.middlewares.push(e)}listen(e,t){e||(e=Math.random().toString(36).substring(7)),this.listeners.push(e),1===this.listeners.length?this.handleRoute(window.location.hash):this.listeners.pop(),t&&t(),window.onhashchange=()=>{this.handleRoute(window.location.hash)}}extractParams(e,t){const s=e.split("/"),n=t.split("/"),r={};return s.forEach(((e,t)=>{if(e.startsWith(":")){const s=e.slice(1);r[s]=n[t]}else if(e.startsWith("*")){n.slice(t).forEach(((e,t)=>{r[t]=e}))}})),r}extractQueryParams(e){const t=e.split("?")[1];if(!t)return{};const s={};return t.split("&").forEach((e=>{const[t,n]=e.split("=");s[t]=n})),s}handleRoute(e){let t=200,s=e=e.slice(1),n=this.routes.find((t=>{if(t.path===e)return!0;if(""===e&&"/"===t.path)return!0;if(e.includes("?")&&(e=e.split("?")[0]),t.path.includes("*")||t.path.includes(":")){const s=t.path.split("/"),n=e.split("/");if(s.length!==n.length&&!t.path.endsWith("*"))return!1;for(let e=0;e<s.length;e++){const t=s[e],r=n[e];if(!t.startsWith(":")&&!t.startsWith("*")&&t!==r)return!1}return!0}const n=this.extractParams(t.path,s);return Object.keys(n).length>0}));n||(n=this.routes.find((e=>{if(e.path.includes("/404"))return this.error=!0,!0;!this.error&&e.path.includes("/404")&&(window.location.hash=this.basePath)})),t=n?200:404);const r=this.extractQueryParams(s),o=n&&n.path?this.extractParams(n.path,s):{},a={headers:{},params:o,query:r,path:e,url:window.location.href+e,method:n?n.method:"get",pause:!1,timestamp:Date.now()};window.$CURRENT_URL=a.path,window.$FULL_URL=window.location.href.replace("#","");const i={status:t,log:e=>{void 0===e?console.log(`${a.path} ${a.method} ${i.status} ${a.timestamp}`):console.table({"Request Path":a.path,"Request Method":n.method,"Response Status":i.status,"Request Timestamp":a.timestamp})},refresh:()=>{this.handleRoute(window.location.hash)},redirect:e=>{!e.startsWith("/")&&(e=`/${e}`),window.location.hash=`#${e}`},render:async(e,t,s)=>{function n(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}try{let a=new Component;if(n(e.default)){let t=new e.default;a.state=t.state,a=t}else{if(e.default.toString().includes("this.key"))throw new Error('Using this.key is not supported in functional components use the attribute key="a value" instead');a.key=e.default.toString().split('key="')[1]?e.default.toString().split('key="')[1].split('"')[0]:null;let n={key:a.key,render:()=>e.default.apply(a,[t,s]),request:t,response:s,params:o,queryParams:r,reset:a.reset.bind(a),onMount:a.onMount.bind(a),useState:null,router:{use:a.router.use.bind(a)},bindMount:a.bindMount.bind(a),memoize:a.memoize.bind(a),createComponent:a.createComponent.bind(a),isChild:!1,useState:a.useState.bind(a),parseStyle:a.parseStyle.bind(a),bind:a.bind.bind(a),hydrate:a.hydrate.bind(a)};a.render=n.render,a=n}if(!document.querySelector("#root"))throw new Error("Root element not found, please add an element with id root");a.reset(),a.components={},a.request=t,a.response=s,a.router.use&&!a.isChild?await new Promise((async r=>{if(n(e.default))if(n(e.default))switch(await a.router.use(t,s),t.pause){case!0:console.log("pausing",t.pause);let e=setInterval((()=>{t.pause?console.log("still pausing",t.pause):(clearInterval(e),r())}),1e3);break;case!1:r()}else r();else switch(await e.default.apply(a,[t,s]),await a.router.use(t,s),t.pause){case!0:let e=setInterval((()=>{t.pause?console.log("still pausing request",t.url):(clearInterval(e),r())}),1e3);break;case!1:r()}})):a.router.use&&a.isChild&&console.warn("Router.use() is not supported in child components");const i=await a.render();document.querySelector("#root").innerHTML=i,a.bindMount(),a.onMount()}catch(e){console.error(e)}},setQuery:e=>{let t="";Object.keys(e).forEach(((s,n)=>{t+=`${0===n?"?":"&"}${s}=${e[s]}`}));let s=window.location.hash.split("?")[0];t=t.replace("/","-").replaceAll("/","-"),window.location.hash=`${s}${t}`},send:e=>{document.querySelector("#root").innerHTML=e},json:e=>{const t=document.querySelector("#root");t.innerHTML="";const s=document.createElement("pre");s.textContent=JSON.stringify(e,null,2),t.appendChild(s)}};middlewares.forEach((e=>{e(a,i)})),n&&n.handler(a,i)}}window.VaderRouter=VaderRouter;export default VaderRouter;
|
|
1
|
+
import{Component}from"./vader.js";let middlewares=[];class VaderRouter{constructor(e,t){this.routes=[],this.middlewares=[],this.errorMiddlewares=[],this.listeners=[],this.basePath=e}get(e,t){this.routes.push({path:e,handler:t,method:"get"})}use(e){console.log(e),this.middlewares.push(e)}listen(e,t){e||(e=Math.random().toString(36).substring(7)),this.listeners.push(e),1===this.listeners.length?this.handleRoute(window.location.hash):this.listeners.pop(),t&&t(),window.onhashchange=()=>{this.handleRoute(window.location.hash)}}extractParams(e,t){const s=e.split("/"),n=t.split("/"),r={};return s.forEach(((e,t)=>{if(e.startsWith(":")){const s=e.slice(1);r[s]=n[t]}else if(e.startsWith("*")){n.slice(t).forEach(((e,t)=>{r[t]=e}))}})),r}extractQueryParams(e){const t=e.split("?")[1];if(!t)return{};const s={};return t.split("&").forEach((e=>{const[t,n]=e.split("=");s[t]=n})),s}handleRoute(e){let t=200,s=e=e.slice(1),n=this.routes.find((t=>{if(t.path===e)return!0;if(""===e&&"/"===t.path)return!0;if(e.includes("?")&&(e=e.split("?")[0]),t.path.includes("*")||t.path.includes(":")){const s=t.path.split("/"),n=e.split("/");if(s.length!==n.length&&!t.path.endsWith("*"))return!1;for(let e=0;e<s.length;e++){const t=s[e],r=n[e];if(!t.startsWith(":")&&!t.startsWith("*")&&t!==r)return!1}return!0}const n=this.extractParams(t.path,s);return Object.keys(n).length>0}));n||(n=this.routes.find((e=>{if(e.path.includes("/404"))return this.error=!0,!0;!this.error&&e.path.includes("/404")&&(window.location.hash=this.basePath)})),t=n?200:404);const r=this.extractQueryParams(s),o=n&&n.path?this.extractParams(n.path,s):{},a={headers:{},params:o,query:r,path:e,url:window.location.href+e,method:n?n.method:"get",pause:!1,timestamp:Date.now()};window.$CURRENT_URL=a.path,window.$FULL_URL=window.location.href.replace("#","");const i={status:t,log:e=>{void 0===e?console.log(`${a.path} ${a.method} ${i.status} ${a.timestamp}`):console.table({"Request Path":a.path,"Request Method":n.method,"Response Status":i.status,"Request Timestamp":a.timestamp})},refresh:()=>{this.handleRoute(window.location.hash)},redirect:e=>{!e.startsWith("/")&&(e=`/${e}`),window.location.hash=`#${e}`},render:async(e,t,s)=>{function n(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}try{let a=new Component;if(n(e.default)){let t=new e.default;a.state=t.state,a=t}else{if(e.default.toString().includes("this.key"))throw new Error('Using this.key is not supported in functional components use the attribute key="a value" instead');a.key=e.default.toString().split('key="')[1]?e.default.toString().split('key="')[1].split('"')[0]:null;let n={key:a.key,render:()=>e.default.apply(a,[t,s]),request:t,response:s,params:o,queryParams:r,reset:a.reset.bind(a),onMount:a.onMount.bind(a),useState:null,router:{use:a.router.use.bind(a)},bindMount:a.bindMount.bind(a),memoize:a.memoize.bind(a),createComponent:a.createComponent.bind(a),isChild:!1,useState:a.useState.bind(a),parseStyle:a.parseStyle.bind(a),bind:a.bind.bind(a),useRef:a.useRef.bind(a),useReducer:a.useReducer.bind(a),hydrate:a.hydrate.bind(a)};a.render=n.render,a=n}if(!document.querySelector("#root"))throw new Error("Root element not found, please add an element with id root");a.reset(),a.components={},a.request=t,a.response=s,a.router.use&&!a.isChild?await new Promise((async r=>{if(n(e.default))if(n(e.default))switch(await a.router.use(t,s),t.pause){case!0:console.log("pausing",t.pause);let e=setInterval((()=>{t.pause?console.log("still pausing",t.pause):(clearInterval(e),r())}),1e3);break;case!1:r()}else r();else switch(await e.default.apply(a,[t,s]),await a.router.use(t,s),t.pause){case!0:let e=setInterval((()=>{t.pause?console.log("still pausing request",t.url):(clearInterval(e),r())}),1e3);break;case!1:r()}})):a.router.use&&a.isChild&&console.warn("Router.use() is not supported in child components");const i=await a.render();document.querySelector("#root").innerHTML=i,a.bindMount(),a.onMount()}catch(e){console.error(e)}},setQuery:e=>{let t="";Object.keys(e).forEach(((s,n)=>{t+=`${0===n?"?":"&"}${s}=${e[s]}`}));let s=window.location.hash.split("?")[0];t=t.replace("/","-").replaceAll("/","-"),window.location.hash=`${s}${t}`},send:e=>{document.querySelector("#root").innerHTML=e},json:e=>{const t=document.querySelector("#root");t.innerHTML="";const s=document.createElement("pre");s.textContent=JSON.stringify(e,null,2),t.appendChild(s)}};middlewares.forEach((e=>{e(a,i)})),n&&n.handler(a,i)}}window.VaderRouter=VaderRouter;export default VaderRouter;
|
package/runtime/vader.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
window.Vader={version:"1.3.3"},window.componentRegistry={};let errors={"SyntaxError: Unexpected token '<'":"You forgot to enclose tags in a fragment <></>"},mounts=[],hasRan=[];export const strictMount=(e,t)=>{let n=setInterval((()=>{document.querySelector(`[key="${e}"]`)&&!hasRan.includes(e)&&(clearInterval(n),t(),hasRan.push(e))}),120)};export class Component{constructor(){this.state={},this.key=null,this.components={},this.mounted=!1,this.checkIFMounted(),this.memoizes=[],this.functions=[],this.children=[],this.parentNode={},this.request={headers:{},method:"GET",params:{},path:"",query:{}},this.response={json:e=>{},send:e=>{},redirect:e=>{},render:async e=>{},log:e=>{},setQuery:e=>{}},this.router={use:e=>{}}}createComponent(e,t,n){function s(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}let r=s(e)?new e(t):null;if(!e)throw new Error("Component must be defined");let o=new Component(t);if(s(e
|
|
1
|
+
window.Vader={version:"1.3.3"},window.componentRegistry={};let errors={"SyntaxError: Unexpected token '<'":"You forgot to enclose tags in a fragment <></>"},mounts=[],hasRan=[];export const strictMount=(e,t)=>{let n=setInterval((()=>{document.querySelector(`[key="${e}"]`)&&!hasRan.includes(e)&&(clearInterval(n),t(),hasRan.push(e))}),120)};export class Component{constructor(){this.state={},this.key=null,this.components={},this.mounted=!1,this.checkIFMounted(),this.memoizes=[],this.functions=[],this.children=[],this.parentNode={},this.request={headers:{},method:"GET",params:{},path:"",query:{}},this.response={json:e=>{},send:e=>{},redirect:e=>{},render:async e=>{},log:e=>{},setQuery:e=>{}},this.router={use:e=>{}}}createComponent(e,t,n){function s(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}let r=s(e)?new e(t):null;if(!e)throw new Error("Component must be defined");let o=new Component(t);if(s(e))r.props=t,r.children=n,r.props.children=n.join(""),r.parentNode=this,r.request=this.request,r.response=this.response,r.key=t.key||null,o=r;else{e.toString();o.key=e.toString().split('key="')[1]?e.toString().split('key="')[1].split('"')[0]:null;let n={key:o.key,render:()=>e.apply(o,[t]),request:this.request,isChild:!0,response:this.response,params:this.request.params,queryParams:this.request.query,reset:o.reset.bind(o),onMount:o.onMount.bind(o),useState:null,router:{use:o.router.use.bind(o)},bindMount:o.bindMount.bind(o),memoize:o.memoize.bind(o),createComponent:o.createComponent.bind(o),isChild:!1,useState:o.useState.bind(o),parseStyle:o.parseStyle.bind(o),bind:o.bind.bind(o),useRef:o.useRef.bind(o),request:this.request,response:this.response,useReducer:o.useReducer.bind(o),hydrate:o.hydrate.bind(o),parentNoe:this};o.render=n.render,o=n}return this.components[t.key]||(this.components[t.key]=o),!this.children.includes(o)&&this.children.push(o),this.components[t.key]}reset(){Object.keys(this.components).forEach((e=>{this.components[e].onUnmount(),delete this.components[e]})),this.state={},this.children=[]}memoize(e){if(!e.key)throw new Error("Component must have a static key");if(!0==!this.memoizes.includes(e.key))this.memoizes.push(e.key),this.components[e.key]=e;let t=this.components[e.key];t.bindMount(),t.parentNode=this,t.props=e.props,t.request=this.request,t.response=this.response;let n=t.render();return n&&n.split(">,").length>1&&(n=n.replaceAll(">,",">")),`<div key="${e.key}">${n}</div>`}parseStyle(e){let t="";return Object.keys(e).forEach((n=>{let s=e[n];n=n.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g,"$1-$2").toLowerCase(),t+=`${n}:${s};`})),t}bindMount(){mounts.push(this)}domDifference(e,t){let n=[];for(let s=0;s<e.length;s++){let r=e[s],o=t[s];r&&o&&!r.isEqualNode(o)&&n.push({type:"replace",old:r,new:o.cloneNode(!0)})}return n}updateChangedElements(e){e.forEach((e=>{switch(e.type){case"replace":e.old.parentNode.replaceChild(e.new,e.old);break;case"remove":e.old.remove();break;case"add":e.old.appendChild(e.new.cloneNode(!0))}}))}hydrate(e){if(e){console.log(e);let t=(new DOMParser).parseFromString(this.render(),"text/html").body.querySelector(`[ref="${e}"]`),n=document.querySelector(`[ref="${e}"]`);console.log(t,n)}else{let e=this.key?document.querySelector(`[key="${this.key}"]`):null,t=(new DOMParser).parseFromString(this.render(),"text/html").body;if(t=document.createElement("div").appendChild(t),!e&&(e=document.querySelector(`[key="${t.attributes?.key?.value||null}"]`)),!e)return void console.error('Hydration failed, component not found got ensure you have set key="a value" on the component or this.key inside of function or render method body');t.querySelectorAll("*").forEach((e=>{e.hasAttribute("key")&&e.innerHTML!==document.querySelector(`[key="${e.attributes.key.value}"]`).innerHTML&&document.querySelector(`[key="${e.attributes.key.value}"]`).replaceWith(e)}))}}patch(e,t){const n=this.domDifference(e,t);this.updateChangedElements(n)}handleObject(obj){try{obj=JSON.parse(obj)}catch(e){}return eval(obj)}bind(e,t,n,s,...r){n=n+this.key||2022;let o={},i=(s=s.replace(/,,/g,",")).replaceAll(",,",",");for(var u in r){let e=r[u];o[i.split(",")[u]]=e}s=s.replace(",,",",");let a=null;try{a=new Function(`event, ${s}`,` \n return (async (event, ${s}) => { \n ${e.toString()}\n })(event, ${Object.keys(o).join(",")}) \n `)}catch(e){let{message:t}=e;console.error(`Error in function ${n} ${t}`)}return a=a.bind(this),this.functions.find((e=>e.ref===n))||document.addEventListener(`$dispatch_#id=${n}`,(e=>{let{name:t,event:s}=e.detail;if(t===n){let e=this.functions.find((e=>e.ref===n)).params;Object.keys(e).forEach((t=>{e[t]instanceof CustomEvent&&delete e[t],void 0===e[t]?delete e[t]:e[t]})),a(s,...Object.values(e))}})),window.callFunction=(e,t)=>{document.dispatchEvent(new CustomEvent(`$dispatch_#id=${e}`,{detail:{name:e,params:null,event:t}}))},!this.functions.find((e=>e.ref===n))&&this.functions.push({ref:n,params:o}),t?e:`((event)=>{event.target.ev = event; callFunction('${n}', event.target.ev)})(event)`}useState(e,t){this.state[e]||(this.state[e]=t);let n=()=>this.state[e],s=n();return[s,(t,r)=>{this.state[e]=t,this.hydrate(r),s=n()}]}useRef(e=null,t){this.state[e]||(this.state[e]=t);return{bind:e+this.key,current:(()=>document.querySelector(`[ref="${e+this.key}"]`)||t)()}}useReducer(e=null,t,n=null){this.state[e]||(this.state[e]=t);const s=()=>this.state[e];let r=s();return[s(),(t,o)=>{const i=n(r,t)??t;this.state[e]=i,this.hydrate(o),r=s()}]}render(){}checkIFMounted(){new MutationObserver((e=>{e.forEach((e=>{e.target.querySelector(`[key="${this.key}"]`)&&!this.mounted&&(this.onMount(),this.mounted=!0),Array.from(e.removedNodes).find((e=>e.attributes&&e.attributes.key&&e.attributes.key.value===this.key))&&(this.onUnmount(),this.reset())}))})).observe(document.body,{childList:!0,subtree:!0})}onMount(){}onUnmount(){}}export const useState=(e,t)=>{states[e]||(states[e]=t);return[states[e],(t,n)=>{states[e]=t,this.hydrate(n)}]};export const useReducer=(e,t)=>[e,e=>{}];export const useRef=e=>({current:e,bind:""});export default{Component:Component,useRef:useRef,useReducer:useReducer,useState:useState,strictMount:strictMount};
|
package/vader.js
CHANGED
|
@@ -590,8 +590,10 @@ function Compiler(func, file) {
|
|
|
590
590
|
path = path.replace(/'/g, '').trim().replace(/"/g, '').trim()
|
|
591
591
|
// remove double / from path
|
|
592
592
|
path = path.split('//').join('/')
|
|
593
|
-
if (!path.startsWith('./') && !path.includes('/vader.js') && !path.startsWith('src')
|
|
594
|
-
|
|
593
|
+
if (!path.startsWith('./') && !path.includes('/vader.js') && !path.startsWith('src')
|
|
594
|
+
&& !path.startsWith('/public')
|
|
595
|
+
) {
|
|
596
|
+
path = '/src/' + path
|
|
595
597
|
}
|
|
596
598
|
|
|
597
599
|
path = path.replaceAll('.jsx', '.js');
|
|
@@ -634,13 +636,14 @@ function Compiler(func, file) {
|
|
|
634
636
|
}
|
|
635
637
|
path = path.replace(/'/g, '').trim().replace(/"/g, '').trim()
|
|
636
638
|
// remove double / from path
|
|
637
|
-
path = path.split('//').join('/')
|
|
638
|
-
if (!path.startsWith('./') && !path.includes('/vader.js') && !path.startsWith('src')) {
|
|
639
|
+
path = path.split('//').join('/')
|
|
640
|
+
if (!path.startsWith('./') && !path.includes('/vader.js') && !path.startsWith('src') && !path.startsWith('public')) {
|
|
639
641
|
path.includes('src') ? path.split('src')[1] : null
|
|
640
642
|
path = '/src/' + path
|
|
641
|
-
} else if (path.startsWith('src')) {
|
|
643
|
+
} else if (path.startsWith('src') || path.startsWith('public')) {
|
|
642
644
|
path = '/' + path
|
|
643
645
|
}
|
|
646
|
+
console.log(path)
|
|
644
647
|
path = path.replaceAll('.jsx', '.js');
|
|
645
648
|
|
|
646
649
|
|
|
@@ -678,6 +681,7 @@ let exec = await import('child_process').then((child) => {
|
|
|
678
681
|
return child.exec
|
|
679
682
|
})
|
|
680
683
|
globalThis.isBuilding = false
|
|
684
|
+
globalThis.isWriting = null
|
|
681
685
|
async function Build() {
|
|
682
686
|
globalThis.isBuilding = true
|
|
683
687
|
console.log('Compiling......')
|
|
@@ -685,14 +689,20 @@ async function Build() {
|
|
|
685
689
|
let text = await fs.readFileSync(file, "utf8");
|
|
686
690
|
return text;
|
|
687
691
|
};
|
|
692
|
+
|
|
688
693
|
let writer = async (file, data) => {
|
|
694
|
+
globalThis.isWriting = file
|
|
689
695
|
switch (true) {
|
|
690
696
|
case !fs.existsSync(file):
|
|
691
697
|
fs.mkdirSync(file.split('/').slice(0, -1).join('/'), { recursive: true })
|
|
692
698
|
break;
|
|
693
699
|
}
|
|
694
|
-
|
|
700
|
+
if(globalThis.isWriting !== file){
|
|
701
|
+
return
|
|
702
|
+
}
|
|
703
|
+
await fs.writeFileSync(file, data);
|
|
695
704
|
|
|
705
|
+
globalThis.isWriting = null
|
|
696
706
|
return { _written: true };
|
|
697
707
|
};
|
|
698
708
|
|