dragifyjs-core-cli
Version:
dragifyJS CLI tool for the plugin development
2 lines • 11 kB
JavaScript
#!/usr/bin/env node
(()=>{"use strict";var e={n:t=>{var n=t&&t.__esModule?()=>t.default:()=>t;return e.d(n,{a:n}),n},d:(t,n)=>{for(var s in n)e.o(n,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:n[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};const t=require("yargs");var n=e.n(t);const s=require("fs");var o=e.n(s);const i=require("path");var r=e.n(i);const a=require("chalk");var c=e.n(a);const l=require("fs/promises");var p=e.n(l);const d=e=>void 0===e,u=(e,{color:t="green",lineDown:n=1}={})=>{console.log(""),console.log(c()[t].bold(e)),n&&console.log("")},y=e=>{u(e,{color:"red"})},m=(...e)=>console.log.apply(void 0,e),b=e=>{const t=r().dirname(e);return!!o().existsSync(t)||(o().mkdirSync(t),b(t))},g=(e,t)=>{let n=e[t]||{};if("string"==typeof n)try{n=JSON.parse(n)}catch(e){y(`Error while parsing "${t}" option`),y(e),n={}}return n},f=e=>({...e,babel:g(e,"babel"),htmlWebpack:g(e,"htmlWebpack")}),h=(e,t)=>{const n=o().existsSync(e);n&&o().statSync(e).isDirectory()?(o().mkdirSync(t),o().readdirSync(e).forEach((n=>{h(r().join(e,n),r().join(t,n))}))):n&&o().copyFileSync(e,t)},v=e=>r().resolve(process.cwd(),e),w=()=>require,S=e=>w().resolve(e),k=(e={})=>({presets:[[S("@babel/preset-env"),{targets:e.targets}]],plugins:[S("@babel/plugin-transform-runtime")]}),j=require("webpack");var x=e.n(j);const F=require("webpack-dev-server");var $=e.n(F);const _=require("html-webpack-plugin");var q=e.n(_);const O=require("terser-webpack-plugin");var E=e.n(O);const P=process.cwd();let C=[];const N=(e={})=>{const t=r().join(P,"package.json"),n=o().readFileSync(t),s=JSON.parse(n),{args:i,cmdOpts:a={}}=e,{htmlWebpack:l={}}=i,p=s.name,d=e.production,u=`/*! ${p} - ${s.version} */`;if(!d){const e="index.html",t=`${P}/${e}`,n=`${P}/_${e}`;let s=r().resolve(__dirname,`./../${e}`);o().existsSync(n)?s=n:o().existsSync(t)&&(s=t),C.push(new(q())({inject:"head",template:s,...l,templateParameters:{name:p,title:p,dragifyVersion:"latest",pathdragify:"",pathdragifyCss:"",...l.templateParameters||{}}}))}const y=r().resolve(P,i.output),b=["node_modules",r().join(__dirname,"../node_modules")];let g={entry:r().resolve(P,i.entry),mode:d?"production":"development",devtool:d?"source-map":"eval",optimization:{minimizer:[new(E())({extractComments:!1,terserOptions:{compress:{evaluate:!1},output:{comments:!1,quote_style:3,preamble:u}}})]},output:{path:y,filename:"index.js",library:p,libraryTarget:"umd",globalObject:"typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this)"},module:{rules:[{test:/\.tsx?$/,loader:S("ts-loader"),exclude:/node_modules/,options:{context:v(""),configFile:v("tsconfig.json")}},{test:/\.js$/,loader:S("babel-loader"),include:/src/,options:{...k(i),cacheDirectory:!0,...i.babel}}]},resolve:{extensions:[".tsx",".ts",".js"],modules:b},plugins:C};const f=v("webpack.config.js");let h;if(o().existsSync(f)){const e=w()(f);h=e.default||e}if("function"==typeof h){const e=h({config:g,webpack:x(),pkg:s});g=null===(j=e)||Array.isArray(j)||"object"!=typeof j?g:e}var j;return a.verbose&&m(c().yellow("Webpack config:\n"),g,"\n"),g},B=require("dts-bundle-generator"),D=require("child_process"),I=require("rimraf");var A=e.n(I);const R=require("@babel/core"),T=async(e={})=>{const t=v("src/index.ts");if(!o().existsSync(t))return;u("Start building TS declaration file...",{lineDown:0});const n={filePath:t,output:{noBanner:!0}},s={preferredConfigPath:v("tsconfig.json")},i=(0,B.generateDtsBundle)([n],s)[0];await(async(e,t)=>{try{const n=r().dirname(e);await(async e=>{try{return await p().access(e),!0}catch{return!1}})(n)||await p().mkdir(n,{recursive:!0}),await p().writeFile(e,t,"utf8")}catch(e){throw new Error(e)}})(v("dist/index.d.ts"),i),u("TS declaration file building completed successfully!")},W=require("inquirer");var J=e.n(W);const L=require("listr");var M=e.n(L);const H=require("spdx-license-list/full");var U=e.n(H);const z=require("lodash.template");var G=e.n(z);const Y="1.0.0",V="./template",K=process.cwd(),Q=e=>{const t=r().resolve(__dirname,`${V}/${e}`);return o().readFileSync(t,"utf8")},X=e=>r().resolve(K,e),Z=e=>r().resolve(__dirname,`${V}/${e}`),ee=e=>!(!e||"false"===e);n().usage(c().green.bold(o().readFileSync(r().resolve(__dirname,"./banner.txt"),"utf8")+`\nv${Y}`));const te=e=>{e.positional("config",{describe:"webpack configuration options",type:"string",default:"{}"}).positional("babel",{describe:"Babel configuration object",type:"string",default:"{}"}).positional("targets",{describe:"Browser targets in browserslist query",type:"string",default:"> 0.25%, not dead"}).positional("entry",{describe:"Library entry point",type:"string",default:"src/index"}).positional("output",{describe:"Build destination directory",type:"string",default:"dist"})},ne=e=>e.command(["serve [port]","server"],"Start the server",(e=>{e.positional("devServer",{describe:"webpack-dev-server options",type:"string",default:"{}"}).positional("host",{alias:"h",describe:"Host to bind on",type:"string",default:"localhost"}).positional("port",{alias:"p",describe:"Port to bind on",type:"number",default:8080}).positional("htmlWebpack",{describe:"html-webpack-plugin options",type:"string",default:"{}"}),te(e)}),(e=>((e={})=>{u("Start the development server...");const{host:t,port:n}=e,s=e.verbose,o={...N({args:f(e),cmdOpts:e}),...g(e,"webpack")},i={...o.devServer,open:!0,...g(e,"devServer")};"localhost"!==t&&(i.host=t),8080!==n&&(i.port=n),s&&(m(c().yellow("Server config:\n"),e,"\n"),m(c().yellow("DevServer config:\n"),i,"\n"));const r=x()(o);new($())(i,r).start()})(e))).command("build","Build the source",(e=>{e.positional("stats",{describe:"Options for webpack Stats instance",type:"string",default:"{}"}).positional("statsOutput",{describe:'Specify the path where to output webpack stats file (eg. "stats.json")',type:"string",default:""}).positional("patch",{describe:"Increase automatically the patch version",type:"boolean",default:!0}).positional("localePath",{describe:"Path to the directory containing locale files",type:"string",default:"src/locale"}).positional("dts",{describe:'Generate typescript dts file ("include", "skip", "only")',type:"string",default:"include"}),te(e)}),(e=>((e={})=>{u("Start building the library...");const t=e.verbose,{dts:n}=e;t&&m(c().yellow("Build config:\n"),e,"\n");const s=()=>{const s={...N({production:1,args:f(e),cmdOpts:e}),...g(e,"config")};if("only"===n)return T(e);x()(s,(async(s,i)=>{const r=s||!!i&&i.hasErrors(),a={hash:!1,colors:!0,builtAt:!1,entrypoints:!1,modules:!1,...g(e,"stats")};if(i){e.statsOutput&&o().writeFileSync(v(e.statsOutput),JSON.stringify(i.toJson())),t&&m(c().yellow("Stats config:\n"),a,"\n");const n=i.toString(a);m(n,"\n")}await(async(e={})=>{const{localePath:t}=e;if(!o().existsSync(v(t)))return;u("Start building locale files...",{lineDown:0}),await A()("locale");const n=v("locale");h(v(t),n);let s="";o().readdirSync(n).forEach((e=>{const t=e.split(".")[0];s+=`export { default as ${t} } from './${t}'\n`})),o().writeFileSync(`${n}/index.js`,s);const i={...k(f(e))};o().readdirSync(n).forEach((e=>{const t=`${n}/${e}`,s=(0,R.transformFileSync)(t,i).code;o().writeFileSync(t,s)})),u("Locale files building completed successfully!")})(e),"skip"!==n&&await T(e),r?(y("Error during building"),console.error(s)):u("Building completed successfully!")}))};e.patch?(t&&m(c().yellow("Patch the version"),"\n"),(0,D.exec)("npm version --no-git-tag-version patch",s)):s()})(e))).command("init","Init dragifyJS plugin project",(e=>{e.positional("yes",{alias:"y",describe:"All default answers",type:"boolean",default:!1}).positional("name",{describe:"Name of the project",type:"string"}).positional("rName",{describe:"Repository name",type:"string"}).positional("user",{describe:"Repository username",type:"string"}).positional("components",{describe:"Indicate to include custom component types API",type:"boolean"}).positional("blocks",{describe:"Indicate to include blocks API",type:"boolean"}).positional("i18n",{describe:"Indicate to include the support for i18n",type:"boolean"}).positional("license",{describe:"License of the project",type:"string"})}),(e=>(async(e={})=>{const t=r().basename(process.cwd()),n=[],{verbose:s,name:i,rName:a,user:c,yes:l,components:p,blocks:y,i18n:g,license:f}=e;let h={name:i||(v=t,v.replace(/\_/g,"-").split("-").filter((e=>e)).map((e=>e[0].toUpperCase()+e.slice(1))).join(" ")),rName:a||t,user:c||"YOUR-USERNAME",components:!!d(p)||p,blocks:!!d(y)||y,i18n:!!d(g)||g,license:f||"MIT"};var v;u(`Init the project${s?" (verbose)":""}...`),l||(!i&&n.push({name:"name",message:"Name of the project",default:h.name}),!a&&n.push({name:"rName",message:"Repository name (used also as the plugin name)",default:h.rName}),!c&&n.push({name:"user",message:"Repository username (eg. on GitHub/Bitbucket)",default:h.user}),d(p)&&n.push({type:"boolean",name:"components",message:"Will you need to add custom Component Types?",default:h.components}),d(y)&&n.push({type:"boolean",name:"blocks",message:"Will you need to add Blocks?",default:h.blocks}),d(g)&&n.push({type:"boolean",name:"i18n",message:"Do you want to setup i18n structure in this plugin?",default:h.i18n}),!f&&n.push({name:"license",message:"License of the project",default:h.license}));const w=await J().prompt(n);h={...h,...w},s&&m({results:h,opts:e}),await(async(e={})=>{u("Start project creation..."),e.components=ee(e.components),e.blocks=ee(e.blocks),e.i18n=ee(e.i18n);const t=new(M())([{title:"Creating initial source files",task:()=>(async(e={})=>{const t=Q("README.md"),n=X("README.md"),s=Q("src/index.js"),i=X("src/index.js"),r=Q("_index.html"),a=X("_index.html"),c=U()[e.license],l=c&&(c.licenseText||"").replace("<year>",`${(new Date).getFullYear()}-current`).replace("<copyright holders>",e.name);b(i),o().writeFileSync(i,G()(s)(e).trim()),o().writeFileSync(a,G()(r)(e)),o().writeFileSync(n,G()(t)(e)),l&&o().writeFileSync(X("LICENSE"),l),o().copyFileSync(Z(".gitignore-t"),X(".gitignore")),o().copyFileSync(Z(".npmignore-t"),X(".npmignore")),o().copyFileSync(Z("tsconfig.json"),X("tsconfig.json"))})(e)},{title:"Creating custom Component Type file",task:()=>((e={})=>{const t="src/components.js",n=Z(t),s=X(t);e.components&&o().copyFileSync(n,s)})(e),enabled:()=>e.components},{title:"Creating Blocks file",task:()=>((e={})=>{const t="src/blocks.js",n=Z(t),s=X(t);e.blocks&&o().copyFileSync(n,s)})(e),enabled:()=>e.blocks},{title:"Creating i18n structure",task:()=>((e={})=>{const t="src/locale/en.js",n=Q(t),s=X(t);b(s),o().writeFileSync(s,G()(n)(e))})(e),enabled:()=>e.i18n},{title:"Update package.json",task:()=>((e={})=>{const t="package.json",n=Q(t),s=X(t);o().writeFileSync(s,G()(n)({...e,version:Y}))})(e)}]);await t.run()})(h),u("Project created! Happy coding")})(e))).options({verbose:{alias:"v",description:"Run with verbose logging",type:"boolean",default:!1}}).recommendCommands().strict();(async()=>{try{(await(async()=>await ne(n()).parse())())._.length||n().showHelp()}catch(e){y((e.stack||e).toString())}})()})();