@lmjs/cli 2.7.0 → 2.8.1

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/dist/lib/fcs.js CHANGED
@@ -7,5 +7,5 @@ var _vcData = {
7
7
  };
8
8
  `;try{let _indexJsSrc=_hasOwnDeps?_npmBundle.buildEntryWithImports(projectPath+path.sep+"src"+path.sep+"index.js",projectPath):String(indexJs);if(_split)vt+=_split.manifestJs;vt+=_compiledScripts+"\n"+compileProjectScript(_indexJsSrc,"index")}catch(e){spinner.fail("Error compiling index.js: "+(e&&e.message?e.message:e));spinner.fail("Build Failed! Fix index.js and try again.");return}indexCode=v1CompatIndexHtml(indexCode);spinner.succeed("Gathering Required Resources").start("Signing & Securing App..");let vaultApis=await _vault.resolveVaultApis(projectPath);let effectiveApis=(config.apis||[]).concat(vaultApis);let baasEntry=(config.apis||[]).find(a=>a&&typeof a.baseURL==="string"&&a.baseURL.indexOf("beaapis.com")>-1);let beajsAppId=baasEntry&&baasEntry.headers&&baasEntry.headers["X-BEA-Application-ID"];let beajsAuth=baasEntry&&baasEntry.headers&&baasEntry.headers["X-BEA-Authorization"];const keyUnset=v=>!v||/^YOUR_/i.test(String(v).trim());let token_="";if(!baasEntry||keyUnset(beajsAppId)||keyUnset(beajsAuth)){spinner.warn("No Roxyon BaaS keys in config.json, so this build has no backend token. The app works as a static site; to use the Roxyon BaaS (data, auth, files), add your app's keys from https://console.roxyon.com to config.json's apis[] and build again.");spinner.start("Signing & Securing App..")}else{let beajsRawRes;try{beajsRawRes=await API.req("https://www.beaapis.com/1/beajs",{data:{apis:JSON.stringify(effectiveApis)}},{"X-BEA-Application-ID":beajsAppId,"X-BEA-Authorization":beajsAuth},"POST",void 0,true)}catch(e){spinner.fail("Error getting a unique token for production! "+(e&&e.message?e.message:e));spinner.fail("Build Failed! Try again later.");return}if(!beajsRawRes.ok){spinner.fail("Error getting a unique token for production! HTTP "+beajsRawRes.status+(beajsRawRes.status===401||beajsRawRes.status===403?" (the Roxyon BaaS keys in config.json were rejected: check them in https://console.roxyon.com)":""));spinner.fail("Build Failed!");return}let r={};try{r=JSON.parse(await beajsRawRes.text())}catch(e){r={}}token_=r.token;if(!token_){spinner.fail("Error getting a unique token for production!");spinner.fail("Build Failed! Try again later.");return}}let _tokenJs=`
9
9
  var _beaTn = "`+token_+`";
10
- `+(token_?"":"var _lmStatic = true;\n");let _runtimeCode=_uncompiledScripts===0?stripDevOnlyRuntime(ownRuntime):ownRuntime;let js_=_runtimePlan?vt:_tokenJs+_runtimeCode+"\n"+vt;spinner.succeed("Signing & Securing App").start("Packing & Cleaning...");rd(dest);spinner.succeed("Packing & Cleaning").start("Writing Files...");let buildPath=`build_serverless`;copyDir(`${__dirname}`+path.sep+`files`+path.sep+buildPath,dest);copyDir(projectPath+path.sep+"src",dest,"_beajsBuild");cd(dest+path.sep+"js");cd(dest+path.sep+"css");cd(dest+path.sep+"images");copyDir(projectPath+path.sep+"src"+path.sep+"js",dest+path.sep+"js","_beajsBuild");copyDir(projectPath+path.sep+"src"+path.sep+"css",dest+path.sep+"css","_beajsBuild");copyDir(projectPath+path.sep+"src"+path.sep+"images",dest+path.sep+"images","_beajsBuild");fs.writeFileSync(dest+path.sep+"js"+path.sep+"lm.js",String(js_));let _dT=new Date().getTime();if(_runtimePlan){let _rtDir=dest+path.sep+"js"+path.sep+"lumenjs"+path.sep+_runtimePlan.version;fs.mkdirSync(_rtDir,{recursive:true});fs.writeFileSync(_rtDir+path.sep+_runtimePlan.file,_runtimePlan.code)}if(_split){for(const rel in _split.files){let _f=dest+path.sep+rel.split("/").join(path.sep);fs.mkdirSync(path.dirname(_f),{recursive:true});fs.writeFileSync(_f,_split.files[rel])}}fs.renameSync(dest+path.sep+"js"+path.sep+"lm.js",dest+path.sep+"js"+path.sep+"app."+_dT+".js");if(!fs.existsSync(dest+path.sep+"css"))fs.mkdirSync(dest+path.sep+"css",{recursive:true});let _cssAppFile="app."+_cdnRt.shortHash(String(beaCSSCode))+".css";let _stylesFile="styles.css";if(_mainCssName){let _copied=dest+path.sep+"css"+path.sep+_mainCssName;if(fs.existsSync(_copied))fs.unlinkSync(_copied);fs.writeFileSync(dest+path.sep+"css"+path.sep+_cssAppFile,String(beaCSSCode))}let _hasStyles=fs.existsSync(dest+path.sep+"css"+path.sep+"styles.css");if(_hasStyles){_stylesFile="styles."+_cdnRt.shortHash(fs.readFileSync(dest+path.sep+"css"+path.sep+"styles.css","utf8"))+".css";fs.renameSync(dest+path.sep+"css"+path.sep+"styles.css",dest+path.sep+"css"+path.sep+_stylesFile)}let _selectedPlugins=selectedProjectPlugins(projectPath);let _pluginsTags="";let _pluginsCssTag="";if(_selectedPlugins.length){let _pluginsJs=await _pluginsBundle.buildSelectedPluginsBundle(_selectedPlugins,projectPath,{minify:true});let _pluginsCss=await _pluginsBundle.buildSelectedCss(_selectedPlugins,projectPath+path.sep+"node_modules");let _pjs="plugins."+_cdnRt.shortHash(String(_pluginsJs))+".js";fs.writeFileSync(dest+path.sep+"js"+path.sep+_pjs,String(_pluginsJs));_pluginsTags+=`
10
+ `+(token_?"":"var _lmStatic = true;\n");let _runtimeCode=_uncompiledScripts===0?stripDevOnlyRuntime(ownRuntime):ownRuntime;let js_=_runtimePlan?vt:_tokenJs+_runtimeCode+"\n"+vt;spinner.succeed("Signing & Securing App").start("Packing & Cleaning...");rd(dest);spinner.succeed("Packing & Cleaning").start("Writing Files...");let buildPath=`build_serverless`;copyDir(`${__dirname}`+path.sep+`files`+path.sep+buildPath,dest);copyDir(projectPath+path.sep+"src",dest,"_beajsBuild");try{const _seo=require("./seo-files.js").writeSeoFiles(projectPath,dest,config);if(!_seo.site)spinner.info('No site address (config.json "domain" or project_info.WebsiteURL): robots.txt has no Sitemap line and no sitemap.xml was made.');spinner.start("Writing Files...")}catch(e){spinner.warn("SEO files were not written: "+(e&&e.message?e.message:e));spinner.start("Writing Files...")}cd(dest+path.sep+"js");cd(dest+path.sep+"css");cd(dest+path.sep+"images");copyDir(projectPath+path.sep+"src"+path.sep+"js",dest+path.sep+"js","_beajsBuild");copyDir(projectPath+path.sep+"src"+path.sep+"css",dest+path.sep+"css","_beajsBuild");copyDir(projectPath+path.sep+"src"+path.sep+"images",dest+path.sep+"images","_beajsBuild");fs.writeFileSync(dest+path.sep+"js"+path.sep+"lm.js",String(js_));let _dT=new Date().getTime();if(_runtimePlan){let _rtDir=dest+path.sep+"js"+path.sep+"lumenjs"+path.sep+_runtimePlan.version;fs.mkdirSync(_rtDir,{recursive:true});fs.writeFileSync(_rtDir+path.sep+_runtimePlan.file,_runtimePlan.code)}if(_split){for(const rel in _split.files){let _f=dest+path.sep+rel.split("/").join(path.sep);fs.mkdirSync(path.dirname(_f),{recursive:true});fs.writeFileSync(_f,_split.files[rel])}}fs.renameSync(dest+path.sep+"js"+path.sep+"lm.js",dest+path.sep+"js"+path.sep+"app."+_dT+".js");if(!fs.existsSync(dest+path.sep+"css"))fs.mkdirSync(dest+path.sep+"css",{recursive:true});let _cssAppFile="app."+_cdnRt.shortHash(String(beaCSSCode))+".css";let _stylesFile="styles.css";if(_mainCssName){let _copied=dest+path.sep+"css"+path.sep+_mainCssName;if(fs.existsSync(_copied))fs.unlinkSync(_copied);fs.writeFileSync(dest+path.sep+"css"+path.sep+_cssAppFile,String(beaCSSCode))}let _hasStyles=fs.existsSync(dest+path.sep+"css"+path.sep+"styles.css");if(_hasStyles){_stylesFile="styles."+_cdnRt.shortHash(fs.readFileSync(dest+path.sep+"css"+path.sep+"styles.css","utf8"))+".css";fs.renameSync(dest+path.sep+"css"+path.sep+"styles.css",dest+path.sep+"css"+path.sep+_stylesFile)}let _selectedPlugins=selectedProjectPlugins(projectPath);let _pluginsTags="";let _pluginsCssTag="";if(_selectedPlugins.length){let _pluginsJs=await _pluginsBundle.buildSelectedPluginsBundle(_selectedPlugins,projectPath,{minify:true});let _pluginsCss=await _pluginsBundle.buildSelectedCss(_selectedPlugins,projectPath+path.sep+"node_modules");let _pjs="plugins."+_cdnRt.shortHash(String(_pluginsJs))+".js";fs.writeFileSync(dest+path.sep+"js"+path.sep+_pjs,String(_pluginsJs));_pluginsTags+=`
11
11
  <script src="/js/`+_pjs+`" type="text/javascript"><\/script>`;if(_pluginsCss&&_pluginsCss.trim()!=""){let _pcss="plugins."+_cdnRt.shortHash(String(_pluginsCss))+".css";fs.writeFileSync(dest+path.sep+"css"+path.sep+_pcss,String(_pluginsCss));_pluginsCssTag=`<link href="/css/`+_pcss+`" rel="stylesheet" type="text/css" />`}}if(_split&&_split.routes){indexCode=String(indexCode).split("</head>").join(" "+_cdnRt.routePreload(_split.routes)+"\n</head>")}if(_runtimePlan){const _lmTag=/<script\b[^>]*\bsrc=["']\/?js\/lm\.js["'][^>]*>\s*<\/script>/i;if(_lmTag.test(indexCode)){const _tags=_cdnRt.runtimeTags(_runtimePlan,_tokenJs,"/js/app."+_dT+".js");indexCode=String(indexCode).replace(_lmTag,()=>_tags).split("</head>").join(" "+_cdnRt.preconnectTag()+"\n</head>")}else{fs.writeFileSync(dest+path.sep+"js"+path.sep+"app."+_dT+".js",_tokenJs+_runtimeCode+"\n"+vt);fs.rmSync(dest+path.sep+"js"+path.sep+"lumenjs",{recursive:true,force:true});_runtimePlan=null}}let _indexOut=String(indexCode).split("/js/lm.js").join("/js/app."+_dT+".js").split("/css/styles.css").join("/css/"+_stylesFile).split("/css/"+(_mainCssName||"mobius.css")).join(_mainCssName?"/css/"+_cssAppFile:"/css/mobius.css").split("</head>").join(_pluginsTags+"\n</head>");if(_pluginsCssTag)_indexOut=placePluginsCss(_indexOut,_pluginsCssTag);fs.writeFileSync(dest+path.sep+"index.html",_indexOut);if(cmds.indexOf("--deploy")>=0){spinner.succeed("Writing Files").start("Uploading To Server..");const _config={user:config.ftp.username,password:config.ftp.password,host:config.ftp.host,port:config.ftp.port,localRoot:dest,remoteRoot:config.ftp.remotePath,include:["*","**/*",".*"],exclude:config.ftp.ignore,deleteRemote:false,forcePasv:true,sftp:config.ftp.protocol=="sftp"?true:false};_fD.deploy(_config,function(err,res){if(err){console.log(err)}else{spinner.succeed("Finished Uploading To Server");spinner.succeed("Done")}});_fD.on("uploading",function(data){spinner.start(parseFloat((data.transferredFileCount*100/data.totalFilesCount).toFixed(2))+"% Uploading "+data.filename+" ")})}else spinner.succeed("Writing Files").succeed("Done")})}function clear(isSoft){process.stdout.write(isSoft?"\x1B[H\x1B[2J":"\x1B[2J\x1B[3J\x1B[H\x1Bc")}function startServer(){clear();if(!process.env.LM_COPILOT_TOKEN)process.env.LM_COPILOT_TOKEN=require("crypto").randomBytes(24).toString("hex");if(!process.env.LM_COPILOT_AUTO)process.env.LM_COPILOT_AUTO=process.stdout.isTTY&&!process.env.CI?"1":"0";nodemon({script:path.join(__dirname.toString(),"app.js"),ext:"view,js,css,json,layout,html",watch:["src/","config.json"],ignore:["src/views/**","src/layouts/**"]});nodemon.on("restart",files2=>{console.log(files2)})}
@@ -1,4 +1,2 @@
1
- Sitemap: https://www.lumenjs.com/sitemap.xml
2
-
3
1
  User-agent: *
4
- Disallow:
2
+ Allow: /
@@ -28,7 +28,7 @@ var cl=console.log;var LumenJS_HTML_SNIFF_RE=/([&][a-zA-Z]*[;]+)|<\/?[a-z][\s\S]
28
28
 
29
29
  var _reactiveEngines=[];var _rxMoustache=/\{\s*\{\s*([\s\S]*?)\s*\}\s*\}/g;var _rxVoid={area:1,base:1,basefont:1,bgsound:1,br:1,col:1,command:1,embed:1,frame:1,hr:1,image:1,img:1,input:1,isindex:1,keygen:1,link:1,menuitem:1,meta:1,nextid:1,param:1,source:1,track:1,wbr:1};var _rxSkip={};"break case catch class const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield await async of static get set null true false undefined NaN Infinity Object Function Boolean Symbol Error Number BigInt Math Date String RegExp Array Map Set WeakMap WeakSet Promise Reflect Proxy Intl JSON console window document navigator location localStorage sessionStorage fetch setTimeout clearTimeout setInterval clearInterval parseInt parseFloat isFinite isNaN encodeURI decodeURI encodeURIComponent decodeURIComponent escape unescape globalThis".split(" ").forEach(function(w){_rxSkip[w]=1});var _rxExprCache=new Map;function _rxKeepOneSpace(t){t=t.replace(/\s\s/gm," ");if(/\s\s/gm.test(t))return _rxKeepOneSpace(t);return t}function _rxClean(t){t=t.replace(/(\r?\n|\r)/gm,"");t=t.replace(/(\t)/gm,"");t=_rxKeepOneSpace(t);return t.replace(/^(?:\s*\t*\r*\n*\{*)+|(?:\s*\t*\r*\n*\})+$/g,"").trim()}function _rxIdents(src,out){var i=0,n=src.length,prev="";function skipTemplate(){i++;while(i<n){var c=src[i];if(c==="\\"){i+=2;continue}if(c==="`"){i++;return}if(c==="$"&&src[i+1]==="{"){i+=2;var depth=1,start=i;while(i<n&&depth){var d=src[i];if(d==="`"){var s=i;skipTemplate();continue}if(d==="{")depth++;else if(d==="}"){depth--;if(!depth)break}else if(d==="'"||d==='"'){var q=d;i++;while(i<n&&src[i]!==q){if(src[i]==="\\")i++;i++}}i++}_rxIdents(src.slice(start,i),out);i++;continue}i++}}while(i<n){var ch=src[i];if(ch==="'"||ch==='"'){i++;while(i<n&&src[i]!==ch){if(src[i]==="\\")i++;i++}i++;prev="s";continue}if(ch==="`"){skipTemplate();prev="s";continue}if(ch==="/"&&src[i+1]==="/"){while(i<n&&src[i]!=="\n")i++;continue}if(ch==="/"&&src[i+1]==="*"){var e=src.indexOf("*/",i+2);i=e<0?n:e+2;continue}if(/\s/.test(ch)){i++;continue}if(/[0-9]/.test(ch)){while(i<n&&/[\w.]/.test(src[i]))i++;prev="n";continue}if(/[A-Za-z_$]/.test(ch)){var st=i;while(i<n&&/[\w$]/.test(src[i]))i++;var id=src.slice(st,i);var j=i;while(j<n&&/\s/.test(src[j]))j++;var isKey=src[j]===":"&&(prev==="{"||prev===",");if(prev!=="."&&!isKey&&!_rxSkip[id]&&out.indexOf(id)===-1)out.push(id);prev="i";continue}prev=ch;i++}return out}function _rxExpr(mux){var hit=_rxExprCache.get(mux);if(hit)return hit;var rv=null;try{new Function(mux);rv=_rxIdents(mux,[])}catch(e){rv=null}if(_rxExprCache.size>2e3)_rxExprCache.clear();_rxExprCache.set(mux,rv);return rv}function _rxEscape(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function _rxMustaches(text,escapeStatic,rvSet){var found=[],m,last=0;_rxMoustache.lastIndex=0;while((m=_rxMoustache.exec(text))!=null){var mux=_rxClean(m[0]);var rvs=_rxExpr(mux);if(rvs)found.push({index:m.index,len:m[0].length,mux,rvs})}if(!found.length)return{content:escapeStatic?_rxEscape(text):text,mss:[]};var esc=escapeStatic?_rxEscape:function(s){return s};var content="",mss=[];for(var k=0;k<found.length;k++){var f=found[k];content+=esc(text.substring(last,f.index));var start=content.length;content+="{{"+f.mux+"}}";mss.push({mus:f.mux,jst:null,rvs:f.rvs.slice(),start,end:content.length});for(var r=0;r<f.rvs.length;r++)rvSet[f.rvs[r]]=1;last=f.index+f.len}content+=esc(text.substring(last));return{content,mss}}function _rxForX(val){var forX={js:"",as:{k:"",v:""},dx:""};val=val.trim();if(val.indexOf(";")>-1){var zxx=val.split(";");forX.dx=zxx[1].trim();val=zxx[0].trim()}if(val.indexOf(" as ")>-1){var arr2=val.split(" as ");var arr3=arr2[1].split(" ").join("").split(",");forX.as.k=arr3[0].trim();if(arr3.length>1)forX.as.v=arr3[1].trim();val=arr2[0].trim()}forX.js=val.trim();return forX}function _rxCompileNode(n,ptag,rvSet){if(n.nodeType===3){var t=n.nodeValue;var mm=_rxMustaches(t,ptag!=="style",rvSet);if(ptag==="textarea"&&mm.mss.length)mm=_rxMustaches(t,false,rvSet);return{type:"text",content:mm.content,mss:mm.mss,tag:ptag}}if(n.nodeType!==1)return null;var name=n.localName;if(name==="script")return null;var res={type:"tag",name,isV:!!_rxVoid[name],attrs:{},ax:{},evs:{},ex:{},children:[]};if(n.namespaceURI==="http://www.w3.org/2000/svg")res.svg=true;var attrs=n.attributes;for(var a=0;a<attrs.length;a++){var an=attrs[a].name,av=attrs[a].value;if(an===":else"){res.type="section";res.cond=""}else if(an===":if"||an===":else-if"){res.type="section";res.cond=av;_rxIdents(av,[]).forEach(function(id){rvSet[id]=1})}else if(an===":for"){res.type="sections";res.content=av;res.forX=_rxForX(av);if(res.forX.js)_rxIdents(res.forX.js,[]).forEach(function(id){rvSet[id]=1})}var ms=_rxMustaches(an.charAt(0)==="@"?av:av.replace(/`(\{\s*\{[\s\S]*?\}\s*\})`/g,"$1"),false,rvSet);if(an.charAt(0)==="@"){res.evs[an]=ms.content;if(ms.mss.length)res.ex[an]=ms.mss}else{res.attrs[an]=ms.content;if(ms.mss.length)res.ax[an]=ms.mss}}_rxOrderIfFor(res);if(!res.isV){var kids=n.childNodes;for(var c=0;c<kids.length;c++){var ch=_rxCompileNode(kids[c],name,rvSet);if(ch)res.children.push(ch)}if(name==="style"&&!res.children.length)res.children.push({type:"text",content:"",mss:[],tag:"style"})}return res}function _rxOrderIfFor(res){if(!res||!res.attrs||!res.forX||!Object.prototype.hasOwnProperty.call(res.attrs,":if"))return;var keys=Object.keys(res.attrs);var cond=String(res.attrs[":if"]);if(keys.indexOf(":if")<keys.indexOf(":for"))res.forX.js="("+cond+") ? ("+res.forX.js+") : []";else res.attrs[":for-if"]=res.attrs[":for-if"]?"("+res.attrs[":for-if"]+") && ("+cond+")":cond;res.type="sections";delete res.cond;delete res.attrs[":if"];if(res.ax)delete res.ax[":if"]}function _rxCompileHost(host){var rvSet={},hst=[],kids=host.childNodes;for(var i=0;i<kids.length;i++){var c=_rxCompileNode(kids[i],host.localName,rvSet);if(c)hst.push(c)}return{hst,reactiveVars:Object.keys(rvSet)}}async function _rxRender(host){host.classList.add("binded");var compiled=_rxCompileHost(host);var sub=null;for(var p=host.parentNode;p;p=p.parentNode){if(p.isSub===true){sub=p;break}}var _re=await renderHST(compiled,"reactive","section",void 0,null,["View"],sub?sub.vars:void 0,sub?sub.fns:void 0);_re._blankUnresolved=true;var bindEl=host.closest("[bind]");if(bindEl){String(bindEl.getAttribute("bind")||"").split(",").forEach(function(v){var parts=v.trim().split(" as ");if(parts.length===2&&parts[0].trim()&&parts[1].trim()){try{_re.vrs[parts[1].trim()]=_re.scopedEval(_re.reactiveVariables,parts[0].trim())}catch(e){}}})}host.textContent="";host.append.apply(host,_re._RealDOM);_re._rxHost=host;_reactiveEngines.push(_re);_re.renderAll("section")}function _updateReactiveEngines(varName){for(var i=_reactiveEngines.length-1;i>=0;i--){var re=_reactiveEngines[i];if(!re._rxHost||!re._rxHost.isConnected){_reactiveEngines.splice(i,1);continue}try{re.update(varName)}catch(e){cl(e)}}}(function(){if(typeof MutationObserver==="undefined"||typeof document==="undefined"||!document.documentElement)return;var pending=[],running=false;function consider(node){if(!node||node.nodeType!==1||node._ownerRe)return;if(node.hasAttribute("reactive"))pending.push(node);if(node.firstElementChild){var found=node.querySelectorAll("[reactive]");for(var i=0;i<found.length;i++)pending.push(found[i])}}async function drain(){if(running)return;running=true;var rendered=0;try{while(pending.length){var h=pending.shift();if(!h.isConnected||h._ownerRe||h.classList.contains("binded"))continue;try{await _rxRender(h);rendered++}catch(e){reportLumenError({stage:"reactive",error:e})}}}finally{running=false}if(rendered&&typeof globalWatch==="function"){try{globalWatch()}catch(e){reportLumenError({stage:"reactive",error:e})}}}new MutationObserver(function(records){for(var r=0;r<records.length;r++){var added=records[r].addedNodes;for(var k=0;k<added.length;k++)consider(added[k])}if(pending.length)drain()}).observe(document.documentElement,{childList:true,subtree:true});function scan(){consider(document.documentElement);if(pending.length)drain()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",scan);else setTimeout(scan,0)})();
30
30
 
31
- var LM_BUILD=(function(){try{var m=/\/js\/app\.(\d+)\.js/.exec(document.currentScript&&document.currentScript.src||(function(){var s=document.querySelectorAll('script[src*="/js/app."]');return s.length?s[s.length-1].src:""})());return m?parseInt(m[1],10):0}catch(e){return 0}})();var LM_VERSION=(function(){if(!LM_BUILD)return"dev";var d=new Date(LM_BUILD);var p=function(n){return(n<10?"0":"")+n};return d.getUTCFullYear()+"."+p(d.getUTCMonth()+1)+"."+p(d.getUTCDate())+"."+p(d.getUTCHours())+p(d.getUTCMinutes())})();var _lmUpdateShown=false;function _lmUpdateOpts(){var o=typeof appSettings!=="undefined"&&appSettings?appSettings.updateCheck:void 0;if(o===false)return null;return o&&typeof o==="object"?o:{}}function _lmShowUpdateBar(opts,latest){if(_lmUpdateShown)return;_lmUpdateShown=true;var reload=function(){var done=false;var go2=function(){if(!done){done=true;location.reload()}};setTimeout(go2,4e3);try{fetch(location.href,{cache:"reload",credentials:"same-origin"}).then(go2,go2)}catch(e){go2()}};if(typeof opts.onUpdate==="function"){try{opts.onUpdate({current:LM_BUILD,latest,reload})}catch(e){cl(e)}return}if(!document.getElementById("lm-update-style")){var st=document.createElement("style");st.id="lm-update-style";st.textContent=".lm-update-bar{position:fixed;left:50%;bottom:22px;transform:translateX(-50%);z-index:100001;display:flex;align-items:center;gap:14px;max-width:calc(100vw - 32px);padding:10px 12px 10px 18px;background:var(--color-card-background,#1c1c1e);border:1px solid var(--color-border--dark,#333);border-radius:12px;box-shadow:0 16px 40px -10px rgba(0,0,0,.55);color:var(--color-text,#e8e8e8);font-size:13px;font-family:inherit}.lm-update-go{background:#e5484d;color:#fff;border:0;border-radius:8px;padding:6px 14px;font-weight:700;cursor:pointer;font-size:13px}.lm-update-x{background:none;border:0;color:#8a8a8a;font-size:18px;line-height:1;cursor:pointer;padding:2px 4px}.lm-update-x:hover{color:var(--color-text,#e8e8e8)}";document.head.appendChild(st)}var bar=document.createElement("div");bar.className="lm-update-bar";bar.setAttribute("role","status");var msg=document.createElement("span");msg.textContent=opts.message||"A new version is available.";var go=document.createElement("button");go.type="button";go.className="lm-update-go";go.textContent=opts.buttonText||"Reload";go.onclick=reload;var x=document.createElement("button");x.type="button";x.className="lm-update-x";x.setAttribute("aria-label","Dismiss");x.textContent="\xD7";x.onclick=function(){if(bar.parentNode)bar.parentNode.removeChild(bar)};bar.appendChild(msg);bar.appendChild(go);bar.appendChild(x);document.body.appendChild(bar)}function _lmAssetSig(html){var out=[];var re=/<(?:script|link)\b[^>]*?\b(?:src|href)\s*=\s*["']([^"']+)["'][^>]*>/gi,m;while(m=re.exec(html||"")){var u=m[1];if(/^(?:https?:)?\/\//i.test(u)||/^(?:data|blob|mailto):/i.test(u))continue;if(/\.(?:js|mjs|css)(?:[?#]|$)/i.test(u))out.push(u)}var b=/<meta\b[^>]*name\s*=\s*["']lm-build["'][^>]*content\s*=\s*["']([^"']*)["']/i.exec(html||"")||/<meta\b[^>]*content\s*=\s*["']([^"']*)["'][^>]*name\s*=\s*["']lm-build["']/i.exec(html||"");if(b)out.push("lm-build="+b[1]);return out.sort().join("|")}var _lmBaseSig=null;function lmCheckForUpdate(){var opts=_lmUpdateOpts();if(!opts||!LM_BUILD||_lmUpdateShown||typeof fetch!=="function")return Promise.resolve(false);var url=opts.url||"/";return fetch(url+(url.indexOf("?")>-1?"&":"?")+"_v="+Date.now(),{cache:"no-store",credentials:"same-origin"}).then(function(r){return r.ok?r.text():""}).then(function(html){if(!html)return false;var m=/\/js\/app\.(\d+)\.js/.exec(html);var latest=m?parseInt(m[1],10):0;if(latest>LM_BUILD){_lmShowUpdateBar(opts,latest);return true}var sig=_lmAssetSig(html);if(_lmBaseSig===null)_lmBaseSig=sig;if(latest===LM_BUILD&&sig!==_lmBaseSig){_lmShowUpdateBar(opts,latest);return true}return false}).catch(function(){return false})}(function(){if(!LM_BUILD)return;document.addEventListener("visibilitychange",function(){if(document.visibilityState==="visible")lmCheckForUpdate()});setTimeout(function(){lmCheckForUpdate();var o=_lmUpdateOpts();var every=o&&o.interval>0?o.interval:5*60*1e3;if(o)setInterval(lmCheckForUpdate,every)},15e3)})();
31
+ var LM_BUILD=0;var LM_VERSION="dev";var _lmBuildCache=0;function _lmVersionOf(build){var d=new Date(build);var p=function(n){return(n<10?"0":"")+n};return d.getUTCFullYear()+"."+p(d.getUTCMonth()+1)+"."+p(d.getUTCDate())+"."+p(d.getUTCHours())+p(d.getUTCMinutes())}function lmBuildStamp(){if(_lmBuildCache)return _lmBuildCache;try{var m=/\/js\/app\.(\d+)\.js/.exec(document.currentScript&&document.currentScript.src||(function(){var s=document.querySelectorAll('script[src*="/js/app."]');return s.length?s[s.length-1].src:""})());_lmBuildCache=m&&parseInt(m[1],10)||0}catch(e){_lmBuildCache=0}if(_lmBuildCache){LM_BUILD=_lmBuildCache;LM_VERSION=_lmVersionOf(_lmBuildCache)}return _lmBuildCache}var _lmUpdateShown=false;function _lmUpdateOpts(){var o=typeof appSettings!=="undefined"&&appSettings?appSettings.updateCheck:void 0;if(o===false)return null;return o&&typeof o==="object"?o:{}}function _lmShowUpdateBar(opts,latest){if(_lmUpdateShown)return;_lmUpdateShown=true;var reload=function(){var done=false;var go2=function(){if(!done){done=true;location.reload()}};setTimeout(go2,4e3);try{fetch(location.href,{cache:"reload",credentials:"same-origin"}).then(go2,go2)}catch(e){go2()}};if(typeof opts.onUpdate==="function"){try{opts.onUpdate({current:lmBuildStamp(),latest,reload})}catch(e){cl(e)}return}if(!document.getElementById("lm-update-style")){var st=document.createElement("style");st.id="lm-update-style";st.textContent=".lm-update-bar{position:fixed;left:50%;bottom:22px;transform:translateX(-50%);z-index:100001;display:flex;align-items:center;gap:14px;max-width:calc(100vw - 32px);padding:10px 12px 10px 18px;background:var(--color-card-background,#1c1c1e);border:1px solid var(--color-border--dark,#333);border-radius:12px;box-shadow:0 16px 40px -10px rgba(0,0,0,.55);color:var(--color-text,#e8e8e8);font-size:13px;font-family:inherit}.lm-update-go{background:#e5484d;color:#fff;border:0;border-radius:8px;padding:6px 14px;font-weight:700;cursor:pointer;font-size:13px}.lm-update-x{background:none;border:0;color:#8a8a8a;font-size:18px;line-height:1;cursor:pointer;padding:2px 4px}.lm-update-x:hover{color:var(--color-text,#e8e8e8)}";document.head.appendChild(st)}var bar=document.createElement("div");bar.className="lm-update-bar";bar.setAttribute("role","status");var msg=document.createElement("span");msg.textContent=opts.message||"A new version is available.";var go=document.createElement("button");go.type="button";go.className="lm-update-go";go.textContent=opts.buttonText||"Reload";go.onclick=reload;var x=document.createElement("button");x.type="button";x.className="lm-update-x";x.setAttribute("aria-label","Dismiss");x.textContent="\xD7";x.onclick=function(){if(bar.parentNode)bar.parentNode.removeChild(bar)};bar.appendChild(msg);bar.appendChild(go);bar.appendChild(x);document.body.appendChild(bar)}function _lmAssetSig(html){var out=[];var re=/<(?:script|link)\b[^>]*?\b(?:src|href)\s*=\s*["']([^"']+)["'][^>]*>/gi,m;while(m=re.exec(html||"")){var u=m[1];if(/^(?:https?:)?\/\//i.test(u)||/^(?:data|blob|mailto):/i.test(u))continue;if(/\.(?:js|mjs|css)(?:[?#]|$)/i.test(u))out.push(u)}var b=/<meta\b[^>]*name\s*=\s*["']lm-build["'][^>]*content\s*=\s*["']([^"']*)["']/i.exec(html||"")||/<meta\b[^>]*content\s*=\s*["']([^"']*)["'][^>]*name\s*=\s*["']lm-build["']/i.exec(html||"");if(b)out.push("lm-build="+b[1]);return out.sort().join("|")}var _lmBaseSig=null;function lmCheckForUpdate(){var build=lmBuildStamp();var opts=_lmUpdateOpts();if(!opts||!build||_lmUpdateShown||typeof fetch!=="function")return Promise.resolve(false);var url=opts.url||"/";return fetch(url+(url.indexOf("?")>-1?"&":"?")+"_v="+Date.now(),{cache:"no-store",credentials:"same-origin"}).then(function(r){return r.ok?r.text():""}).then(function(html){if(!html)return false;var m=/\/js\/app\.(\d+)\.js/.exec(html);var latest=m?parseInt(m[1],10):0;if(latest>build){_lmShowUpdateBar(opts,latest);return true}var sig=_lmAssetSig(html);if(_lmBaseSig===null)_lmBaseSig=sig;if(latest===build&&sig!==_lmBaseSig){_lmShowUpdateBar(opts,latest);return true}return false}).catch(function(){return false})}(function(){function start(){lmBuildStamp();document.addEventListener("visibilitychange",function(){if(document.visibilityState==="visible")lmCheckForUpdate()});var opts=_lmUpdateOpts();if(!opts)return;var first=opts.firstCheckMs>0?opts.firstCheckMs:15e3;var tries=0;function tick(){var o=_lmUpdateOpts();if(!o)return;if(!lmBuildStamp()){tries+=1;if(tries<20)setTimeout(tick,first);return}lmCheckForUpdate();var every=o.interval>0?o.interval:5*60*1e3;setInterval(lmCheckForUpdate,every)}setTimeout(tick,first)}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()})();
32
32
 
33
33
  !(function(a,b){"function"==typeof define&&define.amd?define([],b):"undefined"!=typeof module&&module.exports?module.exports=b():a.ReconnectingWebSocket=b()})(this,function(){function a(b,c,d){function l(a2,b2){var c2=document.createEvent("CustomEvent");return c2.initCustomEvent(a2,false,false,b2),c2}var e={debug:false,automaticOpen:true,reconnectInterval:1e3,maxReconnectInterval:3e4,reconnectDecay:1,timeoutInterval:3e3};d||(d={});for(var f in e)this[f]="undefined"!=typeof d[f]?d[f]:e[f];this.url=b,this.reconnectAttempts=0,this.readyState=WebSocket.CONNECTING,this.protocol=null;var h,g=this,i2=false,j=false,k=document.createElement("div");k.addEventListener("open",function(a2){g.onopen(a2)}),k.addEventListener("close",function(a2){g.onclose(a2)}),k.addEventListener("connecting",function(a2){g.onconnecting(a2)}),k.addEventListener("message",function(a2){g.onmessage(a2)}),k.addEventListener("error",function(a2){g.onerror(a2)}),this.addEventListener=k.addEventListener.bind(k),this.removeEventListener=k.removeEventListener.bind(k),this.dispatchEvent=k.dispatchEvent.bind(k),this.open=function(b2){try{h=new WebSocket(g.url,c||[]),b2||k.dispatchEvent(l("connecting")),(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","attempt-connect",g.url);var d2=h,e2=setTimeout(function(){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","connection-timeout",g.url),j=true,j=false;if(d2.readyState==1)d2.close()},g.timeoutInterval);h.onopen=function(){clearTimeout(e2),(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onopen",g.url),g.protocol=h.protocol,g.readyState=WebSocket.OPEN,g.reconnectAttempts=0;var d3=l("open");d3.isReconnect=b2,b2=false,k.dispatchEvent(d3)},h.onclose=function(c2){if(clearTimeout(e3),h=null,i2)g.readyState=WebSocket.CLOSED,k.dispatchEvent(l("close"));else{g.readyState=WebSocket.CONNECTING;var d3=l("connecting");d3.code=c2.code,d3.reason=c2.reason,d3.wasClean=c2.wasClean,k.dispatchEvent(d3),b2||j||((g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onclose",g.url),k.dispatchEvent(l("close")));var e3=g.reconnectInterval*Math.pow(g.reconnectDecay,g.reconnectAttempts);setTimeout(function(){g.reconnectAttempts++,g.open(true)},e3>g.maxReconnectInterval?g.maxReconnectInterval:e3)}},h.onmessage=function(b3){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onmessage",g.url,b3.data);var c2=l("message");c2.data=b3.data,k.dispatchEvent(c2)},h.onerror=function(b3){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onerror",g.url,b3),k.dispatchEvent(l("error"))}}catch(error){console.error("WebSocket connection error:",error)}},1==this.automaticOpen&&this.open(false),this.send=function(b2){if(h)return(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","send",g.url,b2),h.send(b2);throw"INVALID_STATE_ERR : Pausing to reconnect websocket"},this.close=function(a2,b2){"undefined"==typeof a2&&(a2=1e3),i2=true,h&&h.close(a2,b2)},this.refresh=function(){h&&h.readyState==1&&h.close()}}return a.prototype.onopen=function(){},a.prototype.onclose=function(){},a.prototype.onconnecting=function(){},a.prototype.onmessage=function(){},a.prototype.onerror=function(){},a.debugAll=false,a.CONNECTING=WebSocket.CONNECTING,a.OPEN=WebSocket.OPEN,a.CLOSING=WebSocket.CLOSING,a.CLOSED=WebSocket.CLOSED,a});let _isTipped=false;var _debugMode=false;var _initialized=null;var _dbcrs={};var _dbcrsTime=200;var _tickTime=20;var _scW=0;var cl=console.log;if(!_vcData)var _vcData=void 0;if(!_beaTn)var _beaTn=void 0;var beas;var appSettings;var execEl="";var currentlyValidTags=new Array;var _upwrk=new WebWorker("_upw");var _csswrk=new WebWorker("_cssw");_csswrk.start();var _ups=[];(function(e,t2){typeof module!="undefined"&&module.exports?module.exports=t2():typeof define=="function"&&define.amd?define(t2):this[e]=t2()})("bea",function(){function p(e2,t3){for(var n3=0,i3=e2.length;n3<i3;++n3)if(!t3(e2[n3]))return r2;return 1}function d(e2,t3){p(e2,function(e3){return t3(e3),1})}function v(e2,t3,n3){function g(e3){return e3.call?e3():u[e3]}function y(){if(!--h2){u[o2]=1,s2&&s2();for(var e3 in f)p(e3.split("|"),g)&&!d(f[e3],g)&&(f[e3]=[])}}e2=e2[i2]?e2:[e2];var r3=t3&&t3.call,s2=r3?t3:n3,o2=r3?e2.join(""):t3,h2=e2.length;return setTimeout(function(){d(e2,function t4(e3,n4){if(e3===null)return y();/*!n &&
34
34
  !/^https?:\/\//.test(e) &&
@@ -0,0 +1,200 @@
1
+ <?php
2
+ // LumenJS: the page search engines and link previews get (WhatsApp, Facebook, LinkedIn, X, Telegram, Google, Bing...).
3
+ // Written by `lm build` when the project has no seo.php of its own. On Roxyon hosting the router sends known crawlers
4
+ // here (Domains.SiteOptions.seo_prerender); visitors get index.html. Settings: seo.json next to this file (made by the
5
+ // build from config.json's project_info, the views and the project's own src/seo.json). A route can read its item
6
+ // from Roxyon Base with the site's publishable key (public read rules only), cached a few minutes.
7
+ declare(strict_types=1);
8
+
9
+ $cfg = json_decode((string) @file_get_contents(__DIR__ . '/seo.json'), true);
10
+ $cfg = is_array($cfg) ? $cfg : [];
11
+ $host = preg_replace('/[^a-z0-9.:-]/', '', strtolower((string) ($_SERVER['HTTP_HOST'] ?? 'localhost')));
12
+ $site = rtrim((string) ($cfg['site'] ?? ''), '/') ?: 'https://' . $host;
13
+ $abs = fn (string $u): string => $u === '' ? '' : (preg_match('#^https?://#i', $u) ? $u : $site . '/' . ltrim($u, '/'));
14
+ $name = (string) ($cfg['name'] ?? $host);
15
+ $route = trim((string) ($_GET['__nodes'] ?? ''), '/');
16
+ $parts = $route === '' ? [] : explode('/', $route);
17
+
18
+ /** The route pattern that matches ("product/:id" style), with its params. */
19
+ $match = null;
20
+ $params = [];
21
+ foreach ((array) ($cfg['routes'] ?? []) as $pattern => $r) {
22
+ $pp = trim((string) $pattern, '/');
23
+ $segs = $pp === '' ? [] : explode('/', $pp);
24
+ if (count($segs) !== count($parts)) {
25
+ continue;
26
+ }
27
+ $ok = true;
28
+ $p = [];
29
+ foreach ($segs as $i => $s) {
30
+ if ($s !== '' && $s[0] === ':') {
31
+ $p[substr($s, 1)] = rawurldecode($parts[$i]);
32
+ } elseif (strcasecmp($s, $parts[$i]) !== 0) {
33
+ $ok = false;
34
+ break;
35
+ }
36
+ }
37
+ if ($ok) {
38
+ $match = is_array($r) ? $r : [];
39
+ $params = $p;
40
+ break;
41
+ }
42
+ }
43
+
44
+ function seo_tmp(): string
45
+ {
46
+ $d = dirname(__DIR__) . '/tmp/lm-seo';
47
+ if (!is_dir($d)) {
48
+ @mkdir($d, 0700, true);
49
+ }
50
+ return is_dir($d) && is_writable($d) ? $d : sys_get_temp_dir();
51
+ }
52
+
53
+ function seo_http(string $method, string $url, array $headers, string $origin, ?string $body = null): ?array
54
+ {
55
+ $headers[] = 'Origin: ' . $origin;
56
+ $headers[] = 'X-BEA-Installation-ID: lm-seo';
57
+ $ctx = stream_context_create(['http' => ['method' => $method, 'header' => implode("\r\n", $headers), 'content' => $body ?? '', 'timeout' => 4, 'ignore_errors' => true]]);
58
+ $out = @file_get_contents($url, false, $ctx);
59
+ $d = $out === false ? null : json_decode($out, true);
60
+ return is_array($d) ? $d : null;
61
+ }
62
+
63
+ /** One record for a route that names a Base class: {key, class, field?, base?}; null when not found or not public. */
64
+ function seo_record(array $b, string $value, string $origin): ?array
65
+ {
66
+ $key = (string) ($b['key'] ?? '');
67
+ $class = preg_replace('/[^A-Za-z0-9_]/', '', (string) ($b['class'] ?? ''));
68
+ $field = preg_replace('/[^A-Za-z0-9_]/', '', (string) ($b['field'] ?? 'objectId'));
69
+ $api = rtrim((string) ($b['base'] ?? 'https://www.beaapis.com/2'), '/');
70
+ if ($key === '' || $class === '' || !preg_match('/^[\p{L}\p{N}_.\- ]{1,120}$/u', $value)) {
71
+ return null;
72
+ }
73
+ $f = seo_tmp() . '/r-' . md5($class . '|' . $field . '|' . $value) . '.json';
74
+ if (is_file($f) && filemtime($f) > time() - 300) {
75
+ $c = json_decode((string) @file_get_contents($f), true);
76
+ return is_array($c) && $c ? $c : null;
77
+ }
78
+ $tf = seo_tmp() . '/token-' . md5($key) . '.json';
79
+ $row = null;
80
+ foreach ([false, true] as $fresh) {
81
+ $tok = null;
82
+ if (!$fresh && is_file($tf)) {
83
+ $t = json_decode((string) @file_get_contents($tf), true);
84
+ if (is_array($t) && ($t['until'] ?? 0) > time()) {
85
+ $tok = (string) ($t['token'] ?? '');
86
+ }
87
+ }
88
+ if (!$tok) {
89
+ $d = seo_http('POST', $api . '/auth/public', ['Content-Type: application/json'], $origin, (string) json_encode(['key' => $key]));
90
+ if (empty($d['access_token'])) {
91
+ break;
92
+ }
93
+ $tok = (string) $d['access_token'];
94
+ @file_put_contents($tf, json_encode(['token' => $tok, 'until' => time() + min(3600, (int) ($d['expires_in'] ?? 3600)) - 60]), LOCK_EX);
95
+ @chmod($tf, 0600);
96
+ }
97
+ $q = http_build_query(['limit' => 1, 'media' => 'images', 'where' => json_encode([$field => $value])]);
98
+ $d = seo_http('GET', $api . '/records/' . $class . '?' . $q, ['Authorization: Bearer ' . $tok], $origin);
99
+ if (is_array($d) && !empty($d['ok'])) {
100
+ $row = $d['results'][0] ?? null;
101
+ break;
102
+ }
103
+ }
104
+ @file_put_contents($f, json_encode($row ?: []), LOCK_EX);
105
+ return is_array($row) && $row ? $row : null;
106
+ }
107
+
108
+ /** A record's first photo (product photos first), at 1200 px. */
109
+ function seo_photo(array $row): string
110
+ {
111
+ $all = [];
112
+ foreach ((array) ($row['images'] ?? []) as $g) {
113
+ foreach ((array) $g as $p) {
114
+ if (is_array($p) && !empty($p['dir']) && !empty($p['image'])) {
115
+ $all[] = $p;
116
+ }
117
+ }
118
+ }
119
+ if (!$all) {
120
+ return '';
121
+ }
122
+ usort($all, fn ($a, $b) => (int) !preg_match('/^product/i', (string) ($a['title'] ?? '')) <=> (int) !preg_match('/^product/i', (string) ($b['title'] ?? '')));
123
+ return $all[0]['dir'] . preg_replace('/(\.[a-z0-9]+)$/i', '(1200xa)$1', (string) $all[0]['image']);
124
+ }
125
+
126
+ $fill = function (string $tpl, array $vars): string {
127
+ return trim(preg_replace_callback('/\{(\w+)\}/', fn ($m) => (string) ($vars[$m[1]] ?? ''), $tpl));
128
+ };
129
+ $text = fn ($v): string => trim(preg_replace('/\s+/', ' ', strip_tags(html_entity_decode(is_array($v) ? (string) ($v['en'] ?? reset($v) ?: '') : (string) $v))));
130
+
131
+ $title = (string) ($cfg['title'] ?? $name);
132
+ $desc = (string) ($cfg['description'] ?? '');
133
+ $image = $abs((string) ($cfg['image'] ?? ''));
134
+ $type = 'website';
135
+ $status = 200;
136
+ $body = '';
137
+ if ($match !== null) {
138
+ $vars = $params;
139
+ if (!empty($match['base']) && is_array($match['base'])) {
140
+ $param = (string) ($match['base']['param'] ?? (array_key_first($params) ?? ''));
141
+ $row = $param !== '' && isset($params[$param]) ? seo_record($match['base'], (string) $params[$param], $site) : null;
142
+ if ($row === null) {
143
+ $status = 404;
144
+ } else {
145
+ foreach ($row as $k => $v) {
146
+ if (is_scalar($v) || (is_array($v) && isset($v['en']))) {
147
+ $vars[$k] = $text($v);
148
+ }
149
+ }
150
+ $photo = seo_photo($row);
151
+ if ($photo !== '') {
152
+ $image = $photo;
153
+ }
154
+ }
155
+ }
156
+ if ($status === 200) {
157
+ $title = $fill((string) ($match['title'] ?? $title), $vars) ?: $title;
158
+ $desc = mb_substr($fill((string) ($match['description'] ?? $desc), $vars) ?: $desc, 0, 300);
159
+ if (!empty($match['image']) && !preg_match('/\{/', (string) $match['image'])) {
160
+ $image = $abs((string) $match['image']);
161
+ }
162
+ $type = (string) ($match['type'] ?? $type);
163
+ $body = $fill((string) ($match['body'] ?? ''), $vars);
164
+ }
165
+ } elseif ($route !== '') {
166
+ $status = 404;
167
+ }
168
+ $url = $site . '/' . ($route === '' ? '' : implode('/', array_map('rawurlencode', $parts)));
169
+ http_response_code($status);
170
+ header('Content-Type: text/html; charset=utf-8');
171
+ header('Cache-Control: public, max-age=300');
172
+ $h = fn ($s) => htmlspecialchars((string) $s, ENT_QUOTES | ENT_HTML5, 'UTF-8');
173
+ $lang = preg_replace('/[^a-z-]/', '', strtolower((string) ($cfg['lang'] ?? 'en'))) ?: 'en';
174
+ $links = array_filter(array_keys((array) ($cfg['routes'] ?? [])), fn ($p) => strpos((string) $p, ':') === false);
175
+ ?><!DOCTYPE html>
176
+ <html lang="<?= $h($lang) ?>"<?= in_array($lang, ['ar', 'fa', 'he', 'ur'], true) ? ' dir="rtl"' : '' ?>>
177
+ <head>
178
+ <meta charset="utf-8">
179
+ <title><?= $h($title) ?></title>
180
+ <meta name="description" content="<?= $h($desc) ?>">
181
+ <link rel="canonical" href="<?= $h($url) ?>">
182
+ <meta property="og:site_name" content="<?= $h($name) ?>">
183
+ <meta property="og:type" content="<?= $h($type) ?>">
184
+ <meta property="og:url" content="<?= $h($url) ?>">
185
+ <meta property="og:title" content="<?= $h($title) ?>">
186
+ <meta property="og:description" content="<?= $h($desc) ?>">
187
+ <?php if ($image !== ''): ?><meta property="og:image" content="<?= $h($image) ?>">
188
+ <?php endif; ?>
189
+ <meta name="twitter:card" content="<?= $image !== '' ? 'summary_large_image' : 'summary' ?>">
190
+ <script type="application/ld+json"><?= json_encode(['@context' => 'https://schema.org', '@type' => $type === 'product' ? 'Product' : 'WebPage', 'name' => $title, 'description' => $desc, 'url' => $url] + ($image !== '' ? ['image' => $image] : []), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG) ?></script>
191
+ </head>
192
+ <body>
193
+ <h1><?= $h($title) ?></h1>
194
+ <?php if ($desc !== ''): ?><p><?= $h($desc) ?></p>
195
+ <?php endif; ?><?php if ($body !== ''): ?><p><?= $h($body) ?></p>
196
+ <?php endif; ?><?php if ($image !== ''): ?><p><img src="<?= $h($image) ?>" alt="<?= $h($title) ?>"></p>
197
+ <?php endif; ?>
198
+ <nav><?php foreach ($links as $p): ?><a href="<?= $h($site . '/' . ltrim((string) $p, '/')) ?>"><?= $h(((array) $cfg['routes'][$p])['label'] ?? ($p === '' ? $name : ucwords(str_replace(['-', '_'], ' ', (string) $p)))) ?></a> <?php endforeach; ?></nav>
199
+ </body>
200
+ </html>
@@ -0,0 +1,3 @@
1
+ "use strict";const fs=require("fs");const path=require("path");const SKIP_VIEW=/^(_|404|index$|layout|header|footer|nav)|(\s|copy|_bu|_old|backup|\.bak|test)/i;function siteUrl(config,seo){const pick=[seo&&seo.site,config&&config.site,config&&config.domain,config&&config.project_info&&config.project_info.WebsiteURL];for(const v of pick){if(typeof v!=="string"||!v.trim())continue;const s=/^https?:\/\//i.test(v.trim())?v.trim():"https://"+v.trim();try{const u=new URL(s);if(/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(u.hostname))return u.origin}catch(e){}}return""}function pageRoutes(projectPath){const dir=path.join(projectPath,"src","views");if(!fs.existsSync(dir))return[];const out=[];for(const f of fs.readdirSync(dir)){if(!f.endsWith(".view"))continue;const name=f.slice(0,-5);if(SKIP_VIEW.test(name)||!/^[a-z0-9][a-z0-9_-]*$/i.test(name))continue;out.push(name==="home"?"":name)}return[...new Set(out)].sort((a,b)=>a===""?-1:b===""?1:a.localeCompare(b))}function readJson(file){try{const j=JSON.parse(fs.readFileSync(file,"utf8"));return j&&typeof j==="object"?j:null}catch(e){return null}}const words=s=>String(s).replace(/[-_]+/g," ").replace(/\b\w/g,c=>c.toUpperCase());const xml=s=>String(s).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");function writeSeoFiles(projectPath,dest,config){const src=f=>path.join(projectPath,"src",f);const own=readJson(src("seo.json"))||{};const info=config&&config.project_info||{};const site=siteUrl(config,own);const routes=pageRoutes(projectPath);const name=own.name||info.Title||(site?new URL(site).hostname:"");const done={site,robots:false,sitemap:false,seo:false,pages:routes.length};if(!fs.existsSync(src("robots.txt"))){fs.writeFileSync(path.join(dest,"robots.txt"),"User-agent: *\nAllow: /\n"+(site?`
2
+ Sitemap: ${site}/sitemap.xml
3
+ `:""));done.robots=true}if(!fs.existsSync(src("sitemap.xml"))){const target=path.join(dest,"sitemap.xml");const fixed=Object.keys(own.routes||{}).map(r=>r.replace(/^\/+|\/+$/g,"")).filter(r=>!r.includes(":"));const all=[...new Set([...routes,...fixed])];if(site){const day=new Date().toISOString().slice(0,10);fs.writeFileSync(target,'<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'+all.map(r=>` <url><loc>${xml(site+"/"+r)}</loc><lastmod>${day}</lastmod></url>`).join("\n")+"\n</urlset>\n");done.sitemap=true}else if(fs.existsSync(target)){fs.unlinkSync(target)}}if(!fs.existsSync(src("seo.php"))){const defaults={};for(const r of routes){defaults[r]={title:r===""?info.Title||name:`${words(r)} | ${name}`}}const meta=info.MetaTags||{};const seo={site,name,title:own.title||info.Title||name,description:own.description||info.Description||"",image:own.image||meta["og:image"]||meta.image||"",lang:own.lang||"en",routes:Object.assign(defaults,own.routes||{})};fs.copyFileSync(path.join(__dirname,"files","seo","seo.php"),path.join(dest,"seo.php"));fs.writeFileSync(path.join(dest,"seo.json"),JSON.stringify(seo,null,2)+"\n");done.seo=true}return done}module.exports={writeSeoFiles,siteUrl,pageRoutes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lmjs/cli",
3
- "version": "2.7.0",
3
+ "version": "2.8.1",
4
4
  "description": "Command line interface for LumenJS — scaffold, develop, and build LumenJS applications. LumenJS is a tiny, fast reactive JavaScript framework for building web applications and interfaces with standard HTML, CSS, and JavaScript.",
5
5
  "bin": {
6
6
  "lm": "./dist/bin/commands.js",
@@ -52,7 +52,7 @@
52
52
  "ora": "^6.1.2",
53
53
  "semver": "^7.3.7",
54
54
  "ws": "^8.8.1",
55
- "@lmjs/core": "2.7.0"
55
+ "@lmjs/core": "2.8.1"
56
56
  },
57
57
  "engines": {
58
58
  "node": ">=18.0.0"