@lmjs/cli 2.2.0 → 2.2.2

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 CHANGED
@@ -1,3 +1,3 @@
1
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");const bodyParser=require("body-parser");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 _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)}})();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);async function sendIndexHtml(res){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
2
  <script src="/js/lumenjs-plugins.js" type="text/javascript"><\/script>`}if(_pluginsCss&&_pluginsCss.trim()!=""&&html.indexOf("/css/lumenjs-plugins.css")==-1){tags+=`
3
- <link href="/css/lumenjs-plugins.css" rel="stylesheet" type="text/css" />`}if(tags)html=html.split("</head>").join(tags+"\n</head>");res.type("text/html").send(html)}app.use("/",async function(req,res,next){if(req.path==="/"||req.path==="/index.html"){sendIndexHtml(res);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(bodyParser.urlencoded({extended:true}));app.use(bodyParser.json());app.use(bodyParser.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=="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);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);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}/`);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);
3
+ <link href="/css/lumenjs-plugins.css" rel="stylesheet" type="text/css" />`}if(tags)html=html.split("</head>").join(tags+"\n</head>");res.type("text/html").send(html)}app.use("/",async function(req,res,next){if(req.path==="/"||req.path==="/index.html"){sendIndexHtml(res);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(bodyParser.urlencoded({extended:true}));app.use(bodyParser.json());app.use(bodyParser.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);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);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}/`);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);