@lmjs/cli 2.8.5 → 2.9.0
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/app.js +2 -2
- package/dist/lib/fcs.js +2 -2
- package/dist/lib/files/project/AGENTS.md +374 -25
- package/package.json +2 -2
package/dist/lib/app.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var fs=require("fs");const path=require("path");const chokidar=require("chokidar");const express=require("express");var compression=require("compression");const app=express();const server=require("http").createServer(app);var WebSocketServer=require("ws").Server;var wss=new WebSocketServer({server,path:"/"});const fcs=require("./fcs.js");var cl=console.log;var cookieParser=require("cookie-parser");var expressSession=require("express-session");
|
|
2
|
-
<script src="/js/lumenjs-plugins.js" type="text/javascript"><\/script>`}if(tags)html=html.split("</head>").join(tags+"\n</head>");if(_pluginsCss&&_pluginsCss.trim()!=""&&html.indexOf("/css/lumenjs-plugins.css")==-1){html=fcs.placePluginsCss(html,`<link href="/css/lumenjs-plugins.css" rel="stylesheet" type="text/css" />`)}if(_copilot)html=_copilot.inject(html,req);res.type("text/html").send(html)}app.use("/",async function(req,res,next){if(req.path==="/"||req.path==="/index.html"){sendIndexHtml(res,req);return}if(req.path==="/js/lm.js"&&!fs.existsSync(`${process.cwd()}`+path.sep+`src`+path.sep+`js`+path.sep+`lm.js`)){res.type("application/javascript").sendFile(path.join(__dirname,"files","libs","lm.js"));return}if(Object.prototype.hasOwnProperty.call(_compiledScripts,req.path)){res.type("application/javascript").send(_compiledScripts[req.path]);return}if(req.path==="/js/lumenjs-plugins.js"||req.path==="/css/lumenjs-plugins.css"){if(_pluginsBuildPromise){try{await _pluginsBuildPromise}catch(e){}}if(req.path==="/js/lumenjs-plugins.js"&&_pluginsJs!=null){res.type("application/javascript").send(_pluginsJs);return}if(req.path==="/css/lumenjs-plugins.css"&&_pluginsCss!=null){res.type("text/css").send(_pluginsCss);return}}next()});app.use("/",express.static(`${process.cwd()}`+path.sep+`src`));app.set("etag",false);app.use(
|
|
1
|
+
var fs=require("fs");const path=require("path");const chokidar=require("chokidar");const express=require("express");var compression=require("compression");const app=express();const server=require("http").createServer(app);var WebSocketServer=require("ws").Server;var wss=new WebSocketServer({server,path:"/"});const fcs=require("./fcs.js");var cl=console.log;var cookieParser=require("cookie-parser");var expressSession=require("express-session");var multer=require("multer");var upload=multer();let session=expressSession({secret:"keyboardcat",resave:true,saveUninitialized:true,cookie:{maxAge:9999e3}});var config=fcs.getConfig();var _views={};var _layouts={};var _tpls={};function readTpls(){return fcs.readTemplates(`${process.cwd()}`)}function readLayouts(){let dir=`${process.cwd()}`+path.sep+`src`+path.sep+`layouts`+path.sep;return fs.existsSync(dir)?fcs.linkTemplateReactiveVars(fcs.annotateLayoutRegions(fcs.getAllFiles(dir,{},false,true)),_tpls):{}}function readViews(){let dir=`${process.cwd()}`+path.sep+`src`+path.sep+`views`+path.sep;return fs.existsSync(dir)?fcs.linkTemplateReactiveVars(fcs.getAllFiles(dir,{},false,true),_tpls):{}}var _lmServerErrors=[];var _compiledScripts={};(function buildCompiledScriptsMap(){try{var projectRoot=`${process.cwd()}`;var srcRoot=projectRoot+path.sep+`src`;var hasOwnDeps=fcs.hasOwnDependencies(projectRoot);var indexJsPath=srcRoot+path.sep+"index.js";if(fs.existsSync(indexJsPath)){var indexJsSrc=hasOwnDeps?fcs.buildEntryWithImports(indexJsPath,projectRoot):fs.readFileSync(indexJsPath,"utf8");_compiledScripts["/index.js"]=fcs.compileProjectScript(indexJsSrc,"index")}var indexHtmlPath=srcRoot+path.sep+"index.html";if(fs.existsSync(indexHtmlPath)){var localSrcs=fcs.detectLocalProjectScripts(fs.readFileSync(indexHtmlPath,"utf8"));for(const src of localSrcs){var scriptPath=srcRoot+src.split("/").join(path.sep);if(fs.existsSync(scriptPath)){var scriptSrc=hasOwnDeps?fcs.buildEntryWithImports(scriptPath,projectRoot):fs.readFileSync(scriptPath,"utf8");_compiledScripts[src]=fcs.compileProjectScript(scriptSrc,src)}}}}catch(e){cl("Failed to compile index.js / project scripts for reactivity \u2014 serving them raw. "+e.message);_lmServerErrors.push("Failed to compile index.js / project scripts: "+e.message)}})();var _pluginsJs=null;var _pluginsCss=null;var _pluginsBuildPromise=null;_pluginsBuildPromise=(async function buildSelectedPluginsBundle(){try{var projectRoot=`${process.cwd()}`;var selected=fcs.selectedProjectPlugins(projectRoot);if(!selected.length)return;var pluginsEsbuild=require(path.join(__dirname,"plugins-esbuild-plugin.js"));_pluginsJs=await pluginsEsbuild.buildSelectedPluginsBundle(selected,projectRoot);_pluginsCss=await pluginsEsbuild.buildSelectedCss(selected,projectRoot+path.sep+"node_modules")}catch(e){cl("Failed to build the selective plugins bundle \u2014 "+e.message)}})();app.use(compression());app.use(cookieParser());app.use(session);var _copilot=null;try{const _copilotServer=require(path.join(__dirname,"copilot","server.js"));if(_copilotServer.isEnabled(config)){_copilot=_copilotServer.mount(app,{root:`${process.cwd()}`,token:process.env.LM_COPILOT_TOKEN||require("crypto").randomBytes(24).toString("hex"),getPort:function(){var a=server.address();return a?a.port:0}})}}catch(e){cl("Lumen Copilot is off: "+e.message);_copilot=null}async function sendIndexHtml(res,req){let file=`${process.cwd()}`+path.sep+`src`+path.sep+`index.html`;let html=fcs.v1CompatIndexHtml(fs.readFileSync(file,"utf8"));if(_pluginsBuildPromise){try{await _pluginsBuildPromise}catch(e){}}let tags="";if(_pluginsJs!=null&&html.indexOf("/js/lumenjs-plugins.js")==-1){tags+=`
|
|
2
|
+
<script src="/js/lumenjs-plugins.js" type="text/javascript"><\/script>`}if(tags)html=html.split("</head>").join(tags+"\n</head>");if(_pluginsCss&&_pluginsCss.trim()!=""&&html.indexOf("/css/lumenjs-plugins.css")==-1){html=fcs.placePluginsCss(html,`<link href="/css/lumenjs-plugins.css" rel="stylesheet" type="text/css" />`)}if(_copilot)html=_copilot.inject(html,req);res.type("text/html").send(html)}app.use("/",async function(req,res,next){if(req.path==="/"||req.path==="/index.html"){sendIndexHtml(res,req);return}if(req.path==="/js/lm.js"&&!fs.existsSync(`${process.cwd()}`+path.sep+`src`+path.sep+`js`+path.sep+`lm.js`)){res.type("application/javascript").sendFile(path.join(__dirname,"files","libs","lm.js"));return}if(Object.prototype.hasOwnProperty.call(_compiledScripts,req.path)){res.type("application/javascript").send(_compiledScripts[req.path]);return}if(req.path==="/js/lumenjs-plugins.js"||req.path==="/css/lumenjs-plugins.css"){if(_pluginsBuildPromise){try{await _pluginsBuildPromise}catch(e){}}if(req.path==="/js/lumenjs-plugins.js"&&_pluginsJs!=null){res.type("application/javascript").send(_pluginsJs);return}if(req.path==="/css/lumenjs-plugins.css"&&_pluginsCss!=null){res.type("text/css").send(_pluginsCss);return}}next()});app.use("/",express.static(`${process.cwd()}`+path.sep+`src`));app.set("etag",false);app.use(express.urlencoded({extended:true}));app.use(express.json());app.use(express.raw());app.use(upload.array());wss.on("connection",ws=>{ws.on("message",async message=>{try{const buffer=Buffer.from(message);const data=JSON.parse(buffer.toString());if(data.hasOwnProperty("e")){var _data={"e":data.e,"_iter":data._iter,"payload":{}};if(data.e=="getfiles"){_data["payload"]={"hstFormatVersion":fcs.HST_FORMAT_VERSION,"views":_views,"layouts":_layouts,"tpls":_tpls}}else if(data.e=="getlayout"){_data.payload=_layouts[data.payload]}else if(data.e=="getview"){_data.payload=_views[data.payload]}else if(data.e=="gettpl"){_data.payload=_tpls[data.payload]}else if(data.e=="request"){try{let pata=data.payload;let __data=pata["data"];let _body=pata["body"];var resa=await API.req(_body["path"],__data,_body["headers"],_body["method"],_body["api"],true);let res=await resa.text();try{res=JSON.parse(res)}catch(e){}_data.payload=_body["full"]?{"headers":resa.headers,"data":res}:res;ws.send(JSON.stringify(_data))}catch(e){_data.payload={"code":108,"error":e.message,"type":"RequestError"};ws.send(JSON.stringify(_data))}return}ws.send(JSON.stringify(_data))}}catch(e){}})}).on("error",e=>{});global.app=app;var fetch=fcs.fetch;global.fetch=fetch;global.wss=wss;global.fs=fs;global.path=path;var API=fcs.API;global.API=API;if(fs.existsSync(`${process.cwd()}`+path.sep+`src`+path.sep+`app.js`)){require(`${process.cwd()}`+path.sep+`src`+path.sep+`app.js`)}app.get("*",function(req,res){let nodes=req.params[0].split("/");if(nodes.length)nodes.shift();if(fs.existsSync(`${process.cwd()}`+path.sep+`src`+path.sep+`views`+path.sep+nodes[0]+`.view`))sendIndexHtml(res,req);else res.sendFile(`${process.cwd()}`+path.sep+`src`+path.sep+`404.html`);return});app.post("*",function(req,res){let nodes=req.params[0].split("/");if(nodes.length)nodes.shift();if(fs.existsSync(`${process.cwd()}`+path.sep+`src`+path.sep+`views`+path.sep+nodes[0]+`.view`))sendIndexHtml(res,req);else res.sendFile(`${process.cwd()}`+path.sep+`src`+path.sep+`404.html`);return});function broadcastFilesChanged(){wss.clients.forEach(function(client){if(client.readyState===1){client.send(JSON.stringify({e:"files-changed"}))}})}chokidar.watch(`${process.cwd()}`+path.sep+`src`+path.sep+`views`,{ignoreInitial:true}).on("all",function(){_views=readViews();broadcastFilesChanged()});chokidar.watch(`${process.cwd()}`+path.sep+`src`+path.sep+`layouts`,{ignoreInitial:true}).on("all",function(){_layouts=readLayouts();broadcastFilesChanged()});chokidar.watch([`${process.cwd()}`+path.sep+`src`+path.sep+`tpls`,`${process.cwd()}`+path.sep+`src`+path.sep+`comps`],{ignoreInitial:true}).on("all",function(){_tpls=readTpls();_views=readViews();_layouts=readLayouts();broadcastFilesChanged()});var _lmBasePort=Number(config.server.port)>0?Number(config.server.port):0;var _lmOriginalPortRetries=0;var _LM_MAX_ORIGINAL_PORT_RETRIES=10;var _lmFallbackAttempt=0;var _LM_MAX_FALLBACK_ATTEMPTS=20;function lmStartListening(port){server.listen(port)}server.on("listening",function(){cl(`LumenJS server running at http://${config.server.host}:${server.address().port}/`);if(_copilot){_lmServerErrors.splice(0).forEach(function(m){_copilot.noteServerError(m)});if(!require(path.join(__dirname,"copilot","auth.js")).hasCredentials()){cl("Lumen Copilot (AI help on this page): run `lm login` to turn it on. New Roxyon accounts get $0.50 of free credit.")}}fcs.checkProjectRuntime(process.cwd());config.server.port=server.address().port;_tpls=readTpls();_views=readViews();_layouts=readLayouts()});server.on("error",e=>{if(e.code!=="EADDRINUSE")throw e;if(_lmBasePort>0&&_lmOriginalPortRetries<_LM_MAX_ORIGINAL_PORT_RETRIES){_lmOriginalPortRetries++;cl("Port "+_lmBasePort+" is in use (likely still being released by a previous run) \u2014 retrying ("+_lmOriginalPortRetries+"/"+_LM_MAX_ORIGINAL_PORT_RETRIES+")...");setTimeout(()=>lmStartListening(_lmBasePort),300);return}if(_lmFallbackAttempt<_LM_MAX_FALLBACK_ATTEMPTS){_lmFallbackAttempt++;let fallbackPort=(_lmBasePort>0?_lmBasePort:3e3)+_lmFallbackAttempt;cl("Port "+_lmBasePort+" is already in use \u2014 falling back to "+fallbackPort+"..");lmStartListening(fallbackPort);return}cl("Could not find a free port after "+_LM_MAX_FALLBACK_ATTEMPTS+" attempts starting from "+_lmBasePort+".")});lmStartListening(_lmBasePort);
|
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");const _hstLib=require("./hst.js");const{parseScriptJs,scriptPayload,stripAstPositions,annotateLayoutRegions,hst_markSvg,hst_orderIfFor,_hst}=_hstLib;exports.scriptPayload=scriptPayload;exports.stripAstPositions=stripAstPositions;exports.annotateLayoutRegions=annotateLayoutRegions;exports.hst_orderIfFor=hst_orderIfFor;function precompileViewScripts(groups){let failed=0;function visit(nodes,vars,inSection,file){if(!Array.isArray(nodes))return;for(const n of nodes){if(!n||n.type==="text")continue;const sectioned=inSection||n.type==="section"||n.type==="sections";const nm=String(n.name||"").toLowerCase();if((nm==="script"||nm==="js")&&Array.isArray(n.children)&&n.children[0]&&n.children[0].type==="text"){const t=n.children[0];if(t.content||t.jst){try{const ast=t.jst||_acorn.parse(t.content,{ecmaVersion:"latest",sourceType:"script"});const code=_walk.getWatcher(ast,{name:file},sectioned?void 0:(vars||[]).slice(),["__LMROOT__"]).code;new Function(code);t.pre=code;delete t.content;delete t.jst}catch(e){failed++;console.warn("\x1B[33mLumenJS: could not precompile a <script> in "+file+": "+(e&&e.message)+" (it will be compiled in the browser)\x1B[0m")}}}visit(n.children,vars,sectioned,file)}}for(const group of groups){const isTpl=group.kind==="tpls";for(const key in group.files){const entry=group.files[key];if(!entry||!Array.isArray(entry.hst))continue;const file=Buffer.from(key,"base64").toString().split(/[\\/]/).slice(-2).join("/");visit(entry.hst,entry.reactiveVars,isTpl,file)}}return failed}exports.precompileViewScripts=precompileViewScripts;const stripDevOnlyRuntime=require("./cdn-runtime.js").stripDevOnlyRuntime;exports.stripDevOnlyRuntime=stripDevOnlyRuntime;const _HST_EMPTY_OBJ={attrs:1,ax:1,evs:1,ex:1};function compactHstReplacer(key,value){if(_HST_EMPTY_OBJ[key]===1&&value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).length===0)return void 0;if(key==="isV"&&value===false)return void 0;if((key==="mss"||key==="children")&&Array.isArray(value)&&value.length===0)return void 0;return value}exports.compactHstReplacer=compactHstReplacer;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"));const _cdnRt=require(path.join(__dirname,"cdn-runtime.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{let deps={};const pkgPath=path.join(projectRoot,"package.json");if(fs.existsSync(pkgPath)){const pkg=JSON.parse(fs.readFileSync(pkgPath,"utf8"));Object.assign(deps,pkg.dependencies||{})}for(const key of detectUsedPlugins(projectRoot))if(!deps.hasOwnProperty(key))deps[key]="*";if(!Object.keys(deps).length)return[];return _pluginsBundle.selectedRegistryEntries(deps)}catch(e){return[]}}exports.selectedProjectPlugins=selectedProjectPlugins;const PLUGIN_SIGNATURES={"select2":[/\.select2\s*\(/,/<[a-z][^>]*\s(?:sl|slct)(?=[\s>=\/])/i],"flickity":[/\.flickity\s*\(/,/\bFlickity\b/,/<[a-z][^>]*\scrslf(?=[\s>=\/])/i],"bootstrap-colorpicker":[/\.colorpicker\s*\(/,/<input[^>]*\scolor(?=[\s>=\/])/i],"bootstrap-datetimepicker":[/\.datetimepicker\s*\(/,/<input[^>]*\s(?:date|time|datetime)(?=[\s>=\/])/i],"jquery-ui-dist":[/\.(?:sortable|draggable|droppable|resizable|datepicker|autocomplete|slider|accordion)\s*\(/,/<[a-z][^>]*\s(?:sort|drag|drop)(?=[\s>=\/])/i],"jquery.easing":[/\beas(?:e|ing)(?:In|Out)[A-Z]\w*/],"nestedSortable":[/\.nestedSortable\s*\(/],"jquery.numeric":[/\.numeric\s*\(/,/<input[^>]*\s(?:numeric|integer|decimal)(?=[\s>=\/])/i],"timeago":[/\.timeago\s*\(/,/\$\.timeago\b/],"slick-carousel":[/\.(?:crsl|slick)\s*\(/,/<[a-z][^>]*\scrsl(?=[\s>=\/])/i],"@iconify/iconify":[/class=["'][^"']*\biconify\b/,/\bIconify\./],"rellax":[/\bRellax\b/],"headroom.js":[/\bHeadroom\b/,/<[a-z][^>]*\spinnable(?=[\s>=\/])/i],"in-view":[/\binView\b/],"gsap":[/\bgsap\b/,/\bTween(?:Max|Lite)\b/,/\bTimeline(?:Max|Lite)\b/],"jquery.caret":[/\.caret\s*\(/],"jquery-tageditor":[/\.tagEditor\s*\(/,/<[a-z][^>]*\stags(?=[\s>=\/])/i],"jquery-lazy":[/\.lazy\s*\(/,/<img[^>]*\slazy(?=[\s>=\/])/i]};function detectUsedPlugins(projectRoot){const src=path.join(projectRoot,"src");if(!fs.existsSync(src))return[];let indexHtml="";try{indexHtml=fs.readFileSync(path.join(src,"index.html"),"utf8")}catch(e){}const texts=[];(function walk(dir){let entries;try{entries=fs.readdirSync(dir,{withFileTypes:true})}catch(e){return}for(const e of entries){const p=path.join(dir,e.name);if(e.isDirectory()){if(e.name==="node_modules"||e.name==="js"||e.name==="css"||e.name==="images")continue;walk(p)}else if(/\.(view|tpl|layout)$/.test(e.name)){try{texts.push(fs.readFileSync(p,"utf8"))}catch(x){}}}})(src);try{texts.push(fs.readFileSync(path.join(src,"index.js"),"utf8"))}catch(e){}for(const s of detectLocalProjectScripts(indexHtml)){try{texts.push(fs.readFileSync(path.join(src,s.replace(/^\//,"")),"utf8"))}catch(e){}}const all=texts.join("\n");const loadedByPage=key=>new RegExp(`<script[^>]+src=["'][^"']*`+key.replace(/^@[^/]+\//,"").replace(/\.js$/,"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i").test(indexHtml);const found=[];for(const key in PLUGIN_SIGNATURES){if(loadedByPage(key))continue;if(PLUGIN_SIGNATURES[key].some(re=>re.test(all)))found.push(key)}return found}exports.detectUsedPlugins=detectUsedPlugins;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 placePluginsCss(html,cssTag){html=String(html);let at=html.search(/<link\b[^>]*href=["']\/css\//i);return at>=0?html.slice(0,at)+cssTag+"\n "+html.slice(at):html.split("</head>").join(" "+cssTag+"\n</head>")}exports.placePluginsCss=placePluginsCss;function detectLocalProjectScripts(indexHtmlSource){let found=[];let re=/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;let m;indexHtmlSource=String(indexHtmlSource).replace(/<!--[\s\S]*?-->/g,"");while(m=re.exec(indexHtmlSource)){let src=m[1];if(src.indexOf("/")!==0)continue;if(src==="/js/lm.js"||src==="/index.js")continue;if(/^\/js\/bea\.js(\?|$)/.test(src))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=3;exports.HST_FORMAT_VERSION=HST_FORMAT_VERSION;function checkProjectRuntime(projectPath){try{let lm=fs.readFileSync(path.join(projectPath,"src","js","lm.js"),"utf8");let m=/EXPECTED_HST_FORMAT_VERSION\s*=\s*(\d+)/.exec(lm);let accepts=/_HST_FORMATS_ACCEPTED\s*=\s*\[([\d,\s]+)\]/.exec(lm);let ok=accepts?accepts[1].split(",").map(Number).indexOf(HST_FORMAT_VERSION)>-1:m&&Number(m[1])===HST_FORMAT_VERSION;if(m&&!ok){console.warn("\n\x1B[33mLumenJS: src/js/lm.js is older than this CLI (it expects HST v"+m[1]+", this CLI emits v"+HST_FORMAT_VERSION+"). Run `lm update-core` to update the project's runtime.\x1B[0m\n");return false}}catch(e){}return true}exports.checkProjectRuntime=checkProjectRuntime;exports.getAllFiles=getAllFiles;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,hst=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,hst)}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(hst){var result=_hst(fs.readFileSync(filePath,{encoding:"utf8"}))}else{var result=fs.readFileSync(filePath,{encoding:"utf8"})}arrayOfFiles[fileKey]=result}});return arrayOfFiles}function v1CompatIndexHtml(html){return String(html).replace(/(<script\b[^>]*\bsrc=["'])\/?js\/bea\.js(?:\?[^"']*)?(["'])/gi,"$1/js/lm.js$2").replace(/<script\b[^>]*\bsrc=["']\/?index\.js(?:\?[^"']*)?["'][^>]*>\s*<\/script>\s*/gi,"").replace(/<script\b[^>]*\bsrc=["'](?:https?:)?\/\/(?:s\.|www\.)?beacdn\.com\/beajs\/[^"']*["'][^>]*>\s*<\/script>\s*/gi,"").replace(/<script\b[^>]*\bsrc=["'](?:https?:)?\/\/lmjs\.beacdn\.com\/[^"']*["'][^>]*>\s*<\/script>\s*/gi,"")}exports.v1CompatIndexHtml=v1CompatIndexHtml;function readTemplates(root){let out={};for(const folder of["tpls","comps"]){let dir=root+path.sep+"src"+path.sep+folder+path.sep;if(fs.existsSync(dir))Object.assign(out,getAllFiles(dir,{},false,true))}return out}exports.readTemplates=readTemplates;function linkTemplateReactiveVars(files2,templates){function templateFor(attrs){let name=String(attrs.tpl).replace(/^\/+/,"");for(const f of["tpls","comps"]){let key=Buffer.from("src/"+f+"/"+name+".tpl").toString("base64");if(templates[key])return templates[key]}return null}function scan(nodes,add){if(!Array.isArray(nodes))return;for(const node of nodes){if(!node)continue;let a=node.attrs;if(a&&node.type==="sections"&&a.hasOwnProperty("tpl")){let t=templateFor(a);if(t)(t.reactiveVars||[]).forEach(add)}if(a&&a.hasOwnProperty("view")){let sv=viewFor(a.view);if(sv)(sv.reactiveVars||[]).forEach(add)}if(node.children)scan(node.children,add);if(Array.isArray(node.content))scan(node.content,add)}}let viewByPath={};for(const key in files2){let p=Buffer.from(key,"base64").toString().replace(/\\/g,"/");let m=p.match(/(?:^|\/)views\/(.+)\.view$/);if(m)viewByPath[m[1]]=files2[key]}function viewFor(v){let p=String(v).trim().replace(/^\/+/,"").replace(/\.view$/,"");if(!p||/\{\{/.test(p))return null;return viewByPath[p]||null}for(let pass=0;pass<10;pass++){let grew=false;for(const key in files2){let entry=files2[key];if(!entry||!Array.isArray(entry.hst))continue;if(!Array.isArray(entry.reactiveVars))entry.reactiveVars=[];scan(entry.hst,function(n){if(entry.reactiveVars.indexOf(n)===-1){entry.reactiveVars.push(n);grew=true}})}if(!grew)break}for(const key in files2){let entry=files2[key];if(!entry||!Array.isArray(entry.hst))continue;if(!Array.isArray(entry.reactiveVars))entry.reactiveVars=[];scan(entry.hst,function(n){if(entry.reactiveVars.indexOf(n)===-1)entry.reactiveVars.push(n)})}return files2}exports.linkTemplateReactiveVars=linkTemplateReactiveVars;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}addAgentFiles(process.cwd());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;function addAgentFiles(projectPath){var tplDir=path.join(__dirname,"files","project");var added=[];["AGENTS.md","CLAUDE.md"].forEach(function(f){var dest=path.join(projectPath,f);if(!fs.existsSync(dest)&&fs.existsSync(path.join(tplDir,f))){fs.copyFileSync(path.join(tplDir,f),dest);added.push(f)}});if(added.length)console.log("Added "+added.join(" + ")+" (points AI coding agents at the LumenJS reference).");return added}exports.addAgentFiles=addAgentFiles;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);if(!c.length||String(c[0])[0]=="-"&&c.length<2){console.log("Usage: lm create <project name> (or lm create -v|-s|-t <name> for a view, sub-view or layout)");return}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=="cdn-files"){_cdnRt.writeCdnFiles(process.argv[3]||"cdn",stripDevOnlyRuntime)}else if(command=="login"){require(path.join(__dirname,"copilot","auth.js")).loginCommand(process.argv.slice(3))}else if(command=="logout"){require(path.join(__dirname,"copilot","auth.js")).logout()}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()}`;if(!checkProjectRuntime(projectPath)){spinner.fail("Build stopped: run `lm update-core` first, then build again.");process.exit(1)}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 _tpls=readTemplates(`${process.cwd()}`);linkTemplateReactiveVars(_views,_tpls);linkTemplateReactiveVars(_layouts,_tpls);var indexCode=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"index.html","utf8");let _cssDir=projectPath+path.sep+`src`+path.sep+"css"+path.sep;let _mainCssName=["mobius.css","bea.css"].find(f=>fs.existsSync(_cssDir+f))||null;var beaCSSCode=_mainCssName?fs.readFileSync(_cssDir+_mainCssName,"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 _uncompiledScripts=precompileViewScripts([{kind:"views",files:_views},{kind:"layouts",files:_layouts},{kind:"tpls",files:_tpls}]);let _projectRuntime=projectPath+path.sep+"src"+path.sep+"js"+path.sep+"lm.js";let ownRuntime=fs.readFileSync(fs.existsSync(_projectRuntime)?_projectRuntime:path.join(__dirname,"files","libs","lm.js"),"utf8");let _runtimePlan=_cdnRt.planRuntime({cmds,config,ownRuntime,precompiled:_uncompiledScripts===0,stripDevOnlyRuntime});if(_runtimePlan&&_runtimePlan.skipped){spinner.info("Runtime kept inside app.js: "+_runtimePlan.skipped).start("Gathering Required Resources");_runtimePlan=null}let _split=_cdnRt.splitViews(_views,compactHstReplacer,{cmds,config,runtimeSupportsLazy:ownRuntime.indexOf("function _lmViewLoaded")>=0});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");const _hstLib=require("./hst.js");const{parseScriptJs,scriptPayload,stripAstPositions,annotateLayoutRegions,hst_markSvg,hst_orderIfFor,_hst}=_hstLib;exports.scriptPayload=scriptPayload;exports.stripAstPositions=stripAstPositions;exports.annotateLayoutRegions=annotateLayoutRegions;exports.hst_orderIfFor=hst_orderIfFor;function precompileViewScripts(groups){let failed=0;function visit(nodes,vars,inSection,file){if(!Array.isArray(nodes))return;for(const n of nodes){if(!n||n.type==="text")continue;const sectioned=inSection||n.type==="section"||n.type==="sections";const nm=String(n.name||"").toLowerCase();if((nm==="script"||nm==="js")&&Array.isArray(n.children)&&n.children[0]&&n.children[0].type==="text"){const t=n.children[0];if(t.content||t.jst){try{const ast=t.jst||_acorn.parse(t.content,{ecmaVersion:"latest",sourceType:"script"});const code=_walk.getWatcher(ast,{name:file},sectioned?void 0:(vars||[]).slice(),["__LMROOT__"]).code;new Function(code);t.pre=code;delete t.content;delete t.jst}catch(e){failed++;console.warn("\x1B[33mLumenJS: could not precompile a <script> in "+file+": "+(e&&e.message)+" (it will be compiled in the browser)\x1B[0m")}}}visit(n.children,vars,sectioned,file)}}for(const group of groups){const isTpl=group.kind==="tpls";for(const key in group.files){const entry=group.files[key];if(!entry||!Array.isArray(entry.hst))continue;const file=Buffer.from(key,"base64").toString().split(/[\\/]/).slice(-2).join("/");visit(entry.hst,entry.reactiveVars,isTpl,file)}}return failed}exports.precompileViewScripts=precompileViewScripts;const stripDevOnlyRuntime=require("./cdn-runtime.js").stripDevOnlyRuntime;exports.stripDevOnlyRuntime=stripDevOnlyRuntime;const _HST_EMPTY_OBJ={attrs:1,ax:1,evs:1,ex:1};function compactHstReplacer(key,value){if(_HST_EMPTY_OBJ[key]===1&&value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).length===0)return void 0;if(key==="isV"&&value===false)return void 0;if((key==="mss"||key==="children")&&Array.isArray(value)&&value.length===0)return void 0;return value}exports.compactHstReplacer=compactHstReplacer;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"));const _cdnRt=require(path.join(__dirname,"cdn-runtime.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{let deps={};const pkgPath=path.join(projectRoot,"package.json");if(fs.existsSync(pkgPath)){const pkg=JSON.parse(fs.readFileSync(pkgPath,"utf8"));Object.assign(deps,pkg.dependencies||{})}for(const key of detectUsedPlugins(projectRoot))if(!deps.hasOwnProperty(key))deps[key]="*";if(!Object.keys(deps).length)return[];return _pluginsBundle.selectedRegistryEntries(deps)}catch(e){return[]}}exports.selectedProjectPlugins=selectedProjectPlugins;const PLUGIN_SIGNATURES={"select2":[/\.select2\s*\(/,/<[a-z][^>]*\s(?:sl|slct)(?=[\s>=\/])/i],"flickity":[/\.flickity\s*\(/,/\bFlickity\b/,/<[a-z][^>]*\scrslf(?=[\s>=\/])/i],"bootstrap-colorpicker":[/\.colorpicker\s*\(/,/<input[^>]*\scolor(?=[\s>=\/])/i],"bootstrap-datetimepicker":[/\.datetimepicker\s*\(/,/<input[^>]*\s(?:date|time|datetime)(?=[\s>=\/])/i],"jquery-ui-dist":[/\.(?:sortable|draggable|droppable|resizable|datepicker|autocomplete|slider|accordion)\s*\(/,/<[a-z][^>]*\s(?:sort|drag|drop)(?=[\s>=\/])/i],"jquery.easing":[/\beas(?:e|ing)(?:In|Out)[A-Z]\w*/],"nestedSortable":[/\.nestedSortable\s*\(/],"jquery.numeric":[/\.numeric\s*\(/,/<input[^>]*\s(?:numeric|integer|decimal)(?=[\s>=\/])/i],"timeago":[/\.timeago\s*\(/,/\$\.timeago\b/],"slick-carousel":[/\.(?:crsl|slick)\s*\(/,/<[a-z][^>]*\scrsl(?=[\s>=\/])/i],"@iconify/iconify":[/class=["'][^"']*\biconify\b/,/\bIconify\./],"rellax":[/\bRellax\b/],"headroom.js":[/\bHeadroom\b/,/<[a-z][^>]*\spinnable(?=[\s>=\/])/i],"in-view":[/\binView\b/],"gsap":[/\bgsap\b/,/\bTween(?:Max|Lite)\b/,/\bTimeline(?:Max|Lite)\b/],"jquery.caret":[/\.caret\s*\(/],"jquery-tageditor":[/\.tagEditor\s*\(/,/<[a-z][^>]*\stags(?=[\s>=\/])/i],"jquery-lazy":[/\.lazy\s*\(/,/<img[^>]*\slazy(?=[\s>=\/])/i]};function detectUsedPlugins(projectRoot){const src=path.join(projectRoot,"src");if(!fs.existsSync(src))return[];let indexHtml="";try{indexHtml=fs.readFileSync(path.join(src,"index.html"),"utf8")}catch(e){}const texts=[];(function walk(dir){let entries;try{entries=fs.readdirSync(dir,{withFileTypes:true})}catch(e){return}for(const e of entries){const p=path.join(dir,e.name);if(e.isDirectory()){if(e.name==="node_modules"||e.name==="js"||e.name==="css"||e.name==="images")continue;walk(p)}else if(/\.(view|tpl|layout)$/.test(e.name)){try{texts.push(fs.readFileSync(p,"utf8"))}catch(x){}}}})(src);try{texts.push(fs.readFileSync(path.join(src,"index.js"),"utf8"))}catch(e){}for(const s of detectLocalProjectScripts(indexHtml)){try{texts.push(fs.readFileSync(path.join(src,s.replace(/^\//,"")),"utf8"))}catch(e){}}const all=texts.join("\n");const loadedByPage=key=>new RegExp(`<script[^>]+src=["'][^"']*`+key.replace(/^@[^/]+\//,"").replace(/\.js$/,"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i").test(indexHtml);const found=[];for(const key in PLUGIN_SIGNATURES){if(loadedByPage(key))continue;if(PLUGIN_SIGNATURES[key].some(re=>re.test(all)))found.push(key)}return found}exports.detectUsedPlugins=detectUsedPlugins;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 placePluginsCss(html,cssTag){html=String(html);let at=html.search(/<link\b[^>]*href=["']\/css\//i);return at>=0?html.slice(0,at)+cssTag+"\n "+html.slice(at):html.split("</head>").join(" "+cssTag+"\n</head>")}exports.placePluginsCss=placePluginsCss;function withGeneratorMeta(html,version){html=String(html);const v=String(version||"").trim();if(!v||/<meta\b[^>]*\bname\s*=\s*["']generator["']/i.test(html))return html;const tag='<meta name="generator" content="LumenJS '+v+'">';return/<\/head>/i.test(html)?html.replace(/<\/head>/i,function(){return tag+"\n</head>"}):tag+"\n"+html}exports.withGeneratorMeta=withGeneratorMeta;function detectLocalProjectScripts(indexHtmlSource){let found=[];let re=/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;let m;indexHtmlSource=String(indexHtmlSource).replace(/<!--[\s\S]*?-->/g,"");while(m=re.exec(indexHtmlSource)){let src=m[1];if(src.indexOf("/")!==0)continue;if(src==="/js/lm.js"||src==="/index.js")continue;if(/^\/js\/bea\.js(\?|$)/.test(src))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=3;exports.HST_FORMAT_VERSION=HST_FORMAT_VERSION;function checkProjectRuntime(projectPath){try{let lm=fs.readFileSync(path.join(projectPath,"src","js","lm.js"),"utf8");let m=/EXPECTED_HST_FORMAT_VERSION\s*=\s*(\d+)/.exec(lm);let accepts=/_HST_FORMATS_ACCEPTED\s*=\s*\[([\d,\s]+)\]/.exec(lm);let ok=accepts?accepts[1].split(",").map(Number).indexOf(HST_FORMAT_VERSION)>-1:m&&Number(m[1])===HST_FORMAT_VERSION;if(m&&!ok){console.warn("\n\x1B[33mLumenJS: src/js/lm.js is older than this CLI (it expects HST v"+m[1]+", this CLI emits v"+HST_FORMAT_VERSION+"). Run `lm update-core` to update the project's runtime.\x1B[0m\n");return false}}catch(e){}return true}exports.checkProjectRuntime=checkProjectRuntime;exports.getAllFiles=getAllFiles;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,hst=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,hst)}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(hst){var result=_hst(fs.readFileSync(filePath,{encoding:"utf8"}))}else{var result=fs.readFileSync(filePath,{encoding:"utf8"})}arrayOfFiles[fileKey]=result}});return arrayOfFiles}function v1CompatIndexHtml(html){return String(html).replace(/(<script\b[^>]*\bsrc=["'])\/?js\/bea\.js(?:\?[^"']*)?(["'])/gi,"$1/js/lm.js$2").replace(/<script\b[^>]*\bsrc=["']\/?index\.js(?:\?[^"']*)?["'][^>]*>\s*<\/script>\s*/gi,"").replace(/<script\b[^>]*\bsrc=["'](?:https?:)?\/\/(?:s\.|www\.)?beacdn\.com\/beajs\/[^"']*["'][^>]*>\s*<\/script>\s*/gi,"").replace(/<script\b[^>]*\bsrc=["'](?:https?:)?\/\/lmjs\.beacdn\.com\/[^"']*["'][^>]*>\s*<\/script>\s*/gi,"")}exports.v1CompatIndexHtml=v1CompatIndexHtml;function readTemplates(root){let out={};for(const folder of["tpls","comps"]){let dir=root+path.sep+"src"+path.sep+folder+path.sep;if(fs.existsSync(dir))Object.assign(out,getAllFiles(dir,{},false,true))}return out}exports.readTemplates=readTemplates;function linkTemplateReactiveVars(files2,templates){function templateFor(attrs){let name=String(attrs.tpl).replace(/^\/+/,"");for(const f of["tpls","comps"]){let key=Buffer.from("src/"+f+"/"+name+".tpl").toString("base64");if(templates[key])return templates[key]}return null}function scan(nodes,add){if(!Array.isArray(nodes))return;for(const node of nodes){if(!node)continue;let a=node.attrs;if(a&&node.type==="sections"&&a.hasOwnProperty("tpl")){let t=templateFor(a);if(t)(t.reactiveVars||[]).forEach(add)}if(a&&a.hasOwnProperty("view")){let sv=viewFor(a.view);if(sv)(sv.reactiveVars||[]).forEach(add)}if(node.children)scan(node.children,add);if(Array.isArray(node.content))scan(node.content,add)}}let viewByPath={};for(const key in files2){let p=Buffer.from(key,"base64").toString().replace(/\\/g,"/");let m=p.match(/(?:^|\/)views\/(.+)\.view$/);if(m)viewByPath[m[1]]=files2[key]}function viewFor(v){let p=String(v).trim().replace(/^\/+/,"").replace(/\.view$/,"");if(!p||/\{\{/.test(p))return null;return viewByPath[p]||null}for(let pass=0;pass<10;pass++){let grew=false;for(const key in files2){let entry=files2[key];if(!entry||!Array.isArray(entry.hst))continue;if(!Array.isArray(entry.reactiveVars))entry.reactiveVars=[];scan(entry.hst,function(n){if(entry.reactiveVars.indexOf(n)===-1){entry.reactiveVars.push(n);grew=true}})}if(!grew)break}for(const key in files2){let entry=files2[key];if(!entry||!Array.isArray(entry.hst))continue;if(!Array.isArray(entry.reactiveVars))entry.reactiveVars=[];scan(entry.hst,function(n){if(entry.reactiveVars.indexOf(n)===-1)entry.reactiveVars.push(n)})}return files2}exports.linkTemplateReactiveVars=linkTemplateReactiveVars;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}addAgentFiles(process.cwd());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;function addAgentFiles(projectPath){var tplDir=path.join(__dirname,"files","project");var added=[];["AGENTS.md","CLAUDE.md"].forEach(function(f){var dest=path.join(projectPath,f);if(!fs.existsSync(dest)&&fs.existsSync(path.join(tplDir,f))){fs.copyFileSync(path.join(tplDir,f),dest);added.push(f)}});if(added.length)console.log("Added "+added.join(" + ")+" (points AI coding agents at the LumenJS reference).");return added}exports.addAgentFiles=addAgentFiles;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);if(!c.length||String(c[0])[0]=="-"&&c.length<2){console.log("Usage: lm create <project name> (or lm create -v|-s|-t <name> for a view, sub-view or layout)");return}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=="cdn-files"){_cdnRt.writeCdnFiles(process.argv[3]||"cdn",stripDevOnlyRuntime)}else if(command=="login"){require(path.join(__dirname,"copilot","auth.js")).loginCommand(process.argv.slice(3))}else if(command=="logout"){require(path.join(__dirname,"copilot","auth.js")).logout()}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()}`;if(!checkProjectRuntime(projectPath)){spinner.fail("Build stopped: run `lm update-core` first, then build again.");process.exit(1)}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 _tpls=readTemplates(`${process.cwd()}`);linkTemplateReactiveVars(_views,_tpls);linkTemplateReactiveVars(_layouts,_tpls);var indexCode=fs.readFileSync(projectPath+path.sep+`src`+path.sep+"index.html","utf8");let _cssDir=projectPath+path.sep+`src`+path.sep+"css"+path.sep;let _mainCssName=["mobius.css","bea.css"].find(f=>fs.existsSync(_cssDir+f))||null;var beaCSSCode=_mainCssName?fs.readFileSync(_cssDir+_mainCssName,"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 _uncompiledScripts=precompileViewScripts([{kind:"views",files:_views},{kind:"layouts",files:_layouts},{kind:"tpls",files:_tpls}]);let _projectRuntime=projectPath+path.sep+"src"+path.sep+"js"+path.sep+"lm.js";let ownRuntime=fs.readFileSync(fs.existsSync(_projectRuntime)?_projectRuntime:path.join(__dirname,"files","libs","lm.js"),"utf8");let _runtimePlan=_cdnRt.planRuntime({cmds,config,ownRuntime,precompiled:_uncompiledScripts===0,stripDevOnlyRuntime});if(_runtimePlan&&_runtimePlan.skipped){spinner.info("Runtime kept inside app.js: "+_runtimePlan.skipped).start("Gathering Required Resources");_runtimePlan=null}let _split=_cdnRt.splitViews(_views,compactHstReplacer,{cmds,config,runtimeSupportsLazy:ownRuntime.indexOf("function _lmViewLoaded")>=0});let vt=`
|
|
2
2
|
var _vcData = {
|
|
3
3
|
"hstFormatVersion": `+HST_FORMAT_VERSION+`,
|
|
4
4
|
"views": `+JSON.stringify(_views,compactHstReplacer)+`,
|
|
@@ -8,4 +8,4 @@ var _vcData = {
|
|
|
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
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
|
-
<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)})}
|
|
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);let _lmVer="";try{_lmVer=String(_cdnRt.cliVersion()||"")}catch(e){_lmVer=""}_indexOut=withGeneratorMeta(_indexOut,_lmVer);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,40 +1,389 @@
|
|
|
1
1
|
# AGENTS.md — LumenJS project
|
|
2
2
|
|
|
3
|
-
This is a **LumenJS V2** project (`@lmjs/cli` + `@lmjs/core`). LumenJS is not Vue
|
|
4
|
-
|
|
3
|
+
This is a **LumenJS V2** project (`@lmjs/cli` + `@lmjs/core`), written against **2.8.6**. LumenJS is not Vue and
|
|
4
|
+
not React: no virtual DOM, no components, no props. A view is HTML with `{{ }}` expressions; every top-level
|
|
5
|
+
`var`/`let`/`const` in its `<script>` is reactive; navigating swaps the rendered view.
|
|
6
|
+
|
|
7
|
+
Read before changing any `.view`:
|
|
5
8
|
|
|
6
9
|
- Short guide: https://lumenjs.com/llms.txt
|
|
7
10
|
- Full reference: https://lumenjs.com/llms/lumenjs.txt
|
|
11
|
+
- This file is also published at https://lumenjs.com/AGENTS.md
|
|
12
|
+
|
|
13
|
+
## The four roots
|
|
14
|
+
|
|
15
|
+
Everything on the page belongs to exactly one of these, and they are siblings, not nested:
|
|
8
16
|
|
|
9
|
-
|
|
17
|
+
1. **Layout** — `src/layouts/<name>.layout`: the shell. Holds widget regions, the view's body, and slots.
|
|
18
|
+
Its own `<style>` block styles the shell.
|
|
19
|
+
2. **Widgets** — `src/views/widgets/<region>.view`: one persistent mount per region, kept (with its variables
|
|
20
|
+
and DOM) across navigation. Put anything that must not flicker there: nav, sidebar, chat list, cart.
|
|
21
|
+
3. **View** — the route's view (`src/views/<name>.view`) and any sub-views it mounts. A sub-view has its own
|
|
22
|
+
variables; it is rebuilt every time its host renders.
|
|
23
|
+
4. **Global** — `globals` (localStorage-backed), `cookies`, and whatever `src/index.js` sets up.
|
|
10
24
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
25
|
+
## Folder layout
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
src/index.html the page: <div app></div>
|
|
29
|
+
src/index.js start-up: Reactor({...}), helpers, auth
|
|
30
|
+
src/layouts/*.layout shells: public.layout, app.layout ...
|
|
31
|
+
src/views/*.view routes and sub-views
|
|
32
|
+
src/views/widgets/*.view persistent regions of a layout
|
|
33
|
+
src/tpls/*.tpl row templates (tpl="name" on a :for element)
|
|
34
|
+
src/css/, src/images/ assets
|
|
35
|
+
src/js/lm.js the runtime, copied in — never edit it
|
|
36
|
+
```
|
|
15
37
|
|
|
16
38
|
## Commands
|
|
17
39
|
|
|
18
|
-
- `lm serve`: dev server. `lm build`: production build into `dist
|
|
19
|
-
`dist/` using `config.json`'s `ftp
|
|
40
|
+
- `lm serve`: dev server. `lm build`: production build into `dist/` (it writes the release into a
|
|
41
|
+
`<meta name="generator">` tag). `lm build --deploy`: build, then upload `dist/` using `config.json`'s `ftp`.
|
|
20
42
|
- `lm create -v name` / `-s name` / `-t name`: new view / sub-view / layout.
|
|
43
|
+
- `lm update-core` after upgrading `@lmjs/cli`: refreshes `src/js/lm.js`.
|
|
21
44
|
- Pin a version without a global install: `npx -y -p @lmjs/cli@<version> lm <command>`.
|
|
45
|
+
- Never put API secrets in `config.json`. Use `lm login` + `lm api set <name>`.
|
|
22
46
|
|
|
23
|
-
## Rules that are easy to get wrong
|
|
24
47
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
48
|
+
## src/index.js — start-up
|
|
49
|
+
|
|
50
|
+
```js
|
|
51
|
+
Reactor({
|
|
52
|
+
App: '[app]', // the container in index.html
|
|
53
|
+
defaultView: 'new_chat', // what '/' renders
|
|
54
|
+
authView: 'public_chat', // shown in place of a requireAuth view when nobody is signed in
|
|
55
|
+
auth: function () { return AI.auth.user(); }, // asked on every render; falsy = signed out
|
|
56
|
+
init: function () { /* once, before the first render; `nodes` is ready here */ },
|
|
57
|
+
tick: function () { },
|
|
58
|
+
updateCheck: true // false = no built-in "new version, reload" bar
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Keys: `App`, `defaultView`, `authView`, `auth`, `init`, `tick`, `updateCheck`, `Base` (serve under a
|
|
63
|
+
sub-path), `subDirectory`.
|
|
64
|
+
|
|
65
|
+
## Routing: `nodes[]`
|
|
66
|
+
|
|
67
|
+
`nodes` is the URL path split on `/`. `/` gives `nodes[0] = defaultView`. **Only `nodes[0]` picks the view
|
|
68
|
+
file** — the rest of the path is yours to read:
|
|
69
|
+
|
|
70
|
+
- `/c/abc123` → `nodes = ['c', 'abc123']` → renders `src/views/c.view`, and the chat id is `nodes[1]`.
|
|
71
|
+
- `?q=1` → `View.params` (`{q: '1'}`) in the rendered view.
|
|
72
|
+
- `pushURL(path, data)` → the target view's `View.props` is `data`.
|
|
73
|
+
- `#fragment` only scrolls to an element; never route on it.
|
|
74
|
+
- Aliases are fine: rewrite `nodes[0]` in `init()` before the first render (`download` → `desktop`).
|
|
75
|
+
- Keep the state that identifies what you show (chat, product, order) **in the URL**, never in a global.
|
|
76
|
+
|
|
77
|
+
## Links and pushURL
|
|
78
|
+
|
|
79
|
+
```html
|
|
80
|
+
<a href="/c/{{ objectId }}" n1="{{ objectId }}">{{ title }}</a>
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
An in-app `href` is intercepted and pushed as a route. `target="_blank"` and `http(s)://` links leave the app.
|
|
84
|
+
From a script: `pushURL('/c/' + id)`, `pushURL('/c/' + id, {from: 'list'})`. A page change scrolls to the top
|
|
85
|
+
by itself (2.6.4+) — don't add your own; `st(selector)` scrolls inside a page.
|
|
86
|
+
|
|
87
|
+
## Views and sub-views
|
|
88
|
+
|
|
89
|
+
`src/views/x.view` is the route `/x`. Its first child may be a settings block:
|
|
90
|
+
|
|
91
|
+
```
|
|
92
|
+
<settings>
|
|
93
|
+
layout: app,
|
|
94
|
+
requireAuth: true
|
|
95
|
+
</settings>
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`layout` picks the layout file; `requireAuth` asks the auth gate (below); `hasNav`/`hasHeader`/`hasFooter`/
|
|
99
|
+
`has<Region>` override the layout's widget regions.
|
|
100
|
+
|
|
101
|
+
A sub-view is an element with `view="name"`: it renders `src/views/name.view` with **its own** variables, and
|
|
102
|
+
is rebuilt every time its host renders. Hand it data at creation with `@init`:
|
|
103
|
+
|
|
104
|
+
```html
|
|
105
|
+
<div view="chatbox" @init="chatData"></div>
|
|
106
|
+
<script>
|
|
107
|
+
function chatData() { return { chatId: nodes[1] }; }
|
|
108
|
+
</script>
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
The handler's plain-object return is merged into that instance's variables, synchronously (a Promise is not
|
|
112
|
+
awaited), and it is one-way: a sub-view cannot write its parent's variables. Reading a parent variable by
|
|
113
|
+
name needs no syntax at all.
|
|
114
|
+
|
|
115
|
+
## Layouts
|
|
116
|
+
|
|
117
|
+
- `<settings> layout: app </settings>` → `src/layouts/app.layout`. No line → `default`. A project with no
|
|
118
|
+
`src/layouts/` gets the V1 shell (nav/header/body/footer).
|
|
119
|
+
- The layout is re-rendered only when its name changes; widget regions are reattached, never re-rendered.
|
|
120
|
+
That is what makes layout switching the natural sign-in mechanism: public views ask for `public`,
|
|
121
|
+
signed-in views for `app`.
|
|
122
|
+
- `<main body></main>` receives the view. `<nav nav>`, `<aside sidebar>` are widget regions.
|
|
123
|
+
`<div slot="side"></div>` receives the view's `<slot name="side">`.
|
|
124
|
+
- Style the shell in the layout's own `<style>`, with logical CSS (`margin-inline`, `padding-inline`,
|
|
125
|
+
`text-align: start`) so `dir="rtl"` mirrors the whole thing.
|
|
126
|
+
|
|
127
|
+
## Widgets (persistent regions)
|
|
128
|
+
|
|
129
|
+
- A **bare attribute** on a layout element declares a region: `<nav nav>`, `<aside sidebar>`, `<footer footer>`.
|
|
130
|
+
The region `sidebar` is filled from `src/views/widgets/sidebar.view`.
|
|
131
|
+
- Per view: `hasSidebar: false` empties the region, `hasSidebar: "sidebar2"` uses
|
|
132
|
+
`src/views/widgets/sidebar2.view`, and leaving it out means `true`.
|
|
133
|
+
- A widget is mounted **once per region** and keeps its variables and DOM across navigation; after a layout
|
|
134
|
+
swap its existing nodes are reattached, not re-rendered. Anything that must not flicker (nav, chat list,
|
|
135
|
+
cart, filters) belongs in a widget.
|
|
136
|
+
- Widgets and the view are siblings: a widget never sees a view's variables. Share through `globals`, the
|
|
137
|
+
URL (`nodes`), or a small API call the widget makes itself.
|
|
138
|
+
|
|
139
|
+
## Slots
|
|
140
|
+
|
|
141
|
+
`<slot name="side">…</slot>` inside a view is injected into the layout's `[slot="side"]` element, after its
|
|
142
|
+
default content — the way one view adds a right pane or a toolbar to the shell without changing the layout.
|
|
143
|
+
|
|
144
|
+
## Templates
|
|
145
|
+
|
|
146
|
+
`tpl="name"` works **only on a `:for` element** and renders `src/tpls/name.tpl` per row (V1 projects may keep
|
|
147
|
+
templates in `src/comps/`). `comp=` no longer exists.
|
|
148
|
+
|
|
149
|
+
## State
|
|
150
|
+
|
|
151
|
+
- Top-level `var`/`let`/`const` in a view, sub-view or layout `<script>` is reactive. There is no `bind=`.
|
|
152
|
+
- `{{ }}` re-renders when a variable **named in it** changes: `{{ items.length }}` updates, `{{ total() }}`
|
|
153
|
+
goes stale if `total()` reads `items` internally.
|
|
154
|
+
- `watch = { myVar: function () { … } }` runs a callback per variable.
|
|
155
|
+
- `globals` is the persisted, localStorage-backed store; `cookies` for small values. A nested mutation
|
|
156
|
+
(`globals.x.y = 1`) needs `touch('x')` to fire a re-render; reassigning the variable does it too.
|
|
157
|
+
- `{{ }}` output is rendered as HTML, not text: escape anything that came from a user.
|
|
158
|
+
- Directives: `:if` / `:else-if` / `:else`, `:for="list as item"` (with `:for-limit`, `:for-offset`, `:for-if`).
|
|
159
|
+
Attribute order is priority: `<i :if="a" :for="xs as x">` gates the loop, `<i :for="xs as x" :if="x.on">`
|
|
30
160
|
filters rows.
|
|
31
|
-
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
161
|
+
- Changing the loop variable (`@click="t.done = !t.done"`) writes back into the list when the list is a
|
|
162
|
+
variable (2.5.5+). Looping over a computed list (`todos.filter(...)`) gives copies.
|
|
163
|
+
|
|
164
|
+
## Events — every one is built in
|
|
165
|
+
|
|
166
|
+
`@event="fn"` calls `fn(ev, el)`; `el` is the wrapped element (`el.hasClass(...)`, `el.addClass(...)`,
|
|
167
|
+
`el[0]` for the DOM node). **This is the whole list** — a name that is not here does not fire. Every one comes with an
|
|
168
|
+
example, below the table (the full reference is https://lumenjs.com/llms.txt §6.3).
|
|
169
|
+
|
|
170
|
+
| Attribute | Fires |
|
|
171
|
+
|---|---|
|
|
172
|
+
| `@click` | click **or** tap (a tap runs it once, never twice) |
|
|
173
|
+
| `@tap` | a real tap (touch only) |
|
|
174
|
+
| `@dblclick` / `@dbltap` | double click / double tap |
|
|
175
|
+
| `@singleclick` / `@singletap` | a click that was not a double |
|
|
176
|
+
| `@taphold` / `@clickhold` | a held press |
|
|
177
|
+
| `@click2` / `@tap2`, `@click2hold` / `@tap2hold` | two-finger tap, two fingers held |
|
|
178
|
+
| `@tap-start`, `@tap-move`, `@tap-end` | finger down, moving, lifted |
|
|
179
|
+
| `@swipe`, `@swipe-up`, `@swipe-down`, `@swipe-left`, `@swipe-right`, `@swipe-end` | the gesture, on the element that receives it |
|
|
180
|
+
| `@mouse-over` `@mouse-out` `@mouse-enter` `@mouse-leave` `@mouse-move` `@mouse-down` `@mouse-up` | mouse, hyphenated (`@mouse-over`, never `@mouseover`); down/up answer touch too |
|
|
181
|
+
| `@scroll` | every scroll event, the page's included |
|
|
182
|
+
| `@scroll-start` / `@scroll-end` | the first / last scroll of a burst (150 ms of quiet between them) |
|
|
183
|
+
| `@scroll-top` `@scroll-bottom` `@scroll-left` `@scroll-right` | that edge was reached (checked at `@scroll-end`) |
|
|
184
|
+
| `@input` `@change` `@focus` `@blur` `@keyup` `@keydown` | form and keys; a form submits through `o-sub`, there is no `@submit` |
|
|
185
|
+
| `@click-toggled` | after a `tgl` / `t` / `actv` / `actvt` element, or the `.navTgl` drawer button, applied its class change |
|
|
186
|
+
| `@modal-open` `@modal-close` `@modal-beforeclose` | modals; `return false` in beforeclose keeps it open |
|
|
187
|
+
| `@browse-files` `@files-added` `@queue-changed` `@file-removed` `@upload-start` `@file-uploaded` `@upload-progress` `@upload-complete` `@upload-stop` `@queue-empty` | the `up` uploader |
|
|
188
|
+
| `@drag` `@drag-start` `@drag-stop` `@drop` `@sort` `@sort-start` `@sort-update` `@sort-change` `@sort-stop` `@sort-before-stop` | drag/sort, with `ui` as the third argument and the bare `drag`/`sort` attribute on the element |
|
|
189
|
+
| `@sl-select` / `@sl-unselect` | Select2, called `(ev, el, data)` |
|
|
190
|
+
| `@init` | a sub-view's entry point; returns its starting data |
|
|
191
|
+
| `@before-render` / `@after-render` | around a `:if` / `:for` / `:else` render, and `@after-render` on mount |
|
|
192
|
+
| `@orientationchange` | the phone was rotated |
|
|
193
|
+
| `@before-<event>` | a guard that runs first; `return false` cancels the real handler |
|
|
194
|
+
|
|
195
|
+
Modifiers chain onto the attribute: `@click.stop` (preventDefault first), `@click.up` (let it bubble),
|
|
196
|
+
`@click.confirm` / `@click.econfirm="Delete this?"`, `@click.acl="mayRun"`, `@click.rcl="afterwards"`.
|
|
197
|
+
A bare `stop` attribute stops propagation for every handler on the element.
|
|
198
|
+
|
|
199
|
+
Every one, with an example:
|
|
200
|
+
|
|
201
|
+
```html
|
|
202
|
+
<!-- click and tap: @click answers the finger too, so a tap never runs twice -->
|
|
203
|
+
<button @click="save">Save</button>
|
|
204
|
+
<a @tap="open(nodes[1])">Open</a>
|
|
205
|
+
<img @dblclick="zoom" @dbltap="zoom" src="/card.png">
|
|
206
|
+
<li @singleclick="pick(ev, el)" @singletap="pick(ev, el)">one, not two</li>
|
|
207
|
+
<div @taphold="confirmDelete(ev, el)" @clickhold="confirmDelete(ev, el)">hold to delete</div>
|
|
208
|
+
<div @click2="zoom(ev)" @tap2="zoom(ev)">two fingers</div>
|
|
209
|
+
<div @click2hold="menu(ev)" @tap2hold="menu(ev)">two fingers, held</div>
|
|
210
|
+
<div @tap-start="track(ev)" @tap-move="track(ev)" @tap-end="drop(ev)">draw</div>
|
|
211
|
+
|
|
212
|
+
<!-- swipe: on the element that receives the gesture -->
|
|
213
|
+
<aside sidebar @swipe-left="closeDrawer" @swipe-right="openDrawer" @swipe-end="settle(ev)">…</aside>
|
|
214
|
+
<div class="card" @swipe="onSwipe(ev)" @swipe-up="next()" @swipe-down="prev()">…</div>
|
|
215
|
+
|
|
216
|
+
<!-- mouse: hyphenated, never @mouseover; down and up answer touch as well -->
|
|
217
|
+
<div class="card" @mouse-enter="el.addClass('lit')" @mouse-leave="el.removeClass('lit')">…</div>
|
|
218
|
+
<td @mouse-over="hint(row)" @mouse-out="hint(null)" @mouse-move="follow(ev)">…</td>
|
|
219
|
+
<div @mouse-down="grab(ev)" @mouse-up="release(ev)">…</div>
|
|
220
|
+
|
|
221
|
+
<!-- scroll: el is what scrolled; the page's own scroll arrives with el = <html> -->
|
|
222
|
+
<div class="chat" @scroll-start="pinned = false" @scroll-bottom="pinned = true">…</div>
|
|
223
|
+
<div class="list" @scroll="el.hasClass('moved') || el.addClass('moved')">…</div>
|
|
224
|
+
<div class="feed" @scroll-end="save()" @scroll-top="refresh()">…</div>
|
|
225
|
+
<div class="strip" @scroll-left="prev()" @scroll-right="next()">…</div>
|
|
226
|
+
|
|
227
|
+
<!-- forms and keys: there is no @submit, a form submits through o-sub -->
|
|
228
|
+
<input @input="search(ev.target.value)" @change="commit(ev.target.value)"
|
|
229
|
+
@focus="el.addClass('on')" @blur="el.removeClass('on')"
|
|
230
|
+
@keyup="onEsc(ev)" @keydown="onTab(ev)">
|
|
231
|
+
|
|
232
|
+
<!-- toggle: the class is already applied when the handler runs -->
|
|
233
|
+
<button class="navTgl" @click-toggled="if (el.hasClass('on')) loadPane()">Menu</button>
|
|
234
|
+
|
|
235
|
+
<!-- modal: a beforeclose handler that returns false keeps it open -->
|
|
236
|
+
<button modal="sheet" @modal-open="loadSheet()">Details</button>
|
|
237
|
+
<button close-modal @modal-close="cleanup()">×</button>
|
|
238
|
+
<button close-modal @modal-beforeclose="keepOpenIfDirty">Close</button>
|
|
239
|
+
|
|
240
|
+
<!-- uploader, the up element: the file list is the third argument -->
|
|
241
|
+
<div up @browse-files="browse(ev, el, files)" @files-added="added(ev, el, files)"
|
|
242
|
+
@queue-changed="sync(ev, el, files)" @file-removed="removed(ev, el, files)">
|
|
243
|
+
<div drpzn @drop="dropped(ev, el, files)">Drop files</div>
|
|
244
|
+
</div>
|
|
245
|
+
<div up @upload-start="busy(true)" @upload-progress="progress(ev, el, files)"
|
|
246
|
+
@file-uploaded="done(ev, el, files)" @upload-complete="busy(false)"
|
|
247
|
+
@upload-stop="busy(false)" @queue-empty="idle()">…</div>
|
|
248
|
+
|
|
249
|
+
<!-- drag and sort: ui is the third argument, the bare attribute marks the element -->
|
|
250
|
+
<div drag @drag-start="grab(ev, el, ui)" @drag="move(ev, el, ui)" @drag-stop="rest(ev, el, ui)">…</div>
|
|
251
|
+
<div sort @sort-start="lock()" @sort-update="preview(ev, el, ui)" @sort-change="saveOrder(ev, el, ui)"
|
|
252
|
+
@sort-stop="unlock()" @sort-before-stop="keepOrder">…</div>
|
|
253
|
+
|
|
254
|
+
<!-- Select2 -->
|
|
255
|
+
<select sl multiple @sl-select="tagged(ev, el, data)" @sl-unselect="untagged(ev, el, data)">…</select>
|
|
256
|
+
|
|
257
|
+
<!-- lifecycle: @init hands a sub-view its starting data, as a returned object -->
|
|
258
|
+
<div view="chatbox" @init="chatData"></div>
|
|
259
|
+
<div :if="open" @before-render="measure" @after-render="focusFirst">…</div>
|
|
260
|
+
<div :for="rows as row" @after-render="wireChart">…</div>
|
|
261
|
+
|
|
262
|
+
<!-- device -->
|
|
263
|
+
<flx @orientationchange="relayout()">…</flx>
|
|
264
|
+
|
|
265
|
+
<!-- guard: runs first, return false cancels the real handler -->
|
|
266
|
+
<button @before-click="isDirty" @click="go">Continue</button>
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
## Server data
|
|
270
|
+
|
|
271
|
+
- `API.get(url)`, `API.post(url, data)`, `API.put`, `API.patch`, `API.delete` — all promises.
|
|
272
|
+
- `LIVE` is the runtime's live socket (advanced); `cl()` is `console.log`.
|
|
273
|
+
|
|
274
|
+
## Auth — the built-in gate, no `/signin` route
|
|
275
|
+
|
|
276
|
+
- `Reactor({ auth: fn, authView: 'name' })`; `auth()` is asked on every render and returns the signed-in
|
|
277
|
+
person or something falsy.
|
|
278
|
+
- A view whose settings say `requireAuth` and a falsy answer is **not rendered**: the runtime renders
|
|
279
|
+
`authView` in its place, **with the URL unchanged**, and passes `View.props = {redirect: nodes[0], data}`.
|
|
280
|
+
- `authView` must not itself require auth — it is the public page (sign-in card, marketing content).
|
|
281
|
+
- After a successful sign-in, navigate again to the path that is already in the address bar, so the whole
|
|
282
|
+
route survives:
|
|
283
|
+
|
|
284
|
+
```js
|
|
285
|
+
pushURL(location.pathname.replace(/^\/+/, '')); // '/c/abc' → c.view with nodes[1] = 'abc'
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Never `pushURL(View.props.redirect)`: that is only `nodes[0]` and drops the id.
|
|
289
|
+
|
|
290
|
+
## Active nav: `n0` – `n9`
|
|
291
|
+
|
|
292
|
+
Put `nK="value"` on any element. After **every** render the runtime compares `nodes[K]` with the attribute
|
|
293
|
+
and adds the class `active` on a match, removes it otherwise:
|
|
294
|
+
|
|
295
|
+
```html
|
|
296
|
+
<nav>
|
|
297
|
+
<a href="/services" n0="services">Services</a>
|
|
298
|
+
<a href="/account" n0="account">Account</a>
|
|
299
|
+
</nav>
|
|
300
|
+
<aside>
|
|
301
|
+
<a href="/c/{{ objectId }}" n1="{{ objectId }}">{{ title }}</a>
|
|
302
|
+
</aside>
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
- Several values are allowed: `n1="abc,def"`.
|
|
306
|
+
- It runs over the whole document on every navigation, so layout and widget links stay correct without code.
|
|
307
|
+
- It only sets the class `active` — style `.active` yourself.
|
|
308
|
+
|
|
309
|
+
## Events and directives
|
|
310
|
+
|
|
311
|
+
`@event="handler"` binds a DOM event to a function defined in the file's `<script>`; `@init` is the sub-view
|
|
312
|
+
data hook (above), and `@before-render` / `@after-render` run around a render.
|
|
313
|
+
|
|
314
|
+
| Attribute | What it does |
|
|
315
|
+
|---|---|
|
|
316
|
+
| `t="css"` / `tcn="cls"` | click toggles class `active` (or `cls`) on the matching element(s) |
|
|
317
|
+
| `tgl="cls"` | click toggles `cls` (plus `toggled`) on the element itself |
|
|
318
|
+
| `actv="css"` | click: remove `active` from `css`, add it here — use for tab bars |
|
|
319
|
+
| `actvt="css"` | same, but this element toggles |
|
|
320
|
+
| `acl="css"` / `aclcn="cls"` | click adds a class (default `active`) |
|
|
321
|
+
| `rcl="css"` / `rclcn="cls"` | click removes it; with both, attribute order decides the winner |
|
|
322
|
+
| `h="css"` / `s="css"` | hide / show matching elements (order matters) |
|
|
323
|
+
| `stop` | stop the event from bubbling |
|
|
324
|
+
| `confirm="text"` / `econfirm="js"` | ask before acting / run JS before acting |
|
|
325
|
+
| `ctc="css"` | copy that element's text to the clipboard |
|
|
326
|
+
| `st="css"` | scroll to the element (smooth) |
|
|
327
|
+
| `:hover="css"` | inline style while hovered or touched |
|
|
328
|
+
| `alert="text"` (`alert-type`, `alert-icon`) | show a notice |
|
|
329
|
+
| `modal="id"` (`modal-title`, `modal-description`, `modal-icon`, `modal-align`, `modal-spacing`, `modal-ov`, `modal-class`) | open a modal; hooks `@modal-open`, `@modal-close`, `@modal-beforeclose` |
|
|
330
|
+
| `ci="css"` | collect the named fields of the closest form |
|
|
331
|
+
|
|
332
|
+
## Loaders and the update notice
|
|
333
|
+
|
|
334
|
+
`_loader.show()` / `_loader.hide()` for the full-screen wait state, `wait()` / `resume()` around long work,
|
|
335
|
+
`lmCheckForUpdate()` forces the built-in check. With `updateCheck` on, the runtime notices a new build and
|
|
336
|
+
offers a reload by itself — don't build your own.
|
|
337
|
+
|
|
338
|
+
## Built-in features (from `@lmjs/core` 2.8.6)
|
|
339
|
+
|
|
340
|
+
App lifecycle: `Reactor` (App, defaultView, authView, auth, init, tick, updateCheck, Base, subDirectory),
|
|
341
|
+
`globals`, `cookies`, `touch()`, `watch`.
|
|
342
|
+
|
|
343
|
+
Routing and navigation: `nodes[]`, `View.params`, `View.props`, `pushURL()`, in-app `<a href>`, automatic
|
|
344
|
+
scroll-to-top on a page change, `st()`, `#fragment` scrolling, `defaultView`, `init()` aliases.
|
|
345
|
+
|
|
346
|
+
Structure: layouts (`src/layouts`), views (`src/views`), sub-views (`view=`), widget regions
|
|
347
|
+
(`src/views/widgets`, `has<Region>`), slots, templates (`src/tpls`, `tpl=` on `:for`), the V1 fallback shell.
|
|
348
|
+
|
|
349
|
+
Rendering: `{{ }}` expressions, reactive top-level variables, `:if` / `:else-if` / `:else`, `:for` with
|
|
350
|
+
`as`, `:for-limit`, `:for-offset`, `:for-if`, HTML output from values, attribute-order priority.
|
|
351
|
+
|
|
352
|
+
Interaction: `@events`, `t` / `tcn`, `tgl`, `actv` / `actvt`, `acl` / `rcl` (+`cn`), `h` / `s`, `stop`,
|
|
353
|
+
`confirm` / `econfirm`, `ctc`, `st`, `:hover`, `alert*`, modals with their hooks, `ci`.
|
|
354
|
+
|
|
355
|
+
Data and platform: `API.get/post/put/patch/delete`, `LIVE`, `cl()`, `_loader.show/hide`, `wait()` / `resume()`,
|
|
356
|
+
`lmCheckForUpdate()`, `updateCheck`, the built-in update bar, `<meta name="generator">` with the release.
|
|
357
|
+
|
|
358
|
+
Auth: `requireAuth`, `authView`, `auth()`, `View.props.redirect`, no page reload.
|
|
359
|
+
|
|
360
|
+
## Gone in V2 — never use
|
|
361
|
+
|
|
362
|
+
- `bind=` — top-level variables are reactive by themselves.
|
|
363
|
+
- `comp=` — removed in 2.4.1; use `tpl=` (row templates) or `view=` (sub-views).
|
|
364
|
+
- `:data="name"` — sub-view data goes in through `@init` returning an object.
|
|
365
|
+
- `session` — does not exist; use `sessionStorage`.
|
|
366
|
+
- `data-into` — dead code, it does nothing.
|
|
367
|
+
|
|
368
|
+
## Rules that are easy to get wrong
|
|
369
|
+
|
|
370
|
+
- `nodes[0]` picks the view file and nothing else does: `/c/abc` is `c.view` with `nodes[1]`; there is no
|
|
371
|
+
nested route table.
|
|
372
|
+
- A widget keeps its state across navigation — never put "which chat is open" in a widget variable; read
|
|
373
|
+
`nodes[1]`.
|
|
374
|
+
- A sub-view is rebuilt on every host render and has its own variables: read `nodes` inside it instead of
|
|
375
|
+
passing the id down where you can.
|
|
376
|
+
- After sign-in, re-navigate to `location.pathname`, not to `View.props.redirect`.
|
|
377
|
+
- `{{ }}` output is HTML; escape user text.
|
|
378
|
+
- A `{{ }}` only listens to the variables named inside it.
|
|
379
|
+
- `tpl=` only on a `:for` element.
|
|
380
|
+
- Use `?query` for state that must survive a reload; `#fragments` only scroll.
|
|
381
|
+
- One `active` class is shared by `n0`-`n9` and the `t`/`actv`/`acl` directives — use `active` in your CSS.
|
|
382
|
+
- Never put API secrets in `config.json`; `lm login` + `lm api set <name>`.
|
|
383
|
+
|
|
384
|
+
---
|
|
385
|
+
|
|
386
|
+
Published for outside agents: this file ships into every project `lm create` makes (`lm update-core` adds it
|
|
387
|
+
to an existing one). Online, condensed: https://lumenjs.com/llms.txt. Online, long form with the source
|
|
388
|
+
references: https://lumenjs.com/llms/lumenjs.txt, **§14 "App shells"**.
|
|
389
|
+
Written against `@lmjs/core` 2.8.6 — check `lm --version` before relying on a version-specific detail.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lmjs/cli",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.9.0",
|
|
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.
|
|
55
|
+
"@lmjs/core": "2.9.0"
|
|
56
56
|
},
|
|
57
57
|
"engines": {
|
|
58
58
|
"node": ">=18.0.0"
|