@lmjs/cli 2.1.19 → 2.1.21

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
@@ -1,4 +1,4 @@
1
- const fetch=require("node-fetch");const path=require("path");const fs=require("fs");const nodemon=require("nodemon");var _acorn=require("acorn");var acorn=require("acorn-loose");var _min=require("html-minifier").minify;const _FD=require("ftp-deploy");const _fD=new _FD;global.astring=global.astring||require("astring");const _corePackageDir=path.dirname(require.resolve("@lmjs/core/package.json"));const _walk=require(path.join(_corePackageDir,"src","walk.js"));const _npmBundle=require(path.join(__dirname,"npm-bundle.js"));exports.hasOwnDependencies=_npmBundle.hasOwnDependencies;exports.buildEntryWithImports=_npmBundle.buildEntryWithImports;const _pluginsBundle=require(path.join(__dirname,"plugins-esbuild-plugin.js"));const _vault=require(path.join(__dirname,"vault.js"));exports.login=_vault.login;exports.apiSet=_vault.apiSet;exports.apiUpdate=_vault.apiUpdate;exports.apiGet=_vault.apiGet;exports.apiList=_vault.apiList;exports.apiRemove=_vault.apiRemove;function selectedProjectPlugins(projectRoot){try{const pkgPath=path.join(projectRoot,"package.json");if(!fs.existsSync(pkgPath))return[];const pkg=JSON.parse(fs.readFileSync(pkgPath,"utf8"));if(!pkg.dependencies)return[];return _pluginsBundle.selectedRegistryEntries(pkg.dependencies)}catch(e){return[]}}exports.selectedProjectPlugins=selectedProjectPlugins;function compileProjectScript(source,name){let ast=_acorn.parse(source,{ecmaVersion:"latest",sourceType:"script"});let topLevelNames=[];for(const stmt of ast.body){if(stmt.type==="VariableDeclaration"){for(const d of stmt.declarations){if(d.id&&d.id.type==="Identifier")topLevelNames.push(d.id.name)}}}return _walk.getWatcher(ast,{name:name||"script"},topLevelNames,"Global").code}exports.compileProjectScript=compileProjectScript;function detectLocalProjectScripts(indexHtmlSource){let found=[];let re=/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;let m;while(m=re.exec(indexHtmlSource)){let src=m[1];if(src.indexOf("/")!==0)continue;if(src==="/js/lm.js"||src==="/index.js")continue;found.push(src)}return found}exports.detectLocalProjectScripts=detectLocalProjectScripts;const CORE_Libs={BEACSS:"https://s.beacdn.com/beacss/latest",COREJS:"https://lmjs.beacdn.com/latest"};const HST_FORMAT_VERSION=1;exports.HST_FORMAT_VERSION=HST_FORMAT_VERSION;exports.getAllFiles=getAllFiles;exports.validateTplsAreHtmlOnly=validateTplsAreHtmlOnly;exports.ucwords=ucwords;exports.fetch=fetch;exports.getConfig=getConfig;function getConfig(){config={version:"1.0.0.1",server:{host:"127.0.0.1",port:"3000",ssl:{enabled:false,key:"/key.pem",cert:"/certificate.cer"}},apis:[{baseURL:"https://www.beaapis.com/1",headers:{"X-BEA-Application-ID":"YOUR_APPLICATION_ID","X-BEA-Authorization":"YOUR_REST_API_KEY"}}],ftp:{host:"ftp_host",username:"ftp_username",password:"ftp_password",remotePath:"/",concurrency:4,protocol:"ftp",port:21,ignore:[],syncOption:{delete:false,ignoreExisting:false,skipCreate:false,update:true},connectTimeout:3e4}};let configPath=process.cwd()+path.sep+`config.json`;if(fs.existsSync(configPath)){config=JSON.parse(fs.readFileSync(configPath,{encoding:"utf8"}))}return config}var config=getConfig();function ucwords(str){return(str+"").replace(/^([a-z])|\s+([a-z])/g,function($1){return $1.toUpperCase()})}function lw(s){return s.toString().toLowerCase()}exports.lw=lw;function cd(d){if(!fs.existsSync(d))fs.mkdirSync(d)}exports.cd=cd;function rd(d){if(fs.existsSync(d))fs.rmSync(d,{recursive:true,force:true})}exports.rd=rd;function create(conf){let t=conf.type=="v"||conf.type=="s"||conf.type=="t"?conf.type:"p";let n=conf.type=="v"||conf.type=="s"||conf.type=="t"?lw(conf.name[0]):conf.name.join(" ");if(t=="p"){var libsPath=`${__dirname}`+path.sep+`files`+path.sep+`libs`;var getLibs=false;var _beacssMissing=false;var _lmMissing=false;require("dns").resolve("www.google.com",function(err){if(!err){var _mobiuscssPath=libsPath+path.sep+"mobius.css";_beacssMissing=!fs.existsSync(_mobiuscssPath)||fs.statSync(_mobiuscssPath).size===0;_lmMissing=!fs.existsSync(libsPath+path.sep+"lm.js");if(_lmMissing||_beacssMissing)getLibs=true}if(getLibs){API.get(CORE_Libs.COREJS,{}).then(corejs=>{API.get(CORE_Libs.BEACSS,{}).then(mobiuscss=>{var libsPath2=`${__dirname}`+path.sep+`files`+path.sep+`libs`;cd(libsPath2);if(_lmMissing){fs.writeFileSync(libsPath2+path.sep+"lm.js",String(corejs))}if(_beacssMissing){fs.writeFileSync(libsPath2+path.sep+"mobius.css",String(mobiuscss))}var filePath3=`${process.cwd()}`+path.sep;copyDir(`${__dirname}`+path.sep+`files`+path.sep+`project`,filePath3,n);cd(filePath3+path.sep+"src");cd(filePath3+path.sep+"src"+path.sep+"css");cd(filePath3+path.sep+"src"+path.sep+"images");cd(filePath3+path.sep+"src"+path.sep+"js");let stylesFile=filePath3+path.sep+"src"+path.sep+"css"+path.sep+`styles.css`;let faviconFile=filePath3+path.sep+"src"+path.sep+`favicon.ico`;if(!fs.existsSync(stylesFile))fs.writeFileSync(stylesFile,String(""));if(!fs.existsSync(faviconFile))fs.writeFileSync(faviconFile,String(""));fs.writeFileSync(filePath3+path.sep+"src"+path.sep+"js"+path.sep+"lm.js",String(corejs));fs.writeFileSync(filePath3+path.sep+"src"+path.sep+"css"+path.sep+"mobius.css",String(mobiuscss))})}).catch(err2=>{})}else{var filePath2=`${process.cwd()}`+path.sep;copyDir(`${__dirname}`+path.sep+`files`+path.sep+`project`,filePath2,n);cd(filePath2+path.sep+"src");cd(filePath2+path.sep+"src"+path.sep+"css");cd(filePath2+path.sep+"src"+path.sep+"images");cd(filePath2+path.sep+"src"+path.sep+"js");let stylesFile=filePath2+path.sep+"src"+path.sep+"css"+path.sep+`styles.css`;let faviconFile=filePath2+path.sep+"src"+path.sep+`favicon.ico`;if(!fs.existsSync(stylesFile))fs.writeFileSync(stylesFile,String(""));if(!fs.existsSync(faviconFile))fs.writeFileSync(faviconFile,String(""));let corejs=Buffer.from(fs.readFileSync(libsPath+path.sep+"lm.js").toString());let mobiuscss=Buffer.from(fs.readFileSync(libsPath+path.sep+"mobius.css").toString());fs.writeFileSync(filePath2+path.sep+"src"+path.sep+"js"+path.sep+"lm.js",String(corejs));fs.writeFileSync(filePath2+path.sep+"src"+path.sep+"css"+path.sep+"mobius.css",String(mobiuscss))}})}else{let file=t=="s"?"sub_view.view":t=="t"?"layout.layout":"view.view";let ident=t=="s"?"SubView":t=="t"?"Template":"View";let dir=t=="t"?"layouts":"views";let ext=t=="t"?"layout":"view";let html5=Buffer.from(fs.readFileSync(`${__dirname}`+path.sep+`files`+path.sep+file).toString().split("["+ident+"Name]").join(ucwords(n)));var filePath=`${process.cwd()}`+path.sep+`src`+path.sep+dir+path.sep+`${n}.${ext}`;if(fs.existsSync(filePath)){console.log(ident+" already exists:",filePath)}else{fs.writeFileSync(filePath,html5)}}}function getAllFiles(dirPath,arrayOfFiles={},mini=false,hst2=true){files=fs.readdirSync(dirPath);files.forEach(function(file){if(fs.statSync(dirPath+path.sep+file).isDirectory()){arrayOfFiles=getAllFiles(dirPath+path.sep+file,arrayOfFiles,mini,hst2)}else{let filePath=path.join(dirPath,path.sep,file);let fileKey=Buffer.from(filePath.split(`${process.cwd()}`+path.sep).join("").split("\\").join("/")).toString("base64");if(mini){var result=_min(fs.readFileSync(filePath,{encoding:"utf8"}),{removeAttributeQuotes:false,caseSensitive:true,collapseWhitespace:true,collapseInlineTagWhitespace:true,conservativeCollapse:true,removeComments:true,minifyJS:false,minifyCSS:false,processConditionalComments:true,collapseBooleanAttributes:false,decodeEntities:false,html5:true,includeAutoGeneratedTags:true,keepClosingSlash:true,maxLineLength:null,minifyURLs:false,preserveLineBreaks:false,preventAttributesEscaping:false,processScripts:["text/html"],quoteCharacter:"",removeEmptyAttributes:true,removeEmptyElements:false,removeOptionalTags:true,removeRedundantAttributes:true,removeScriptTypeAttributes:false,removeStyleLinkTypeAttributes:true,removeTagWhitespace:false,sortAttributes:false,sortClassName:false,trimCustomFragments:true,useShortDoctype:true,continueOnParseError:true})}else if(hst2){var result=_hst(fs.readFileSync(filePath,{encoding:"utf8"}))}else{var result=fs.readFileSync(filePath,{encoding:"utf8"})}arrayOfFiles[fileKey]=result}});return arrayOfFiles}const RESERVED_BARE_ATTRS=new Set(["body","view","scoped","tpl","sl","color","time","date","datetime","up","stop","confirm","econfirm","acl","rcl","hidden","disabled","readonly","required","checked","selected","autofocus","multiple","async","defer"]);function _collectWidgetRegions(nodes,found){if(!Array.isArray(nodes))return;for(const node of nodes){if(node&&node.type==="tag"&&node.attrs){for(const attrName in node.attrs){if(Object.prototype.hasOwnProperty.call(node.attrs,attrName)&&node.attrs[attrName]===""&&!RESERVED_BARE_ATTRS.has(attrName)&&!found.includes(attrName)){found.push(attrName)}}}if(node&&Array.isArray(node.children)){_collectWidgetRegions(node.children,found)}}}function annotateLayoutRegions(layoutsObj){for(const key in layoutsObj){if(!Object.prototype.hasOwnProperty.call(layoutsObj,key))continue;let entry=layoutsObj[key];if(!entry||!entry.hst)continue;let found=[];_collectWidgetRegions(entry.hst,found);entry.regions=found}return layoutsObj}exports.annotateLayoutRegions=annotateLayoutRegions;function validateTplsAreHtmlOnly(tpls){function scan(nodes,fileKey){if(!Array.isArray(nodes))return;for(const node of nodes){if(!node)continue;if(node.type==="tag"&&node.name){let n=node.name.toLowerCase();if(n==="script"||n==="js"||n==="style"){let name=Buffer.from(fileKey,"base64").toString("utf8");throw new Error('tpls/*.tpl files are HTML-only \u2014 "'+name+'" has a <'+node.name+"> block. Templates render inside whatever scope they're used from (a :for item's own), not an isolated one, so they can't carry their own script/style. Use a view= subview instead if this needs its own state or styling.")}}if(node.children)scan(node.children,fileKey)}}for(const fileKey in tpls){if(Object.prototype.hasOwnProperty.call(tpls,fileKey)){scan(tpls[fileKey].hst,fileKey)}}}class hst{htmlVoidElements=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","isindex","keygen","link","menuitem","meta","nextid","param","source","track","wbr"];moustachePattern=/\{\s*\{\s*([\s\S]*?)\s*\}\s*\}/g;attrRE=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;tagRE=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g;whitespaceRE=/^\s*$/;empty=Object.create(null);reactiveVariables=[];constructor(html){let hst2=this.parse(html);this.reactiveVariables=this.reactiveVariables.filter((value,index,self)=>{return self.indexOf(value)===index});return{hst:hst2,"reactiveVars":this.reactiveVariables}}keepOneSpace(_t){_t=_t.replace(/\s\s/gm," ");if(/\s\s/gm.test(_t))return this.keepOneSpace(_t);return _t}_clean(_t){_t=_t.replace(/(\r?\n|\r)/gm,"");_t=_t.replace(/(\t)/gm,"");_t=this.keepOneSpace(_t);return _t.replace(/^(?:\s*\t*\r*\n*\{*)+|(?:\s*\t*\r*\n*\})+$/g,"").trim()}processAttr(n,v,res){}processForXAttr(val){let forX={"js":"","as":{"k":"","v":""},"dx":""};var val=val.trim();if(val.indexOf(";")>-1){let zxx=val.split(";");forX["dx"]=zxx[1].trim();val=zxx[0].trim()}if(val.indexOf(" as ")>-1){let arr2=val.split(" as ");let kv=[];let arr3=arr2[1].split(" ").join("").split(",");if(arr3.length>1){kv=[arr3[0],arr3[1]]}else{kv=[arr3[0]]}if(kv.length){forX["as"]["k"]=kv[0].trim();if(kv.length>1){forX["as"]["v"]=kv[1].trim()}}val=arr2[0].trim()}forX["js"]=val.trim();return forX}parseTag(tag){var res={type:"tag",name:"",isV:false,attrs:{},ax:{},evs:{},ex:{},children:[]};var tagMatch=tag.match(/<\/?([^\s]+?)[/\s>]/);if(tagMatch){res.name=tagMatch[1];res.isV=this.htmlVoidElements.includes(tagMatch[1])||tag.charAt(tag.length-2)==="/"}var reg=new RegExp(this.attrRE);var result=null;for(;;){result=reg.exec(tag);if(result===null){break}if(!result[0].trim()){continue}if(result[1]){var attr=result[1].trim();var arr=[attr,""];if(arr[0]==":else"){res.type="section";res.cond=""}if(attr.indexOf("=")>-1){arr=attr.split("=")}if(arr[0].substring(0,1)=="@"){}else{if(res.name.toLowerCase()=="icon"&&arr[0].indexOf(":")>-1&&arr[0].substr(0,1)!=":"){res.icon=arr[0]}else res.attrs[arr[0]]=arr[1]}reg.lastIndex--}else if(result[2]){let sl=result[3].trim().substring(1,result[3].length-1);if(result[2]==":if"||result[2]==":else-if"||result[2]==":else"){res.type="section";res.cond=sl;if(sl){try{let condAST=acorn.parse(sl,{ecmaVersion:"latest"});let condVars=this.collectVariableUsageFromAST(condAST,{excludeBuiltins:true,extraBuiltins:[]});for(let X=0;X<condVars.length;X++){this.reactiveVariables.push(condVars[X])}}catch(e){}}}else if(result[2]==":for"){res.type="sections";res.content=sl;res.forX=this.processForXAttr(sl);if(res.forX.js){try{let forAST=acorn.parse(res.forX.js,{ecmaVersion:"latest"});let forVars=this.collectVariableUsageFromAST(forAST,{excludeBuiltins:true,extraBuiltins:[]});for(let X=0;X<forVars.length;X++){this.reactiveVariables.push(forVars[X])}}catch(e){}}}if(result[2].substring(0,1)=="@"){let max=this._getMs2(sl);res.evs[result[2]]=max[1];max[0].length?res.ex[result[2]]=max[0]:null}else{let max=this._getMs2(sl);if(res.name.toLowerCase()=="icon"&&result[2].indexOf(":")>-1&&result[2].substr(0,1)!=":"){res.icon=result[2]}else res.attrs[result[2]]=max[1];max[0].length?res.ax[result[2]]=max[0]:null}}}return res}removeComments(str){str=str.replace(/<!--[\s\S]*?(?:-->)/g,"");return str}cleanExpression(expression){let cleaned="";let inSingle=false,inDouble=false,inTemplate=false;let inRegex=false,escapeNext=false;let inBlockComment=false,inLineComment=false;for(let i=0;i<expression.length;i++){let char=expression[i];let next=expression[i+1];if(escapeNext){cleaned+=char;escapeNext=false;continue}if(inBlockComment){if(char==="*"&&next==="/"){inBlockComment=false;i++}continue}if(inLineComment){if(char==="\n"){inLineComment=false}continue}if(!inSingle&&!inDouble&&!inTemplate&&!inRegex){if(char==="/"&&next==="*"){inBlockComment=true;i++;continue}if(char==="/"&&next==="/"){inLineComment=true;i++;continue}}if(!inDouble&&!inTemplate&&!inRegex&&char==="'"&&!inSingle){inSingle=true;cleaned+=char;continue}else if(inSingle&&char==="'"){inSingle=false;cleaned+=char;continue}if(!inSingle&&!inTemplate&&!inRegex&&char==='"'&&!inDouble){inDouble=true;cleaned+=char;continue}else if(inDouble&&char==='"'){inDouble=false;cleaned+=char;continue}if(!inSingle&&!inDouble&&!inRegex&&char==="`"&&!inTemplate){inTemplate=true;cleaned+=char;continue}else if(inTemplate&&char==="`"){inTemplate=false;cleaned+=char;continue}if(!inSingle&&!inDouble&&!inTemplate&&char==="/"&&!inRegex){let prevNonSpace=cleaned.match(/\S$/);if(!prevNonSpace||/[=({[,;:?!+\-*/%&|^~<>]/.test(prevNonSpace[0])){inRegex=true}cleaned+=char;continue}else if(inRegex&&char==="/"&&expression[i-1]!=="\\"){inRegex=false;cleaned+=char;continue}if(char==="\\"&&(inSingle||inDouble||inTemplate||inRegex)){escapeNext=true;cleaned+=char;continue}if(!inSingle&&!inDouble&&!inTemplate&&!inRegex){if(/\s/.test(char)){if(cleaned[cleaned.length-1]!==" "){cleaned+=" "}continue}}cleaned+=char}return cleaned.trim()}_getMs(_t,wbt){let result="";let lastIndex=0;let _m;var _ms=[];let hasError=false;while((_m=this.moustachePattern.exec(_t))!=null){try{let AST=acorn.parse(_m[0],{ecmaVersion:"latest"});hasError=false;let mux=this._clean(_m[0]);if(wbt){if(_t.substring(_m.index-1,1)=="`"){_ms.push(mux);result+=_t.substring(lastIndex,_m.index);result+="{{"+mux+"}}";lastIndex=_m.index+_m[0].length}}else{if(_t.substring(_m.index-1,1)!="`"){_ms.push(mux);result+=_t.substring(lastIndex,_m.index);result+="{{"+mux+"}}";lastIndex=_m.index+_m[0].length}}}catch(e){hasError=true;result+=_t.substring(lastIndex,_m.index);result+="{{ /*Invalid Javascript Code*/ }}";console.log("Invalid JS",_m[0])}}if(!hasError)result+=_t.substring(lastIndex);return[_ms,result]}_getMs2(_t,wbt){let content="";let lastIndex=0;let _m;var _muxes=[];let hasError=false;while((_m=this.moustachePattern.exec(_t))!=null){try{hasError=false;let mux=this._clean(_m[0]);let JST=acorn.parse(mux,{ecmaVersion:"latest"});let rvs=[];let vss=this.collectVariableUsageFromAST(JST,{excludeBuiltins:true,extraBuiltins:[]});for(let X=0;X<vss.length;X++){rvs.push(vss[X]);this.reactiveVariables.push(vss[X])}rvs=rvs.filter((value,index,self)=>{return self.indexOf(value)===index});_muxes.push({"mus":mux,"jst":JST,"rvs":rvs});content+=_t.substring(lastIndex,_m.index);content+="{{"+mux+"}}";lastIndex=_m.index+_m[0].length}catch(e){hasError=true;content+=_t.substring(lastIndex,_m.index);content+="{{ /*Invalid Javascript Code*/ }}";console.log("Invalid JS",_m[0])}}if(!hasError)content+=_t.substring(lastIndex);_muxes=this.setMuxesIndexes(content,_muxes);return[_muxes,content]}setMuxesIndexes(content,_muxes){let muxes=[];let lastIndex=0;let i=0;let _m;while((_m=this.moustachePattern.exec(content))!=null){muxes.push({..._muxes[i],"start":_m.index,"end":_m.index+_m[0].length});lastIndex=_m.index+_m[0].length;i++}return muxes}parse(html,options){if(options===void 0){options={}}options||(options={});options.components||(options.components=this.empty);html=this.removeComments(html);var result=[];var arr=[];var current;var level=-1;var inComponent=false;var inRawText=false;var par=this;if(html.indexOf("<")!==0){var end=html.indexOf("<");let zl=end===-1?html:html.substring(0,end);let mssx=this._getMs2(zl);let textObj={type:"text",content:mssx[1],mss:mssx[0]};result.push(textObj)}html.replace(this.tagRE,async function(tag,index){if(inComponent||inRawText){if(tag!=="</"+current.name+">"){return""}else{inComponent=false;inRawText=false}}var isOpen=tag.charAt(1)!=="/";var start=index+tag.length;var nextChar=html.charAt(start);var parent;if(isOpen){level++;current=par.parseTag(tag);if(current.type==="tag"&&(current.name==="script"||current.name==="style")){inRawText=true}if(current.type==="tag"&&current.name&&options.components&&options.components[current.name]){current.type="component";inComponent=true}if(!current.isV&&!inComponent&&nextChar&&nextChar!=="<"&&Array.isArray(current.children)){let end2;if(current.name==="script"||current.name==="style"){let closeRe=new RegExp("</\\s*"+current.name+"\\s*>","i");let m=closeRe.exec(html.slice(start));end2=m?start+m.index:html.length}else{end2=html.indexOf("<",start);while(html.charAt(end2+1)==" "){end2=html.indexOf("<",start+(end2+1-start))}}let hl=html.slice(start,end2);let mssx=null;if(current.name!="script")mssx=par._getMs2(hl);let textObj={type:"text",content:current.name=="script"?"":mssx[1],...current.name=="script"?{jst:acorn.parse(hl,{ecmaVersion:"latest"})}:{mss:mssx[0]},tag:current.name};current.children.push(textObj)}if(level===0){result.push(current)}parent=arr[level-1];if(parent&&parent.children){parent.children.push(current)}arr[level]=current}if(!isOpen||current.isV){if(level>-1&&(current.isV||current.name===tag.slice(2,-1))){level--;current=level===-1?result:arr[level]}if(!inComponent&&nextChar!=="<"&&nextChar){parent=level===-1?result:arr[level].children;var _end=html.indexOf("<",start);var content=html.slice(start,_end===-1?void 0:_end);if(par.whitespaceRE.test(content)){content=" "}if(_end>-1&&level+parent.length>=0||content!==" "){if(parent&&Array.isArray(parent)){if(content!==" "){let mssx=par._getMs2(content);let textObj={type:"text",content:mssx[1],mss:mssx[0]};parent.push(textObj)}}}}}});return result}collectVariableUsageFromAST(ast,options={}){const{excludeBuiltins=true,extraBuiltins=[]}=options;const DEFAULT_BUILTINS=new Set(["undefined","NaN","Infinity","null","true","false","Object","Function","Boolean","Symbol","Error","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","Number","BigInt","Math","Date","String","RegExp","Array","Map","Set","WeakMap","WeakSet","Promise","Reflect","Proxy","Intl","JSON","Atomics","SharedArrayBuffer","ArrayBuffer","DataView","WeakRef","FinalizationRegistry","console","window","document","navigator","location","localStorage","sessionStorage","fetch","XMLHttpRequest","setTimeout","clearTimeout","setInterval","clearInterval","requestAnimationFrame","cancelAnimationFrame","process","global","globalThis","require","module","exports","Buffer","parseInt","parseFloat","isFinite","isNaN","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","escape","unescape"]);const builtinSet=new Set([...DEFAULT_BUILTINS,...extraBuiltins]);function createScope(parent=null,isFunction=false){return{parent,isFunction:!!isFunction,names:new Set}}const scopeForNode=new WeakMap;const bindingIdNodes=new WeakSet;const allDeclaredNames=new Set;function markPatternBindings(pattern,scope,kind="var"){if(!pattern)return;switch(pattern.type){case"Identifier":bindingIdNodes.add(pattern);declareInScope(pattern.name,kind,scope);allDeclaredNames.add(pattern.name);break;case"ArrayPattern":for(const el of pattern.elements)if(el)markPatternBindings(el,scope,kind);break;case"ObjectPattern":for(const p of pattern.properties){if(p.type==="Property")markPatternBindings(p.value,scope,kind);else if(p.type==="RestElement")markPatternBindings(p.argument,scope,kind)}break;case"RestElement":markPatternBindings(pattern.argument,scope,kind);break;case"AssignmentPattern":markPatternBindings(pattern.left,scope,kind);break;default:break}}function declareInScope(name,kind,currentScope){if(!name||!currentScope)return;if(kind==="var"||kind==="function"){let s=currentScope;while(s&&!s.isFunction&&s.parent)s=s.parent;s.names.add(name)}else{currentScope.names.add(name)}}function buildScopes(node,currentScope){if(!node||typeof node!=="object")return;switch(node.type){case"Program":{scopeForNode.set(node,currentScope);for(const stmt of node.body)buildScopes(stmt,currentScope);return}case"FunctionDeclaration":{if(node.id){bindingIdNodes.add(node.id);declareInScope(node.id.name,"function",currentScope);allDeclaredNames.add(node.id.name)}const fnScope=createScope(currentScope,true);scopeForNode.set(node,fnScope);for(const p of node.params)markPatternBindings(p,fnScope,"param");buildScopes(node.body,fnScope);return}case"FunctionExpression":{const fnScope=createScope(currentScope,true);scopeForNode.set(node,fnScope);if(node.id){bindingIdNodes.add(node.id);declareInScope(node.id.name,"let",fnScope);allDeclaredNames.add(node.id.name)}for(const p of node.params)markPatternBindings(p,fnScope,"param");buildScopes(node.body,fnScope);return}case"ArrowFunctionExpression":{const fnScope=createScope(currentScope,true);scopeForNode.set(node,fnScope);for(const p of node.params)markPatternBindings(p,fnScope,"param");buildScopes(node.body,fnScope);return}case"BlockStatement":case"StaticBlock":case"SwitchStatement":{const blockScope=createScope(currentScope,false);scopeForNode.set(node,blockScope);if(node.type==="SwitchStatement"){for(const c of node.cases)buildScopes(c,blockScope)}else{for(const s of node.body)buildScopes(s,blockScope)}return}case"CatchClause":{const catchScope=createScope(currentScope,false);scopeForNode.set(node,catchScope);if(node.param)markPatternBindings(node.param,catchScope,"let");buildScopes(node.body,catchScope);return}case"ForStatement":case"ForInStatement":case"ForOfStatement":{const forScope=createScope(currentScope,false);scopeForNode.set(node,forScope);if(node.init)buildScopes(node.init,forScope);if(node.left)buildScopes(node.left,forScope);if(node.test)buildScopes(node.test,forScope);if(node.update)buildScopes(node.update,forScope);buildScopes(node.body,forScope);return}case"VariableDeclaration":{for(const decl of node.declarations||[]){markPatternBindings(decl.id,currentScope,node.kind||"var");if(decl.init)buildScopes(decl.init,currentScope)}return}case"ClassDeclaration":{if(node.id){bindingIdNodes.add(node.id);declareInScope(node.id.name,"let",currentScope);allDeclaredNames.add(node.id.name)}if(node.body)buildScopes(node.body,currentScope);return}case"ImportDeclaration":{for(const spec of node.specifiers||[]){if(spec.local){bindingIdNodes.add(spec.local);declareInScope(spec.local.name,"const",currentScope);allDeclaredNames.add(spec.local.name)}}return}case"ExportNamedDeclaration":case"ExportDefaultDeclaration":case"ExportAllDeclaration":{if(node.declaration)buildScopes(node.declaration,currentScope);return}default:break}for(const key of Object.keys(node)){if(key==="loc"||key==="range")continue;const child=node[key];if(Array.isArray(child)){for(const c of child)if(c&&typeof c==="object")buildScopes(c,currentScope)}else if(child&&typeof child==="object"){buildScopes(child,currentScope)}}}const rootScope=createScope(null,true);scopeForNode.set(ast,rootScope);buildScopes(ast,rootScope);const usageSet=new Set;function isVariableUsageIdentifier(node,parent,propName){if(!parent)return true;if(bindingIdNodes.has(node))return false;if(parent.type==="LabeledStatement"&&propName==="label"||(parent.type==="BreakStatement"||parent.type==="ContinueStatement")&&propName==="label"){return false}if(parent.type==="MemberExpression"&&propName==="property"&&parent.computed===false){return false}if(parent.type==="Property"&&propName==="key"&&parent.computed===false&&!parent.shorthand){return false}if((parent.type==="MethodDefinition"||parent.type==="PropertyDefinition")&&propName==="key"&&parent.computed===false){return false}if(parent.type&&(parent.type.startsWith("Import")||parent.type.startsWith("Export")||parent.type==="MetaProperty")){return false}if((parent.type==="FunctionDeclaration"||parent.type==="FunctionExpression"||parent.type==="ClassDeclaration")&&propName==="id"){return false}if(parent.type==="VariableDeclarator"&&propName==="id"||parent.type==="CatchClause"&&propName==="param"){return false}if((parent.type==="CallExpression"||parent.type==="OptionalCallExpression")&&propName==="callee"){return false}if(parent.type==="NewExpression"&&propName==="callee"){return false}return true}const scopeStack=[rootScope];function collect(node,parent,propName,index){if(!node||typeof node!=="object")return;const nodeScope=scopeForNode.get(node);if(nodeScope)scopeStack.push(nodeScope);if(node.type==="Identifier"){if(isVariableUsageIdentifier(node,parent,propName)){const name=node.name;if(!(excludeBuiltins&&builtinSet.has(name))){usageSet.add(name)}}}for(const key of Object.keys(node)){if(key==="loc"||key==="range")continue;const child=node[key];if(Array.isArray(child)){for(let i=0;i<child.length;i++){const c=child[i];if(c&&typeof c==="object")collect(c,node,key,i)}}else if(child&&typeof child==="object"){collect(child,node,key,null)}}if(nodeScope)scopeStack.pop()}collect(ast,null,null,null);return Array.from(usageSet).sort()}}function _hst(html){return new hst(html)}function copyDir(src,dest,projectName){try{const entries=fs.readdirSync(src,{encoding:"utf8",withFileTypes:true});cd(dest);for(let entry of entries){const srcPath=path.join(src.toString(),entry.name.toString());const destPath=path.join(dest.toString(),entry.name.toString());if(entry.isDirectory()){if(projectName=="_beajsBuild"){if(entry.name!="layouts"&&entry.name!="views"&&entry.name!="css"&&entry.name!="js")copyDir(srcPath,destPath,projectName)}else copyDir(srcPath,destPath,projectName)}else{if(projectName=="_beajsBuild"){if(projectName=="_beajsBuild"&&entry.name!="index.js"&&entry.name!="index.html")fs.copyFileSync(srcPath,destPath)}else{if(!fs.existsSync(destPath)){if(projectName){if(entry.name=="index.html"){let html5=Buffer.from(fs.readFileSync(srcPath).toString().split("[ProjectName]").join(ucwords(projectName)));fs.writeFileSync(destPath,html5)}else if(entry.name=="package.json"){let slug=lw(projectName).replace(/[^a-z0-9._-]+/g,"-").replace(/^[-.]+|[-.]+$/g,"")||"lumenjs-project";let pkgJson=Buffer.from(fs.readFileSync(srcPath).toString().split("[ProjectName]").join(slug));fs.writeFileSync(destPath,pkgJson)}else fs.copyFileSync(srcPath,destPath)}else fs.copyFileSync(srcPath,destPath)}else{console.log("File already exists:",destPath)}}}}}catch(e){console.log(e)}}exports.copyDir=copyDir;function validURL(string){let url;try{url=new URL(string)}catch(_){return false}return url.protocol==="http:"||url.protocol==="https:"}exports.validURL=validURL;let getPairs=(obj,keys=[])=>Object.entries(obj).reduce((pairs,[key,value])=>{if(typeof value==="object")pairs.push(...getPairs(value,[...keys,key]));else pairs.push([[...keys,key],value]);return pairs},[]);function pairIt(obj){return getPairs(obj).map(([[key0,...keysRest],value])=>`${key0}${keysRest.map(a=>`[${a}]`).join("")}=${value}`).join("&")}var API={get:async function(u,d,h,a){return await this.req(u,d,h,"GET",a)},put:async function(u,d,h,a){return await this.req(u,d,h,"PUT",a)},post:async function(u,d,h,a){return await this.req(u,d,h,"POST",a)},delete:async function(u,d,h,a){return await this.req(u,d,h,"DELETE",a)},patch:async function(u,d,h,a){return await this.req(u,d,h,"PATCH",a)},req:async function(u,d,h,m,a,f){var urled=validURL(u)?u:config.apis[a??0].baseURL+u;if(m.toString().toLowerCase()=="get"){if(urled.indexOf("?")>-1)urled=urled+"&"+pairIt(d??{});else urled=urled+"?"+pairIt(d??{})}let resa=await fetch(urled,{method:m.toString().toLowerCase(),body:m.toString().toLowerCase()=="get"?null:JSON.stringify(d??{}),headers:h??config.apis[a??0].headers});if(f)return resa;let res=await resa.text();try{return JSON.parse(res)}catch(e){return res}}};exports.API=API;function updateCore(){var libsPath=`${__dirname}`+path.sep+`files`+path.sep+`libs`;var projectJsPath=process.cwd()+path.sep+"src"+path.sep+"js"+path.sep+"lm.js";var projectCssPath=process.cwd()+path.sep+"src"+path.sep+"css"+path.sep+"mobius.css";if(!fs.existsSync(process.cwd()+path.sep+"config.json")||!fs.existsSync(process.cwd()+path.sep+"src")){console.log("This doesn't look like a LumenJS project (no config.json/src here) \u2014 run this from your project's root.");return}if(!fs.existsSync(libsPath+path.sep+"lm.js")){console.log("This CLI install has no bundled runtime to copy from \u2014 reinstall @lmjs/cli.");return}var oldSize=fs.existsSync(projectJsPath)?fs.statSync(projectJsPath).size:null;var newJs=fs.readFileSync(libsPath+path.sep+"lm.js");var newSize=newJs.length;if(oldSize===newSize){console.log("Already up to date \u2014 this project's src/js/lm.js already matches the installed @lmjs/cli's runtime ("+newSize+" bytes). Nothing to do.");return}fs.writeFileSync(projectJsPath,newJs);if(fs.existsSync(libsPath+path.sep+"mobius.css")){fs.writeFileSync(projectCssPath,fs.readFileSync(libsPath+path.sep+"mobius.css"))}console.log("Updated src/js/lm.js"+(oldSize!==null?" (was "+oldSize+" bytes, now "+newSize+" bytes)":" (was missing, now "+newSize+" bytes)")+" \u2014 matches the currently installed @lmjs/cli.")}exports.updateCore=updateCore;exports.processCommand=processCommands;exports.startServer=startServer;exports.create=create;function processCommands(cmd){var command=cmd?cmd:process.argv[2];if(command=="run"||command=="serve"){startServer()}else if(command=="create"||command=="update"){let c=process.argv.slice(3,process.argv.length);let t=lw(c[0]);create({type:t[0]=="-"?t.split("-").join(""):t,name:t[0]=="-"?c.slice(1,c.length):c})}else if(command=="update-core"){updateCore()}else if(command=="purge"){console.log("(lm purge now does the same thing as `lm update-core` \u2014 prefer that name going forward.)");updateCore()}else if(command=="build"){let cmds=process.argv;_bp(cmds)}else if(command=="login"){_vault.login()}else if(command=="api"){let sub=process.argv[3];let name=process.argv[4];if(sub=="set")_vault.apiSet(name);else if(sub=="update")_vault.apiUpdate(name);else if(sub=="get")_vault.apiGet(name);else if(sub=="list")_vault.apiList();else if(sub=="remove")_vault.apiRemove(name);else console.log("Usage: lm api <set|get|update|list|remove> [name]")}else if(command=="-v"||command=="-version"){let _pkgJsonPath=fs.existsSync(path.join(__dirname,"..","..","package.json"))?path.join(__dirname,"..","..","package.json"):path.join(__dirname,"..","package.json");console.log("LumenJS version "+require(_pkgJsonPath).version)}else{console.log("LumenJS CLI's command not found!")}}async function _bp(cmds){import("ora").then(async({default:ora,oraPromise})=>{const spinner=ora({color:"green"});spinner.succeed("Started Building Project For Production").start("Gathering Required Resources..");var projectPath=`${process.cwd()}`;var dest=projectPath+path.sep+"dist";let _views=getAllFiles(`${process.cwd()}`+path.sep+`src`+path.sep+`views`+path.sep,{},false,true);let _layoutsDir=`${process.cwd()}`+path.sep+`src`+path.sep+`layouts`+path.sep;let _layouts=fs.existsSync(_layoutsDir)?annotateLayoutRegions(getAllFiles(_layoutsDir,{},false,true)):{};let _tplsDir=`${process.cwd()}`+path.sep+`src`+path.sep+`tpls`+path.sep;let _tpls=fs.existsSync(_tplsDir)?getAllFiles(_tplsDir,{},false,true):{};validateTplsAreHtmlOnly(_tpls);var indexCode=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"index.html","utf8");var beaCSSCode=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"css"+path.sep+"mobius.css","utf8");var indexJs=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"index.js","utf8");let _hasOwnDeps=_npmBundle.hasOwnDependencies(projectPath);let _localScriptSrcs=detectLocalProjectScripts(String(indexCode));let _compiledScripts="";for(const src of _localScriptSrcs){let scriptPath=projectPath+path.sep+"src"+path.sep+src.split("/").join(path.sep).replace(/^\\|^\//,"");try{let raw=_hasOwnDeps?_npmBundle.buildEntryWithImports(scriptPath,projectPath):fs.readFileSync(scriptPath,"utf8");_compiledScripts+="\n"+compileProjectScript(raw,src);indexCode=indexCode.split(new RegExp(`<script\\b[^>]*\\bsrc\\s*=\\s*["']`+src.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+`["'][^>]*>\\s*<\\/script>`,"i")).join("")}catch(e){}}let vt=`
1
+ const fetch=require("node-fetch");const path=require("path");const fs=require("fs");const nodemon=require("nodemon");var _acorn=require("acorn");var acorn=require("acorn-loose");var _min=require("html-minifier").minify;var he=require("he");const _FD=require("ftp-deploy");const _fD=new _FD;global.astring=global.astring||require("astring");const _corePackageDir=path.dirname(require.resolve("@lmjs/core/package.json"));const _walk=require(path.join(_corePackageDir,"src","walk.js"));const _npmBundle=require(path.join(__dirname,"npm-bundle.js"));exports.hasOwnDependencies=_npmBundle.hasOwnDependencies;exports.buildEntryWithImports=_npmBundle.buildEntryWithImports;const _pluginsBundle=require(path.join(__dirname,"plugins-esbuild-plugin.js"));const _vault=require(path.join(__dirname,"vault.js"));exports.login=_vault.login;exports.apiSet=_vault.apiSet;exports.apiUpdate=_vault.apiUpdate;exports.apiGet=_vault.apiGet;exports.apiList=_vault.apiList;exports.apiRemove=_vault.apiRemove;function selectedProjectPlugins(projectRoot){try{const pkgPath=path.join(projectRoot,"package.json");if(!fs.existsSync(pkgPath))return[];const pkg=JSON.parse(fs.readFileSync(pkgPath,"utf8"));if(!pkg.dependencies)return[];return _pluginsBundle.selectedRegistryEntries(pkg.dependencies)}catch(e){return[]}}exports.selectedProjectPlugins=selectedProjectPlugins;function compileProjectScript(source,name){let ast=_acorn.parse(source,{ecmaVersion:"latest",sourceType:"script"});let topLevelNames=[];for(const stmt of ast.body){if(stmt.type==="VariableDeclaration"){for(const d of stmt.declarations){if(d.id&&d.id.type==="Identifier")topLevelNames.push(d.id.name)}}}return _walk.getWatcher(ast,{name:name||"script"},topLevelNames,"Global").code}exports.compileProjectScript=compileProjectScript;function detectLocalProjectScripts(indexHtmlSource){let found=[];let re=/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;let m;while(m=re.exec(indexHtmlSource)){let src=m[1];if(src.indexOf("/")!==0)continue;if(src==="/js/lm.js"||src==="/index.js")continue;found.push(src)}return found}exports.detectLocalProjectScripts=detectLocalProjectScripts;const CORE_Libs={BEACSS:"https://s.beacdn.com/beacss/latest",COREJS:"https://lmjs.beacdn.com/latest"};const HST_FORMAT_VERSION=1;exports.HST_FORMAT_VERSION=HST_FORMAT_VERSION;exports.getAllFiles=getAllFiles;exports.validateTplsAreHtmlOnly=validateTplsAreHtmlOnly;exports.ucwords=ucwords;exports.fetch=fetch;exports.getConfig=getConfig;function getConfig(){config={version:"1.0.0.1",server:{host:"127.0.0.1",port:"3000",ssl:{enabled:false,key:"/key.pem",cert:"/certificate.cer"}},apis:[{baseURL:"https://www.beaapis.com/1",headers:{"X-BEA-Application-ID":"YOUR_APPLICATION_ID","X-BEA-Authorization":"YOUR_REST_API_KEY"}}],ftp:{host:"ftp_host",username:"ftp_username",password:"ftp_password",remotePath:"/",concurrency:4,protocol:"ftp",port:21,ignore:[],syncOption:{delete:false,ignoreExisting:false,skipCreate:false,update:true},connectTimeout:3e4}};let configPath=process.cwd()+path.sep+`config.json`;if(fs.existsSync(configPath)){config=JSON.parse(fs.readFileSync(configPath,{encoding:"utf8"}))}return config}var config=getConfig();function ucwords(str){return(str+"").replace(/^([a-z])|\s+([a-z])/g,function($1){return $1.toUpperCase()})}function lw(s){return s.toString().toLowerCase()}exports.lw=lw;function cd(d){if(!fs.existsSync(d))fs.mkdirSync(d)}exports.cd=cd;function rd(d){if(fs.existsSync(d))fs.rmSync(d,{recursive:true,force:true})}exports.rd=rd;function create(conf){let t=conf.type=="v"||conf.type=="s"||conf.type=="t"?conf.type:"p";let n=conf.type=="v"||conf.type=="s"||conf.type=="t"?lw(conf.name[0]):conf.name.join(" ");if(t=="p"){var libsPath=`${__dirname}`+path.sep+`files`+path.sep+`libs`;var getLibs=false;var _beacssMissing=false;var _lmMissing=false;require("dns").resolve("www.google.com",function(err){if(!err){var _mobiuscssPath=libsPath+path.sep+"mobius.css";_beacssMissing=!fs.existsSync(_mobiuscssPath)||fs.statSync(_mobiuscssPath).size===0;_lmMissing=!fs.existsSync(libsPath+path.sep+"lm.js");if(_lmMissing||_beacssMissing)getLibs=true}if(getLibs){API.get(CORE_Libs.COREJS,{}).then(corejs=>{API.get(CORE_Libs.BEACSS,{}).then(mobiuscss=>{var libsPath2=`${__dirname}`+path.sep+`files`+path.sep+`libs`;cd(libsPath2);if(_lmMissing){fs.writeFileSync(libsPath2+path.sep+"lm.js",String(corejs))}if(_beacssMissing){fs.writeFileSync(libsPath2+path.sep+"mobius.css",String(mobiuscss))}var filePath3=`${process.cwd()}`+path.sep;copyDir(`${__dirname}`+path.sep+`files`+path.sep+`project`,filePath3,n);cd(filePath3+path.sep+"src");cd(filePath3+path.sep+"src"+path.sep+"css");cd(filePath3+path.sep+"src"+path.sep+"images");cd(filePath3+path.sep+"src"+path.sep+"js");let stylesFile=filePath3+path.sep+"src"+path.sep+"css"+path.sep+`styles.css`;let faviconFile=filePath3+path.sep+"src"+path.sep+`favicon.ico`;if(!fs.existsSync(stylesFile))fs.writeFileSync(stylesFile,String(""));if(!fs.existsSync(faviconFile))fs.writeFileSync(faviconFile,String(""));fs.writeFileSync(filePath3+path.sep+"src"+path.sep+"js"+path.sep+"lm.js",String(corejs));fs.writeFileSync(filePath3+path.sep+"src"+path.sep+"css"+path.sep+"mobius.css",String(mobiuscss))})}).catch(err2=>{})}else{var filePath2=`${process.cwd()}`+path.sep;copyDir(`${__dirname}`+path.sep+`files`+path.sep+`project`,filePath2,n);cd(filePath2+path.sep+"src");cd(filePath2+path.sep+"src"+path.sep+"css");cd(filePath2+path.sep+"src"+path.sep+"images");cd(filePath2+path.sep+"src"+path.sep+"js");let stylesFile=filePath2+path.sep+"src"+path.sep+"css"+path.sep+`styles.css`;let faviconFile=filePath2+path.sep+"src"+path.sep+`favicon.ico`;if(!fs.existsSync(stylesFile))fs.writeFileSync(stylesFile,String(""));if(!fs.existsSync(faviconFile))fs.writeFileSync(faviconFile,String(""));let corejs=Buffer.from(fs.readFileSync(libsPath+path.sep+"lm.js").toString());let mobiuscss=Buffer.from(fs.readFileSync(libsPath+path.sep+"mobius.css").toString());fs.writeFileSync(filePath2+path.sep+"src"+path.sep+"js"+path.sep+"lm.js",String(corejs));fs.writeFileSync(filePath2+path.sep+"src"+path.sep+"css"+path.sep+"mobius.css",String(mobiuscss))}})}else{let file=t=="s"?"sub_view.view":t=="t"?"layout.layout":"view.view";let ident=t=="s"?"SubView":t=="t"?"Template":"View";let dir=t=="t"?"layouts":"views";let ext=t=="t"?"layout":"view";let html5=Buffer.from(fs.readFileSync(`${__dirname}`+path.sep+`files`+path.sep+file).toString().split("["+ident+"Name]").join(ucwords(n)));var filePath=`${process.cwd()}`+path.sep+`src`+path.sep+dir+path.sep+`${n}.${ext}`;if(fs.existsSync(filePath)){console.log(ident+" already exists:",filePath)}else{fs.writeFileSync(filePath,html5)}}}function getAllFiles(dirPath,arrayOfFiles={},mini=false,hst2=true){files=fs.readdirSync(dirPath);files.forEach(function(file){if(fs.statSync(dirPath+path.sep+file).isDirectory()){arrayOfFiles=getAllFiles(dirPath+path.sep+file,arrayOfFiles,mini,hst2)}else{let filePath=path.join(dirPath,path.sep,file);let fileKey=Buffer.from(filePath.split(`${process.cwd()}`+path.sep).join("").split("\\").join("/")).toString("base64");if(mini){var result=_min(fs.readFileSync(filePath,{encoding:"utf8"}),{removeAttributeQuotes:false,caseSensitive:true,collapseWhitespace:true,collapseInlineTagWhitespace:true,conservativeCollapse:true,removeComments:true,minifyJS:false,minifyCSS:false,processConditionalComments:true,collapseBooleanAttributes:false,decodeEntities:false,html5:true,includeAutoGeneratedTags:true,keepClosingSlash:true,maxLineLength:null,minifyURLs:false,preserveLineBreaks:false,preventAttributesEscaping:false,processScripts:["text/html"],quoteCharacter:"",removeEmptyAttributes:true,removeEmptyElements:false,removeOptionalTags:true,removeRedundantAttributes:true,removeScriptTypeAttributes:false,removeStyleLinkTypeAttributes:true,removeTagWhitespace:false,sortAttributes:false,sortClassName:false,trimCustomFragments:true,useShortDoctype:true,continueOnParseError:true})}else if(hst2){var result=_hst(fs.readFileSync(filePath,{encoding:"utf8"}))}else{var result=fs.readFileSync(filePath,{encoding:"utf8"})}arrayOfFiles[fileKey]=result}});return arrayOfFiles}const RESERVED_BARE_ATTRS=new Set(["body","view","scoped","tpl","sl","color","time","date","datetime","up","stop","confirm","econfirm","acl","rcl","hidden","disabled","readonly","required","checked","selected","autofocus","multiple","async","defer"]);function _collectWidgetRegions(nodes,found){if(!Array.isArray(nodes))return;for(const node of nodes){if(node&&node.type==="tag"&&node.attrs){for(const attrName in node.attrs){if(Object.prototype.hasOwnProperty.call(node.attrs,attrName)&&node.attrs[attrName]===""&&!RESERVED_BARE_ATTRS.has(attrName)&&!found.includes(attrName)){found.push(attrName)}}}if(node&&Array.isArray(node.children)){_collectWidgetRegions(node.children,found)}}}function annotateLayoutRegions(layoutsObj){for(const key in layoutsObj){if(!Object.prototype.hasOwnProperty.call(layoutsObj,key))continue;let entry=layoutsObj[key];if(!entry||!entry.hst)continue;let found=[];_collectWidgetRegions(entry.hst,found);entry.regions=found}return layoutsObj}exports.annotateLayoutRegions=annotateLayoutRegions;function validateTplsAreHtmlOnly(tpls){function scan(nodes,fileKey){if(!Array.isArray(nodes))return;for(const node of nodes){if(!node)continue;if(node.type==="tag"&&node.name){let n=node.name.toLowerCase();if(n==="script"||n==="js"||n==="style"){let name=Buffer.from(fileKey,"base64").toString("utf8");throw new Error('tpls/*.tpl files are HTML-only \u2014 "'+name+'" has a <'+node.name+"> block. Templates render inside whatever scope they're used from (a :for item's own), not an isolated one, so they can't carry their own script/style. Use a view= subview instead if this needs its own state or styling.")}}if(node.children)scan(node.children,fileKey)}}for(const fileKey in tpls){if(Object.prototype.hasOwnProperty.call(tpls,fileKey)){scan(tpls[fileKey].hst,fileKey)}}}class hst{htmlVoidElements=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","isindex","keygen","link","menuitem","meta","nextid","param","source","track","wbr"];moustachePattern=/\{\s*\{\s*([\s\S]*?)\s*\}\s*\}/g;attrRE=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;tagRE=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g;whitespaceRE=/^\s*$/;empty=Object.create(null);reactiveVariables=[];constructor(html){let hst2=this.parse(html);this.reactiveVariables=this.reactiveVariables.filter((value,index,self)=>{return self.indexOf(value)===index});return{hst:hst2,"reactiveVars":this.reactiveVariables}}keepOneSpace(_t){_t=_t.replace(/\s\s/gm," ");if(/\s\s/gm.test(_t))return this.keepOneSpace(_t);return _t}_clean(_t){_t=_t.replace(/(\r?\n|\r)/gm,"");_t=_t.replace(/(\t)/gm,"");_t=this.keepOneSpace(_t);return _t.replace(/^(?:\s*\t*\r*\n*\{*)+|(?:\s*\t*\r*\n*\})+$/g,"").trim()}processAttr(n,v,res){}processForXAttr(val){let forX={"js":"","as":{"k":"","v":""},"dx":""};var val=val.trim();if(val.indexOf(";")>-1){let zxx=val.split(";");forX["dx"]=zxx[1].trim();val=zxx[0].trim()}if(val.indexOf(" as ")>-1){let arr2=val.split(" as ");let kv=[];let arr3=arr2[1].split(" ").join("").split(",");if(arr3.length>1){kv=[arr3[0],arr3[1]]}else{kv=[arr3[0]]}if(kv.length){forX["as"]["k"]=kv[0].trim();if(kv.length>1){forX["as"]["v"]=kv[1].trim()}}val=arr2[0].trim()}forX["js"]=val.trim();return forX}parseTag(tag){var res={type:"tag",name:"",isV:false,attrs:{},ax:{},evs:{},ex:{},children:[]};var tagMatch=tag.match(/<\/?([^\s]+?)[/\s>]/);if(tagMatch){res.name=tagMatch[1];res.isV=this.htmlVoidElements.includes(tagMatch[1])||tag.charAt(tag.length-2)==="/"}var reg=new RegExp(this.attrRE);var result=null;for(;;){result=reg.exec(tag);if(result===null){break}if(!result[0].trim()){continue}if(result[1]){var attr=result[1].trim();var arr=[attr,""];if(arr[0]==":else"){res.type="section";res.cond=""}if(attr.indexOf("=")>-1){arr=attr.split("=")}if(arr[0].substring(0,1)=="@"){}else{if(res.name.toLowerCase()=="icon"&&arr[0].indexOf(":")>-1&&arr[0].substr(0,1)!=":"){res.icon=arr[0]}else res.attrs[arr[0]]=arr[1]}reg.lastIndex--}else if(result[2]){let sl=result[3].trim().substring(1,result[3].length-1);sl=he.decode(sl);if(result[2]==":if"||result[2]==":else-if"||result[2]==":else"){res.type="section";res.cond=sl;if(sl){try{let condAST=acorn.parse(sl,{ecmaVersion:"latest"});let condVars=this.collectVariableUsageFromAST(condAST,{excludeBuiltins:true,extraBuiltins:[]});for(let X=0;X<condVars.length;X++){this.reactiveVariables.push(condVars[X])}}catch(e){}}}else if(result[2]==":for"){res.type="sections";res.content=sl;res.forX=this.processForXAttr(sl);if(res.forX.js){try{let forAST=acorn.parse(res.forX.js,{ecmaVersion:"latest"});let forVars=this.collectVariableUsageFromAST(forAST,{excludeBuiltins:true,extraBuiltins:[]});for(let X=0;X<forVars.length;X++){this.reactiveVariables.push(forVars[X])}}catch(e){}}}if(result[2].substring(0,1)=="@"){let max=this._getMs2(sl);res.evs[result[2]]=max[1];max[0].length?res.ex[result[2]]=max[0]:null}else{let max=this._getMs2(sl);if(res.name.toLowerCase()=="icon"&&result[2].indexOf(":")>-1&&result[2].substr(0,1)!=":"){res.icon=result[2]}else res.attrs[result[2]]=max[1];max[0].length?res.ax[result[2]]=max[0]:null}}}return res}removeComments(str){str=str.replace(/<!--[\s\S]*?(?:-->)/g,"");return str}cleanExpression(expression){let cleaned="";let inSingle=false,inDouble=false,inTemplate=false;let inRegex=false,escapeNext=false;let inBlockComment=false,inLineComment=false;for(let i=0;i<expression.length;i++){let char=expression[i];let next=expression[i+1];if(escapeNext){cleaned+=char;escapeNext=false;continue}if(inBlockComment){if(char==="*"&&next==="/"){inBlockComment=false;i++}continue}if(inLineComment){if(char==="\n"){inLineComment=false}continue}if(!inSingle&&!inDouble&&!inTemplate&&!inRegex){if(char==="/"&&next==="*"){inBlockComment=true;i++;continue}if(char==="/"&&next==="/"){inLineComment=true;i++;continue}}if(!inDouble&&!inTemplate&&!inRegex&&char==="'"&&!inSingle){inSingle=true;cleaned+=char;continue}else if(inSingle&&char==="'"){inSingle=false;cleaned+=char;continue}if(!inSingle&&!inTemplate&&!inRegex&&char==='"'&&!inDouble){inDouble=true;cleaned+=char;continue}else if(inDouble&&char==='"'){inDouble=false;cleaned+=char;continue}if(!inSingle&&!inDouble&&!inRegex&&char==="`"&&!inTemplate){inTemplate=true;cleaned+=char;continue}else if(inTemplate&&char==="`"){inTemplate=false;cleaned+=char;continue}if(!inSingle&&!inDouble&&!inTemplate&&char==="/"&&!inRegex){let prevNonSpace=cleaned.match(/\S$/);if(!prevNonSpace||/[=({[,;:?!+\-*/%&|^~<>]/.test(prevNonSpace[0])){inRegex=true}cleaned+=char;continue}else if(inRegex&&char==="/"&&expression[i-1]!=="\\"){inRegex=false;cleaned+=char;continue}if(char==="\\"&&(inSingle||inDouble||inTemplate||inRegex)){escapeNext=true;cleaned+=char;continue}if(!inSingle&&!inDouble&&!inTemplate&&!inRegex){if(/\s/.test(char)){if(cleaned[cleaned.length-1]!==" "){cleaned+=" "}continue}}cleaned+=char}return cleaned.trim()}_getMs(_t,wbt){let result="";let lastIndex=0;let _m;var _ms=[];let hasError=false;while((_m=this.moustachePattern.exec(_t))!=null){try{let AST=acorn.parse(_m[0],{ecmaVersion:"latest"});hasError=false;let mux=this._clean(_m[0]);if(wbt){if(_t.substring(_m.index-1,1)=="`"){_ms.push(mux);result+=_t.substring(lastIndex,_m.index);result+="{{"+mux+"}}";lastIndex=_m.index+_m[0].length}}else{if(_t.substring(_m.index-1,1)!="`"){_ms.push(mux);result+=_t.substring(lastIndex,_m.index);result+="{{"+mux+"}}";lastIndex=_m.index+_m[0].length}}}catch(e){hasError=true;result+=_t.substring(lastIndex,_m.index);result+="{{ /*Invalid Javascript Code*/ }}";console.log("Invalid JS",_m[0])}}if(!hasError)result+=_t.substring(lastIndex);return[_ms,result]}_getMs2(_t,wbt){let content="";let lastIndex=0;let _m;var _muxes=[];let hasError=false;while((_m=this.moustachePattern.exec(_t))!=null){try{hasError=false;let mux=this._clean(_m[0]);let JST=acorn.parse(mux,{ecmaVersion:"latest"});let rvs=[];let vss=this.collectVariableUsageFromAST(JST,{excludeBuiltins:true,extraBuiltins:[]});for(let X=0;X<vss.length;X++){rvs.push(vss[X]);this.reactiveVariables.push(vss[X])}rvs=rvs.filter((value,index,self)=>{return self.indexOf(value)===index});_muxes.push({"mus":mux,"jst":JST,"rvs":rvs});content+=_t.substring(lastIndex,_m.index);content+="{{"+mux+"}}";lastIndex=_m.index+_m[0].length}catch(e){hasError=true;content+=_t.substring(lastIndex,_m.index);content+="{{ /*Invalid Javascript Code*/ }}";console.log("Invalid JS",_m[0])}}if(!hasError)content+=_t.substring(lastIndex);_muxes=this.setMuxesIndexes(content,_muxes);return[_muxes,content]}setMuxesIndexes(content,_muxes){let muxes=[];let lastIndex=0;let i=0;let _m;while((_m=this.moustachePattern.exec(content))!=null){muxes.push({..._muxes[i],"start":_m.index,"end":_m.index+_m[0].length});lastIndex=_m.index+_m[0].length;i++}return muxes}parse(html,options){if(options===void 0){options={}}options||(options={});options.components||(options.components=this.empty);html=this.removeComments(html);var result=[];var arr=[];var current;var level=-1;var inComponent=false;var inRawText=false;var par=this;if(html.indexOf("<")!==0){var end=html.indexOf("<");let zl=end===-1?html:html.substring(0,end);let mssx=this._getMs2(zl);let textObj={type:"text",content:mssx[1],mss:mssx[0]};result.push(textObj)}html.replace(this.tagRE,async function(tag,index){if(inComponent||inRawText){if(tag!=="</"+current.name+">"){return""}else{inComponent=false;inRawText=false}}var isOpen=tag.charAt(1)!=="/";var start=index+tag.length;var nextChar=html.charAt(start);var parent;if(isOpen){level++;current=par.parseTag(tag);if(current.type==="tag"&&(current.name==="script"||current.name==="style")){inRawText=true}if(current.type==="tag"&&current.name&&options.components&&options.components[current.name]){current.type="component";inComponent=true}if(!current.isV&&!inComponent&&nextChar&&nextChar!=="<"&&Array.isArray(current.children)){let end2;if(current.name==="script"||current.name==="style"){let closeRe=new RegExp("</\\s*"+current.name+"\\s*>","i");let m=closeRe.exec(html.slice(start));end2=m?start+m.index:html.length}else{end2=html.indexOf("<",start);while(html.charAt(end2+1)==" "){end2=html.indexOf("<",start+(end2+1-start))}}let hl=html.slice(start,end2);let mssx=null;if(current.name!="script")mssx=par._getMs2(hl);let textObj={type:"text",content:current.name=="script"?"":mssx[1],...current.name=="script"?{jst:acorn.parse(hl,{ecmaVersion:"latest"})}:{mss:mssx[0]},tag:current.name};current.children.push(textObj)}if(level===0){result.push(current)}parent=arr[level-1];if(parent&&parent.children){parent.children.push(current)}arr[level]=current}if(!isOpen||current.isV){if(level>-1&&(current.isV||current.name===tag.slice(2,-1))){level--;current=level===-1?result:arr[level]}if(!inComponent&&nextChar!=="<"&&nextChar){parent=level===-1?result:arr[level].children;var _end=html.indexOf("<",start);var content=html.slice(start,_end===-1?void 0:_end);if(par.whitespaceRE.test(content)){content=" "}if(_end>-1&&level+parent.length>=0||content!==" "){if(parent&&Array.isArray(parent)){if(content!==" "){let mssx=par._getMs2(content);let textObj={type:"text",content:mssx[1],mss:mssx[0]};parent.push(textObj)}}}}}});return result}collectVariableUsageFromAST(ast,options={}){const{excludeBuiltins=true,extraBuiltins=[]}=options;const DEFAULT_BUILTINS=new Set(["undefined","NaN","Infinity","null","true","false","Object","Function","Boolean","Symbol","Error","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","Number","BigInt","Math","Date","String","RegExp","Array","Map","Set","WeakMap","WeakSet","Promise","Reflect","Proxy","Intl","JSON","Atomics","SharedArrayBuffer","ArrayBuffer","DataView","WeakRef","FinalizationRegistry","console","window","document","navigator","location","localStorage","sessionStorage","fetch","XMLHttpRequest","setTimeout","clearTimeout","setInterval","clearInterval","requestAnimationFrame","cancelAnimationFrame","process","global","globalThis","require","module","exports","Buffer","parseInt","parseFloat","isFinite","isNaN","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","escape","unescape"]);const builtinSet=new Set([...DEFAULT_BUILTINS,...extraBuiltins]);function createScope(parent=null,isFunction=false){return{parent,isFunction:!!isFunction,names:new Set}}const scopeForNode=new WeakMap;const bindingIdNodes=new WeakSet;const allDeclaredNames=new Set;function markPatternBindings(pattern,scope,kind="var"){if(!pattern)return;switch(pattern.type){case"Identifier":bindingIdNodes.add(pattern);declareInScope(pattern.name,kind,scope);allDeclaredNames.add(pattern.name);break;case"ArrayPattern":for(const el of pattern.elements)if(el)markPatternBindings(el,scope,kind);break;case"ObjectPattern":for(const p of pattern.properties){if(p.type==="Property")markPatternBindings(p.value,scope,kind);else if(p.type==="RestElement")markPatternBindings(p.argument,scope,kind)}break;case"RestElement":markPatternBindings(pattern.argument,scope,kind);break;case"AssignmentPattern":markPatternBindings(pattern.left,scope,kind);break;default:break}}function declareInScope(name,kind,currentScope){if(!name||!currentScope)return;if(kind==="var"||kind==="function"){let s=currentScope;while(s&&!s.isFunction&&s.parent)s=s.parent;s.names.add(name)}else{currentScope.names.add(name)}}function buildScopes(node,currentScope){if(!node||typeof node!=="object")return;switch(node.type){case"Program":{scopeForNode.set(node,currentScope);for(const stmt of node.body)buildScopes(stmt,currentScope);return}case"FunctionDeclaration":{if(node.id){bindingIdNodes.add(node.id);declareInScope(node.id.name,"function",currentScope);allDeclaredNames.add(node.id.name)}const fnScope=createScope(currentScope,true);scopeForNode.set(node,fnScope);for(const p of node.params)markPatternBindings(p,fnScope,"param");buildScopes(node.body,fnScope);return}case"FunctionExpression":{const fnScope=createScope(currentScope,true);scopeForNode.set(node,fnScope);if(node.id){bindingIdNodes.add(node.id);declareInScope(node.id.name,"let",fnScope);allDeclaredNames.add(node.id.name)}for(const p of node.params)markPatternBindings(p,fnScope,"param");buildScopes(node.body,fnScope);return}case"ArrowFunctionExpression":{const fnScope=createScope(currentScope,true);scopeForNode.set(node,fnScope);for(const p of node.params)markPatternBindings(p,fnScope,"param");buildScopes(node.body,fnScope);return}case"BlockStatement":case"StaticBlock":case"SwitchStatement":{const blockScope=createScope(currentScope,false);scopeForNode.set(node,blockScope);if(node.type==="SwitchStatement"){for(const c of node.cases)buildScopes(c,blockScope)}else{for(const s of node.body)buildScopes(s,blockScope)}return}case"CatchClause":{const catchScope=createScope(currentScope,false);scopeForNode.set(node,catchScope);if(node.param)markPatternBindings(node.param,catchScope,"let");buildScopes(node.body,catchScope);return}case"ForStatement":case"ForInStatement":case"ForOfStatement":{const forScope=createScope(currentScope,false);scopeForNode.set(node,forScope);if(node.init)buildScopes(node.init,forScope);if(node.left)buildScopes(node.left,forScope);if(node.test)buildScopes(node.test,forScope);if(node.update)buildScopes(node.update,forScope);buildScopes(node.body,forScope);return}case"VariableDeclaration":{for(const decl of node.declarations||[]){markPatternBindings(decl.id,currentScope,node.kind||"var");if(decl.init)buildScopes(decl.init,currentScope)}return}case"ClassDeclaration":{if(node.id){bindingIdNodes.add(node.id);declareInScope(node.id.name,"let",currentScope);allDeclaredNames.add(node.id.name)}if(node.body)buildScopes(node.body,currentScope);return}case"ImportDeclaration":{for(const spec of node.specifiers||[]){if(spec.local){bindingIdNodes.add(spec.local);declareInScope(spec.local.name,"const",currentScope);allDeclaredNames.add(spec.local.name)}}return}case"ExportNamedDeclaration":case"ExportDefaultDeclaration":case"ExportAllDeclaration":{if(node.declaration)buildScopes(node.declaration,currentScope);return}default:break}for(const key of Object.keys(node)){if(key==="loc"||key==="range")continue;const child=node[key];if(Array.isArray(child)){for(const c of child)if(c&&typeof c==="object")buildScopes(c,currentScope)}else if(child&&typeof child==="object"){buildScopes(child,currentScope)}}}const rootScope=createScope(null,true);scopeForNode.set(ast,rootScope);buildScopes(ast,rootScope);const usageSet=new Set;function isVariableUsageIdentifier(node,parent,propName){if(!parent)return true;if(bindingIdNodes.has(node))return false;if(parent.type==="LabeledStatement"&&propName==="label"||(parent.type==="BreakStatement"||parent.type==="ContinueStatement")&&propName==="label"){return false}if(parent.type==="MemberExpression"&&propName==="property"&&parent.computed===false){return false}if(parent.type==="Property"&&propName==="key"&&parent.computed===false&&!parent.shorthand){return false}if((parent.type==="MethodDefinition"||parent.type==="PropertyDefinition")&&propName==="key"&&parent.computed===false){return false}if(parent.type&&(parent.type.startsWith("Import")||parent.type.startsWith("Export")||parent.type==="MetaProperty")){return false}if((parent.type==="FunctionDeclaration"||parent.type==="FunctionExpression"||parent.type==="ClassDeclaration")&&propName==="id"){return false}if(parent.type==="VariableDeclarator"&&propName==="id"||parent.type==="CatchClause"&&propName==="param"){return false}if((parent.type==="CallExpression"||parent.type==="OptionalCallExpression")&&propName==="callee"){return false}if(parent.type==="NewExpression"&&propName==="callee"){return false}return true}const scopeStack=[rootScope];function collect(node,parent,propName,index){if(!node||typeof node!=="object")return;const nodeScope=scopeForNode.get(node);if(nodeScope)scopeStack.push(nodeScope);if(node.type==="Identifier"){if(isVariableUsageIdentifier(node,parent,propName)){const name=node.name;if(!(excludeBuiltins&&builtinSet.has(name))){usageSet.add(name)}}}for(const key of Object.keys(node)){if(key==="loc"||key==="range")continue;const child=node[key];if(Array.isArray(child)){for(let i=0;i<child.length;i++){const c=child[i];if(c&&typeof c==="object")collect(c,node,key,i)}}else if(child&&typeof child==="object"){collect(child,node,key,null)}}if(nodeScope)scopeStack.pop()}collect(ast,null,null,null);return Array.from(usageSet).sort()}}function _hst(html){return new hst(html)}function copyDir(src,dest,projectName){try{const entries=fs.readdirSync(src,{encoding:"utf8",withFileTypes:true});cd(dest);for(let entry of entries){const srcPath=path.join(src.toString(),entry.name.toString());const destPath=path.join(dest.toString(),entry.name.toString());if(entry.isDirectory()){if(projectName=="_beajsBuild"){if(entry.name!="layouts"&&entry.name!="views"&&entry.name!="css"&&entry.name!="js")copyDir(srcPath,destPath,projectName)}else copyDir(srcPath,destPath,projectName)}else{if(projectName=="_beajsBuild"){if(projectName=="_beajsBuild"&&entry.name!="index.js"&&entry.name!="index.html")fs.copyFileSync(srcPath,destPath)}else{if(!fs.existsSync(destPath)){if(projectName){if(entry.name=="index.html"){let html5=Buffer.from(fs.readFileSync(srcPath).toString().split("[ProjectName]").join(ucwords(projectName)));fs.writeFileSync(destPath,html5)}else if(entry.name=="package.json"){let slug=lw(projectName).replace(/[^a-z0-9._-]+/g,"-").replace(/^[-.]+|[-.]+$/g,"")||"lumenjs-project";let pkgJson=Buffer.from(fs.readFileSync(srcPath).toString().split("[ProjectName]").join(slug));fs.writeFileSync(destPath,pkgJson)}else fs.copyFileSync(srcPath,destPath)}else fs.copyFileSync(srcPath,destPath)}else{console.log("File already exists:",destPath)}}}}}catch(e){console.log(e)}}exports.copyDir=copyDir;function validURL(string){let url;try{url=new URL(string)}catch(_){return false}return url.protocol==="http:"||url.protocol==="https:"}exports.validURL=validURL;let getPairs=(obj,keys=[])=>Object.entries(obj).reduce((pairs,[key,value])=>{if(typeof value==="object")pairs.push(...getPairs(value,[...keys,key]));else pairs.push([[...keys,key],value]);return pairs},[]);function pairIt(obj){return getPairs(obj).map(([[key0,...keysRest],value])=>`${key0}${keysRest.map(a=>`[${a}]`).join("")}=${value}`).join("&")}var API={get:async function(u,d,h,a){return await this.req(u,d,h,"GET",a)},put:async function(u,d,h,a){return await this.req(u,d,h,"PUT",a)},post:async function(u,d,h,a){return await this.req(u,d,h,"POST",a)},delete:async function(u,d,h,a){return await this.req(u,d,h,"DELETE",a)},patch:async function(u,d,h,a){return await this.req(u,d,h,"PATCH",a)},req:async function(u,d,h,m,a,f){var urled=validURL(u)?u:config.apis[a??0].baseURL+u;if(m.toString().toLowerCase()=="get"){if(urled.indexOf("?")>-1)urled=urled+"&"+pairIt(d??{});else urled=urled+"?"+pairIt(d??{})}let resa=await fetch(urled,{method:m.toString().toLowerCase(),body:m.toString().toLowerCase()=="get"?null:JSON.stringify(d??{}),headers:h??config.apis[a??0].headers});if(f)return resa;let res=await resa.text();try{return JSON.parse(res)}catch(e){return res}}};exports.API=API;function updateCore(){var libsPath=`${__dirname}`+path.sep+`files`+path.sep+`libs`;var projectJsPath=process.cwd()+path.sep+"src"+path.sep+"js"+path.sep+"lm.js";var projectCssPath=process.cwd()+path.sep+"src"+path.sep+"css"+path.sep+"mobius.css";if(!fs.existsSync(process.cwd()+path.sep+"config.json")||!fs.existsSync(process.cwd()+path.sep+"src")){console.log("This doesn't look like a LumenJS project (no config.json/src here) \u2014 run this from your project's root.");return}if(!fs.existsSync(libsPath+path.sep+"lm.js")){console.log("This CLI install has no bundled runtime to copy from \u2014 reinstall @lmjs/cli.");return}var oldSize=fs.existsSync(projectJsPath)?fs.statSync(projectJsPath).size:null;var newJs=fs.readFileSync(libsPath+path.sep+"lm.js");var newSize=newJs.length;if(oldSize===newSize){console.log("Already up to date \u2014 this project's src/js/lm.js already matches the installed @lmjs/cli's runtime ("+newSize+" bytes). Nothing to do.");return}fs.writeFileSync(projectJsPath,newJs);if(fs.existsSync(libsPath+path.sep+"mobius.css")){fs.writeFileSync(projectCssPath,fs.readFileSync(libsPath+path.sep+"mobius.css"))}console.log("Updated src/js/lm.js"+(oldSize!==null?" (was "+oldSize+" bytes, now "+newSize+" bytes)":" (was missing, now "+newSize+" bytes)")+" \u2014 matches the currently installed @lmjs/cli.")}exports.updateCore=updateCore;exports.processCommand=processCommands;exports.startServer=startServer;exports.create=create;function processCommands(cmd){var command=cmd?cmd:process.argv[2];if(command=="run"||command=="serve"){startServer()}else if(command=="create"||command=="update"){let c=process.argv.slice(3,process.argv.length);let t=lw(c[0]);create({type:t[0]=="-"?t.split("-").join(""):t,name:t[0]=="-"?c.slice(1,c.length):c})}else if(command=="update-core"){updateCore()}else if(command=="purge"){console.log("(lm purge now does the same thing as `lm update-core` \u2014 prefer that name going forward.)");updateCore()}else if(command=="build"){let cmds=process.argv;_bp(cmds)}else if(command=="login"){_vault.login()}else if(command=="api"){let sub=process.argv[3];let name=process.argv[4];if(sub=="set")_vault.apiSet(name);else if(sub=="update")_vault.apiUpdate(name);else if(sub=="get")_vault.apiGet(name);else if(sub=="list")_vault.apiList();else if(sub=="remove")_vault.apiRemove(name);else console.log("Usage: lm api <set|get|update|list|remove> [name]")}else if(command=="-v"||command=="-version"){let _pkgJsonPath=fs.existsSync(path.join(__dirname,"..","..","package.json"))?path.join(__dirname,"..","..","package.json"):path.join(__dirname,"..","package.json");console.log("LumenJS version "+require(_pkgJsonPath).version)}else{console.log("LumenJS CLI's command not found!")}}async function _bp(cmds){import("ora").then(async({default:ora,oraPromise})=>{const spinner=ora({color:"green"});spinner.succeed("Started Building Project For Production").start("Gathering Required Resources..");var projectPath=`${process.cwd()}`;var dest=projectPath+path.sep+"dist";let _views=getAllFiles(`${process.cwd()}`+path.sep+`src`+path.sep+`views`+path.sep,{},false,true);let _layoutsDir=`${process.cwd()}`+path.sep+`src`+path.sep+`layouts`+path.sep;let _layouts=fs.existsSync(_layoutsDir)?annotateLayoutRegions(getAllFiles(_layoutsDir,{},false,true)):{};let _tplsDir=`${process.cwd()}`+path.sep+`src`+path.sep+`tpls`+path.sep;let _tpls=fs.existsSync(_tplsDir)?getAllFiles(_tplsDir,{},false,true):{};validateTplsAreHtmlOnly(_tpls);var indexCode=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"index.html","utf8");var beaCSSCode=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"css"+path.sep+"mobius.css","utf8");var indexJs=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"index.js","utf8");let _hasOwnDeps=_npmBundle.hasOwnDependencies(projectPath);let _localScriptSrcs=detectLocalProjectScripts(String(indexCode));let _compiledScripts="";for(const src of _localScriptSrcs){let scriptPath=projectPath+path.sep+"src"+path.sep+src.split("/").join(path.sep).replace(/^\\|^\//,"");try{let raw=_hasOwnDeps?_npmBundle.buildEntryWithImports(scriptPath,projectPath):fs.readFileSync(scriptPath,"utf8");_compiledScripts+="\n"+compileProjectScript(raw,src);indexCode=indexCode.split(new RegExp(`<script\\b[^>]*\\bsrc\\s*=\\s*["']`+src.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+`["'][^>]*>\\s*<\\/script>`,"i")).join("")}catch(e){}}let vt=`
2
2
  var _vcData = {
3
3
  "hstFormatVersion": `+HST_FORMAT_VERSION+`,
4
4
  "views": `+JSON.stringify(_views)+`,