@aerogel/cli 0.0.0-next.59bf5f7cc06e728d0cf6c00de28f1da48d7d6b8e → 0.0.0-next.b85327579d32f21c6a9fa21142f0165cdd320d7e

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.
Files changed (41) hide show
  1. package/dist/aerogel-cli.cjs.js +1 -1
  2. package/dist/aerogel-cli.esm.js +1 -1
  3. package/noeldemartin.config.js +11 -1
  4. package/package.json +3 -2
  5. package/src/cli.ts +4 -0
  6. package/src/commands/create.test.ts +2 -3
  7. package/src/commands/create.ts +10 -2
  8. package/src/commands/generate-component.test.ts +1 -1
  9. package/src/commands/generate-component.ts +112 -15
  10. package/src/commands/generate-model.test.ts +2 -2
  11. package/src/commands/generate-model.ts +15 -17
  12. package/src/commands/generate-service.test.ts +21 -0
  13. package/src/commands/generate-service.ts +152 -0
  14. package/src/commands/install.test.ts +18 -0
  15. package/src/commands/install.ts +32 -0
  16. package/src/lib/App.ts +59 -4
  17. package/src/lib/Editor.ts +51 -0
  18. package/src/lib/File.ts +6 -0
  19. package/src/lib/Log.mock.ts +2 -1
  20. package/src/lib/Log.ts +6 -4
  21. package/src/lib/utils/app.ts +15 -0
  22. package/src/lib/utils/edit.ts +44 -0
  23. package/src/lib/{utils.test.ts → utils/format.test.ts} +2 -2
  24. package/src/lib/{utils.ts → utils/format.ts} +0 -6
  25. package/src/lib/utils/paths.ts +30 -0
  26. package/src/plugins/Plugin.ts +125 -0
  27. package/src/plugins/Solid.ts +65 -0
  28. package/src/plugins/Soukai.ts +19 -0
  29. package/src/testing/setup.ts +31 -6
  30. package/templates/app/.eslintrc.js +3 -0
  31. package/templates/app/.vscode/launch.json +16 -0
  32. package/templates/app/.vscode/settings.json +10 -0
  33. package/templates/app/cypress.config.ts +4 -0
  34. package/templates/app/index.html +1 -1
  35. package/templates/app/package.json +17 -7
  36. package/templates/app/prettier.config.js +5 -0
  37. package/templates/app/src/App.vue +3 -1
  38. package/templates/app/src/types/globals.d.ts +0 -1
  39. package/templates/app/tailwind.config.js +1 -1
  40. package/templates/app/vite.config.ts +0 -1
  41. package/templates/service/[service.name].ts +8 -0
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("commander"),t=require("@babel/runtime/helpers/defineProperty"),n=require("@noeldemartin/utils"),s=require("fs"),i=require("path");require("core-js/modules/esnext.async-iterator.for-each.js"),require("core-js/modules/esnext.iterator.constructor.js"),require("core-js/modules/esnext.iterator.for-each.js"),require("core-js/modules/esnext.async-iterator.find.js"),require("core-js/modules/esnext.iterator.find.js"),require("core-js/modules/esnext.async-iterator.map.js"),require("core-js/modules/esnext.iterator.map.js");var r=require("chalk"),o=require("readline");require("core-js/modules/esnext.async-iterator.reduce.js"),require("core-js/modules/esnext.iterator.reduce.js");var a=require("mustache"),l=require("child_process");function c(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=c(t);var u=n.facade(new class{contains(e,t){return!!this.read(e)?.includes(t)}exists(e){return s.existsSync(e)}read(e){return this.isFile(e)?s.readFileSync(e).toString():null}getFiles(e){const t=s.readdirSync(e,{withFileTypes:!0}),n=[];for(const s of t){const t=i.resolve(e,s.name);s.isDirectory()?n.push(...this.getFiles(t)):n.push(t)}return n}isDirectory(e){return this.exists(e)&&s.lstatSync(e).isDirectory()}isFile(e){return this.exists(e)&&s.lstatSync(e).isFile()}isEmptyDirectory(e){return!!this.isDirectory(e)&&0===this.getFiles(e).length}makeDirectory(e){s.mkdirSync(e,{recursive:!0})}write(e,t){s.existsSync(i.dirname(e))||s.mkdirSync(i.dirname(e),{recursive:!0}),s.writeFileSync(e,t)}});var p=n.facade(new class{constructor(){d.default(this,"renderInfo",r.hex("#00ffff")),d.default(this,"renderSuccess",r.hex("#00ff00")),d.default(this,"renderError",r.hex("#ff0000"))}async animate(e,t){var n=this;const s=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";const s=n.renderInfo(n.renderMarkdown(e)+".".repeat(i%4))+t;n.stdout(s)};let i=0;s();const r=setInterval((()=>(i++,s())),1e3),o=await t();return clearInterval(r),s("\n"),o}info(e){this.log(this.renderMarkdown(e),this.renderInfo)}error(e){this.log(this.renderMarkdown(e),this.renderError)}fail(e){this.error(e),process.exit(1)}success(e){this.log(this.renderMarkdown(e),this.renderSuccess)}renderMarkdown(e){const t=n.stringMatchAll(e,/\*\*(.*)\*\*/g);for(const n of t)e=e.replace(n[0],r.bold(n[1]));return e}log(e,t){this.formatMessage(e).forEach((e=>{this.logLine(t?t(e):e)}))}formatMessage(e){if("\n"===e[0]){const t=(e=e.slice(1).trimEnd()).split("\n"),n=e.trim()[0]??"",s=t.find((e=>e.trim().length>0))?.indexOf(n)??0;return t.map((e=>e.slice(s)))}return[e]}logLine(e){console.log(e)}stdout(e){o.cursorTo(process.stdout,0),o.clearLine(process.stdout,0),process.stdout.write(e)}});class h{static instantiate(e,t,n){return new h(e).instantiate(t,n)}constructor(e){d.default(this,"path",void 0),this.path=e}instantiate(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=this.getFilenameReplacements(t),i=[];e=`${e}/`.replace(/\/\//,"/");for(const r of u.getFiles(this.path)){const o=Object.entries(n).reduce(((e,t)=>{let[n,s]=t;return e.replaceAll(n,s)}),r.substring(this.path.length+1)),l=s.readFileSync(r).toString(),c=e+(o.endsWith(".template")?o.slice(0,-9):o);u.write(c,a.render(l,t,void 0,["<%","%>"])),i.push(c)}return i}getFilenameReplacements(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return Object.entries(e).reduce(((e,s)=>{let[i,r]=s;return"object"==typeof r?Object.assign(e,this.getFilenameReplacements(r,`${i}.`)):e[`[${t}${i}]`]=n.toString(r),e}),{})}}function m(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return i.resolve(__dirname,"../",e)}function f(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=e.split("\n"),s=t.indent??0;let i=0,r="";for(const e of n){const t=e.trim(),n=0===t.length;if(0===r.length){if(n)continue;i=e.indexOf(t[0]??""),r+=`${" ".repeat(s)}${t}\n`;continue}if(n){r+="\n";continue}const o=e.indexOf(t[0]??"");r+=`${" ".repeat(s+o-i)}${t}\n`}return r.trimEnd()}class g{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};d.default(this,"name",void 0),d.default(this,"options",void 0),this.name=e,this.options=t}create(e){!u.exists(e)||u.isDirectory(e)&&u.isEmptyDirectory(e)||p.fail(`Folder at '${e}' already exists!`),h.instantiate(m("templates/app"),e,{app:{name:this.name,slug:n.stringToSlug(this.name)},local:this.options.local&&{aerogelPath:m("../")}})}}class y{static define(e){var t=this;e=e.command(this.command).description(this.description);for(const[t,n]of this.parameters)e=e.argument(`<${t}>`,n);for(const[t,n]of Object.entries(this.options)){const s="string"==typeof n?n:n.description,i="string"==typeof n?"string":n.type??"string";e=e.option("boolean"===i?`--${t}`:`--${t} <${i}>`,s)}e=e.action((function(){for(var e=arguments.length,n=new Array(e),s=0;s<e;s++)n[s]=arguments[s];return t.run.call(t,...n)}))}static async run(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const s=new this(...t);await s.run()}async run(){}assertAerogelOrDirectory(e){const t=u.read("package.json");if(t?.includes("@aerogel/core"))return;if(e&&u.isDirectory(e))return;const n=e?`${e} folder does not exist.`:"package.json does not contain @aerogel/core.";p.fail(`${n} Are you sure this is an Aerogel app?`)}}d.default(y,"command",""),d.default(y,"description",""),d.default(y,"parameters",[]),d.default(y,"options",{});var w=n.facade(new class{constructor(){d.default(this,"cwd",null)}setWorkingDirectory(e){this.cwd=e}async run(e){await new Promise(((t,n)=>{l.exec(e,{cwd:this.cwd??void 0},(e=>{e?n(e):t()}))}))}});class v extends y{constructor(e,t){super(),d.default(this,"path",void 0),d.default(this,"options",void 0),this.path=e,this.options=t}async run(){const e=this.path,t=this.options.name??"Aerogel App";w.setWorkingDirectory(e),await this.createApp(t,e),await this.installDependencies(),await this.initializeGit(),p.success(`\n\n That's it! You can start working on **${t}** doing the following:\n\n cd ${e}\n npm run dev\n\n Have fun!\n `)}async createApp(e,t){p.info(`Creating **${e}**...`),new g(e,{local:this.options.local}).create(t)}async installDependencies(){await p.animate("Installing dependencies",(async()=>{await w.run("npm install")}))}async initializeGit(){await p.animate("Initializing git",(async()=>{await w.run("git init"),await w.run("git add ."),await w.run('git commit -m "Start"')}))}}d.default(v,"command","create"),d.default(v,"description","Create AerogelJS app"),d.default(v,"parameters",[["path","Application path"]]),d.default(v,"options",{name:"Application name",local:{type:"boolean",description:"Whether to create an app linked to local Aerogel packages (used for core development)"}});class x extends y{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),d.default(this,"path",void 0),d.default(this,"options",void 0),this.path=e,this.options=t}async run(){this.assertAerogelOrDirectory("src/components"),this.options.story&&this.assertHistoireInstalled(),u.exists(`src/components/${this.path}.vue`)&&p.fail(`${this.path} component already exists!`);const[e,t]=this.parsePathComponents(),n=h.instantiate(m("templates/component"),`src/components/${e}`,{component:{name:t}});if(this.options.story){const e=h.instantiate(m("templates/component-story"),"src/components",{component:{name:t}});n.push(...e)}const s=n.map((e=>`- ${e}`)).join("\n");p.info(`${t} component created successfully! The following files were created:\n\n${s}`)}assertHistoireInstalled(){u.exists("src/main.histoire.ts")||p.fail("Histoire is not installed yet!")}parsePathComponents(){const e=this.path.lastIndexOf("/");return-1===e?["",this.path]:[this.path.substring(0,e),this.path.substring(e+1)]}}d.default(x,"command","generate:component"),d.default(x,"description","Generate an AerogelJS component"),d.default(x,"parameters",[["path","Component path (relative to components folder; extension not necessary)"]]),d.default(x,"options",{story:{description:"Create component story using Histoire",type:"boolean"}});class $ extends y{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),d.default(this,"name",void 0),d.default(this,"options",void 0),this.name=e,this.options=t}async run(){this.assertAerogelOrDirectory("src/models"),u.exists(`src/models/${this.name}.ts`)&&p.fail(`${this.name} model already exists!`),this.assertSoukaiInstalled();const e=h.instantiate(m("templates/model"),"src/models",{model:{name:this.name,fieldsDefinition:this.getFieldsDefinition()},soukaiImports:this.options.fields?"FieldType, defineModelSchema":"defineModelSchema"}).map((e=>`- ${e}`)).join("\n");p.info(`${this.name} model created successfully! The following files were created:\n\n${e}`)}getFieldsDefinition(){if(!this.options.fields)return" //";const e=this.options.fields.split(",").map((e=>{const[t,s,i]=e.split(":");return{name:t,type:n.stringToStudlyCase(s??"string"),required:"required"===i}})).reduce(((e,t)=>e+`\n${t.required?f(`\n ${t.name}: {\n type: FieldType.${t.type},\n required: true,\n }\n `):`${t.name}: FieldType.${t.type}`},`),"");return f(e,{indent:8})}assertSoukaiInstalled(){u.contains("package.json",'"soukai"')||u.contains("package.json",'"@aerogel/plugin-soukai"')||p.fail("\n Soukai is not installed yet! You can install it doing the following:\n\n 1. Run the following command:\n npm install soukai @aerogel/plugin-soukai@next\n\n 2. Add this to your plugins array in src/main.ts:\n soukai({ models: import.meta.glob('@/models/*', { eager: true }) })\n ")}}d.default($,"command","generate:model"),d.default($,"description","Generate an AerogelJS model"),d.default($,"parameters",[["name","Model name"]]),d.default($,"options",{fields:"Create model with the given fields"});var j=n.facade(new class{run(t){const n=new e.Command;n.name("ag").description("AerogelJS CLI").version("0.0.0"),v.define(n),x.define(n),$.define(n),n.parse(t)}});exports.CLI=j;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("commander"),t=require("@babel/runtime/helpers/defineProperty");require("core-js/modules/esnext.async-iterator.reduce.js"),require("core-js/modules/esnext.iterator.constructor.js"),require("core-js/modules/esnext.iterator.reduce.js");var i=require("@noeldemartin/utils"),s=require("fs"),n=require("path");require("core-js/modules/esnext.async-iterator.for-each.js"),require("core-js/modules/esnext.iterator.for-each.js"),require("core-js/modules/esnext.async-iterator.find.js"),require("core-js/modules/esnext.iterator.find.js"),require("core-js/modules/esnext.async-iterator.map.js"),require("core-js/modules/esnext.iterator.map.js");var r=require("chalk"),a=require("readline"),o=require("mustache");require("core-js/modules/esnext.set.add-all.js"),require("core-js/modules/esnext.set.delete-all.js"),require("core-js/modules/esnext.set.difference.js"),require("core-js/modules/esnext.set.every.js"),require("core-js/modules/esnext.set.filter.js"),require("core-js/modules/esnext.set.find.js"),require("core-js/modules/esnext.set.intersection.js"),require("core-js/modules/esnext.set.is-disjoint-from.js"),require("core-js/modules/esnext.set.is-subset-of.js"),require("core-js/modules/esnext.set.is-superset-of.js"),require("core-js/modules/esnext.set.join.js"),require("core-js/modules/esnext.set.map.js"),require("core-js/modules/esnext.set.reduce.js"),require("core-js/modules/esnext.set.some.js"),require("core-js/modules/esnext.set.symmetric-difference.js"),require("core-js/modules/esnext.set.union.js");var l=require("ts-morph"),c=require("child_process");function d(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("core-js/modules/esnext.async-iterator.some.js"),require("core-js/modules/esnext.iterator.some.js");var u=d(t);var p=i.facade(new class{contains(e,t){return!!this.read(e)?.includes(t)}exists(e){return s.existsSync(e)}isSymlink(e){return s.lstatSync(e).isSymbolicLink()}read(e){return this.isFile(e)?s.readFileSync(e).toString():null}getFiles(e){const t=s.readdirSync(e,{withFileTypes:!0}),i=[];for(const s of t){const t=n.resolve(e,s.name);s.isDirectory()?i.push(...this.getFiles(t)):i.push(t)}return i}isDirectory(e){return this.exists(e)&&s.lstatSync(e).isDirectory()}isFile(e){return this.exists(e)&&s.lstatSync(e).isFile()}isEmptyDirectory(e){return!!this.isDirectory(e)&&0===this.getFiles(e).length}makeDirectory(e){s.mkdirSync(e,{recursive:!0})}write(e,t){s.existsSync(n.dirname(e))||s.mkdirSync(n.dirname(e),{recursive:!0}),s.writeFileSync(e,t)}});var m=i.facade(new class{constructor(){u.default(this,"renderInfo",r.hex("#00ffff")),u.default(this,"renderSuccess",r.hex("#00ff00")),u.default(this,"renderError",r.hex("#ff0000"))}async animate(e,t){var i=this;const s=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",s=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const r=i.renderInfo(i.renderMarkdown(e)+(s?"...":".".repeat(n%4)))+t;i.stdout(r)};let n=0;s();const r=setInterval((()=>(n++,s())),1e3),a=await t();return clearInterval(r),s("\n",!0),a}info(e){this.log(this.renderMarkdown(e),this.renderInfo)}error(e){this.log(this.renderMarkdown(e),this.renderError)}fail(e){this.error(e),process.exit(1)}success(e){this.log(this.renderMarkdown(e),this.renderSuccess)}renderMarkdown(e){const t=i.stringMatchAll(e,/\*\*(.*)\*\*/g);for(const i of t)e=e.replace(i[0],r.bold(i[1]));return e}log(e,t){this.formatMessage(e).forEach((e=>{this.logLine(t?t(e):e)}))}formatMessage(e){if("\n"===e[0]){const t=(e=e.slice(1).trimEnd()).split("\n"),i=e.trim()[0]??"",s=t.find((e=>e.trim().length>0))?.indexOf(i)??0;return t.map((e=>e.slice(s)))}return[e]}logLine(e){console.log(e)}stdout(e){a.cursorTo(process.stdout,0),a.clearLine(process.stdout,0),process.stdout.write(e)}});class g{static instantiate(e,t,i){return new g(e).instantiate(t,i)}constructor(e){u.default(this,"path",void 0),this.path=e}instantiate(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=this.getFilenameReplacements(t),n=[];e=`${e}/`.replace(/\/\//,"/");for(const r of p.getFiles(this.path)){const a=Object.entries(i).reduce(((e,t)=>{let[i,s]=t;return e.replaceAll(i,s)}),r.substring(this.path.length+1)),l=s.readFileSync(r).toString(),c=e+(a.endsWith(".template")?a.slice(0,-9):a);p.write(c,o.render(l,t,void 0,["<%","%>"])),n.push(c)}return n}getFilenameReplacements(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return Object.entries(e).reduce(((e,s)=>{let[n,r]=s;return"object"==typeof r?Object.assign(e,this.getFilenameReplacements(r,`${n}.`)):e[`[${t}${n}]`]=i.toString(r),e}),{})}}function f(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";if(p.contains(n.resolve(__dirname,"../../../package.json"),'"name": "aerogel"'))return n.resolve(__dirname,"../",e);const t=p.read(n.resolve(__dirname,"../../../../package.json")),s=i.stringMatch(t??"",/"@aerogel\/cli": "file:(.*)\/aerogel-cli-[\d.]*\.tgz"/),r=s?.[1]??m.fail("Could not determine base path");return n.resolve(r,e)}function h(e){return m.fail(`Could not find ${e} pack file, did you run 'npm pack'?`)}function y(e){return p.getFiles(v(e)).find((e=>e.endsWith(".tgz")))??null}function v(e){return f(`../${e}`)}var w=i.facade(new class{constructor(){u.default(this,"cwd",null)}setWorkingDirectory(e){this.cwd=e}async run(e){await new Promise(((t,i)=>{c.exec(e,{cwd:this.cwd??void 0},(e=>{e?i(e):t()}))}))}});class x{constructor(){u.default(this,"project",void 0),u.default(this,"modifiedFiles",void 0),this.project=new l.Project({tsConfigFilePath:"tsconfig.json"}),this.modifiedFiles=new Set,this.project.addSourceFilesAtPaths("src/**/*.ts"),this.project.addSourceFilesAtPaths("tailwind.config.js"),this.project.addSourceFilesAtPaths("vite.config.ts")}addSourceFile(e){this.project.addSourceFilesAtPaths(e)}requireSourceFile(e){return this.project.getSourceFileOrThrow(e)}async format(){await m.animate("Formatting modified files",(async()=>{const e=p.exists("prettier.config.js"),t=p.exists(".eslintrc.js");await Promise.all(i.arrayFrom(this.modifiedFiles).map((async i=>{e&&await w.run(`npx prettier ${i} --write`),t&&await w.run(`npx eslint ${i} --fix`)})))}))}async save(e){await e.save(),this.modifiedFiles.add(e.getFilePath())}}class j{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};u.default(this,"name",void 0),u.default(this,"options",void 0),this.name=e,this.options=t}create(e){!p.exists(e)||p.isDirectory(e)&&p.isEmptyDirectory(e)||m.fail(`Folder at '${e}' already exists!`),g.instantiate(f("templates/app"),e,{app:{name:this.name,slug:i.stringToSlug(this.name)},dependencies:this.getDependencies(),contentPath:this.options.linkedLocal?`${v("core")}/dist/**/*.js`:"./node_modules/@aerogel/core/dist/**/*.js"})}edit(){return new x}getDependencies(){const e=e=>Object.entries(e).reduce(((e,t)=>{let[i,s]=t;return Object.assign(e,{[i]:`file:${s}`})}),{});return this.options.linkedLocal?e({aerogelCli:v("cli"),aerogelCore:v("core"),aerogelCypress:v("cypress"),aerogelPluginI18n:v("plugin-i18n"),aerogelPluginSoukai:v("plugin-soukai"),aerogelVite:v("vite")}):this.options.local?e({aerogelCli:y("cli")??h("cli"),aerogelCore:y("core")??h("core"),aerogelCypress:y("cypress")??h("cypress"),aerogelPluginI18n:y("plugin-i18n")??h("plugin-i18n"),aerogelPluginSoukai:y("plugin-soukai")??h("plugin-soukai"),aerogelVite:y("vite")??h("vite")}):{aerogelCli:"next",aerogelCore:"next",aerogelCypress:"next",aerogelPluginI18n:"next",aerogelPluginSoukai:"next",aerogelVite:"next"}}}class S{static define(e){var t=this;e=e.command(this.command).description(this.description);for(const[t,i]of this.parameters)e=e.argument(`<${t}>`,i);for(const[t,i]of Object.entries(this.options)){const s="string"==typeof i?i:i.description,n="string"==typeof i?"string":i.type??"string";e=e.option("boolean"===n?`--${t}`:`--${t} <${n}>`,s)}e=e.action((function(){for(var e=arguments.length,i=new Array(e),s=0;s<e;s++)i[s]=arguments[s];return t.run.call(t,...i)}))}static async run(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const s=new this(...t);await s.run()}async run(){}assertAerogelOrDirectory(e){const t=p.read("package.json");if(t?.includes("@aerogel/core"))return;if(e&&p.isDirectory(e))return;const i=e?`${e} folder does not exist.`:"package.json does not contain @aerogel/core.";m.fail(`${i} Are you sure this is an Aerogel app?`)}}u.default(S,"command",""),u.default(S,"description",""),u.default(S,"parameters",[]),u.default(S,"options",{});class k extends S{constructor(e,t){super(),u.default(this,"path",void 0),u.default(this,"options",void 0),this.path=e,this.options=t}async run(){const e=this.path,t=this.options.name??"Aerogel App";w.setWorkingDirectory(e),await this.createApp(t,e),await this.installDependencies(),await this.initializeGit(),m.success(`\n\n That's it! You can start working on **${t}** doing the following:\n\n cd ${e}\n npm run dev\n\n Have fun!\n `)}async createApp(e,t){m.info(`Creating **${e}**...`),new j(e,{local:this.options.local,linkedLocal:this.options.local&&!this.options.copy}).create(t)}async installDependencies(){await m.animate("Installing dependencies",(async()=>{await w.run("npm install")}))}async initializeGit(){await m.animate("Initializing git",(async()=>{await w.run("git init"),await w.run("git add ."),await w.run('git commit -m "Start"')}))}}function $(){return new j("")}function C(){return p.isSymlink("node_modules/@aerogel/core")}function A(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e)return;const s=t.guard??(()=>!0),n=t.validate??(()=>!0),r=i.arrayFrom(t.skip??[]);return e.forEachDescendant(((e,t)=>{if(s(e)&&n(e))return e;const i=e.getKind();r.includes(i)&&t.skip()}))}function F(e,t){if(e&&t(e))return e}u.default(k,"command","create"),u.default(k,"description","Create AerogelJS app"),u.default(k,"parameters",[["path","Application path"]]),u.default(k,"options",{name:"Application name",local:{type:"boolean",description:"Whether to create an app using local Aerogel packages (used for core development)"},copy:{type:"boolean",description:"Whether to create an app linked to local Aerogel packages (used in CI)"}});class q extends S{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),u.default(this,"path",void 0),u.default(this,"options",void 0),this.path=e,this.options=t}async run(){this.assertAerogelOrDirectory("src/components"),this.assertHistoireInstalled();const e=new Set,[t,s]=this.parsePathComponents();await this.createComponent(t,s,e),await this.createStory(s,e),await this.declareComponents();const n=i.arrayFrom(e).map((e=>`- ${e}`)).join("\n");m.info(`${s} component created successfully! The following files were created:\n\n${n}`)}assertHistoireInstalled(){this.options.story&&(p.exists("src/main.histoire.ts")||m.fail("Histoire is not installed yet!"))}async createComponent(e,t,i){await m.animate("Creating component",(async()=>{p.exists(`src/components/${this.path}.vue`)&&m.fail(`${this.path} component already exists!`);g.instantiate(f("templates/component"),`src/components/${e}`,{component:{name:t}}).forEach((e=>i.add(e)))}))}async createStory(e,t){this.options.story&&await m.animate("Creating story",(async()=>{g.instantiate(f("templates/component-story"),"src/components",{component:{name:e}}).forEach((e=>t.add(e)))}))}async declareComponents(){const e=$().edit(),t=e.requireSourceFile("vite.config.ts"),i=this.getComponentDirsArray(t);if(!i)return m.fail("Could not find component dirs declaration in vite config!");i.getDescendantsOfKind(l.SyntaxKind.StringLiteral).some((e=>"'src/components'"===e.getText()))||(await m.animate("Updating vite config",(async()=>{i.addElement("'src/components'"),await e.save(t)})),await e.format())}getComponentDirsArray(e){const t=A(e,{guard:l.Node.isCallExpression,validate:e=>e.getText().startsWith("Components("),skip:l.SyntaxKind.ImportDeclaration});if(!t)return null;const i=A(t,{guard:l.Node.isPropertyAssignment,validate:e=>"dirs"===e.getName()}),s=i?.getInitializer();return l.Node.isArrayLiteralExpression(s)?s:this.declareComponentDirsArray(t)}declareComponentDirsArray(e){const t=A(e,{guard:l.Node.isObjectLiteralExpression}),i=t?.addPropertyAssignment({name:"dirs",initializer:"[]"});return i?.getInitializer()??null}parsePathComponents(){const e=this.path.lastIndexOf("/");return-1===e?["",this.path]:[this.path.substring(0,e),this.path.substring(e+1)]}}function D(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=e.split("\n"),s=t.indent??0;let n=0,r="";for(const e of i){const t=e.trim(),i=0===t.length;if(0===r.length){if(i)continue;n=e.indexOf(t[0]??""),r+=`${" ".repeat(s)}${t}\n`;continue}if(i){r+="\n";continue}const a=e.indexOf(t[0]??"");r+=`${" ".repeat(s+a-n)}${t}\n`}return r.trimEnd()}u.default(q,"command","generate:component"),u.default(q,"description","Generate an AerogelJS Component"),u.default(q,"parameters",[["path","Component path (relative to components folder; extension not necessary)"]]),u.default(q,"options",{story:{description:"Create component story using Histoire",type:"boolean"}});class I extends S{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),u.default(this,"name",void 0),u.default(this,"options",void 0),this.name=e,this.options=t}async run(){this.assertAerogelOrDirectory("src/models"),p.exists(`src/models/${this.name}.ts`)&&m.fail(`${this.name} model already exists!`),this.assertSoukaiInstalled();const e=await m.animate("Creating model",(async()=>g.instantiate(f("templates/model"),"src/models",{model:{name:this.name,fieldsDefinition:this.getFieldsDefinition()},soukaiImports:this.options.fields?"FieldType, defineModelSchema":"defineModelSchema"}).map((e=>`- ${e}`)).join("\n")));m.info(`${this.name} model created successfully! The following files were created:\n\n${e}`)}getFieldsDefinition(){if(!this.options.fields)return" //";const e=this.options.fields.split(",").map((e=>{const[t,s,n]=e.split(":");return{name:t,type:i.stringToStudlyCase(s??"string"),required:"required"===n}})).reduce(((e,t)=>e+`\n${t.required?D(`\n ${t.name}: {\n type: FieldType.${t.type},\n required: true,\n }\n `):`${t.name}: FieldType.${t.type}`},`),"");return D(e,{indent:8})}assertSoukaiInstalled(){p.contains("package.json",'"soukai"')||p.contains("package.json",'"@aerogel/plugin-soukai"')||m.fail("\n Soukai is not installed yet! You can install it running:\n npx ag install soukai\n ")}}u.default(I,"command","generate:model"),u.default(I,"description","Generate an AerogelJS Model"),u.default(I,"parameters",[["name","Model name"]]),u.default(I,"options",{fields:"Create model with the given fields"});class P extends S{constructor(e){super(),u.default(this,"name",void 0),this.name=e}async run(){this.assertAerogelOrDirectory("src/services");const e=new Set,t=$().edit();await this.createService(e),await this.registerService(t),await t.format();const s=i.arrayFrom(e).map((e=>`- ${e}`)).join("\n");m.info(`${this.name} service created successfully! The following files were created:\n\n${s}`)}async createService(e){await m.animate("Creating service",(async()=>{p.exists(`src/services/${this.name}.ts`)&&m.fail(`${this.name} service already exists!`);g.instantiate(f("templates/service"),"src/services",{service:{name:this.name}}).forEach((t=>e.add(t)))}))}async registerService(e){await m.animate("Registering service",(async()=>{p.exists("src/services/index.ts")||await this.createServicesIndex(e);const t=e.requireSourceFile("src/services/index.ts"),s=this.getServicesObject(t);if(!s)return m.fail("Could not find services object in services config, please add it manually.");t.addImportDeclaration({defaultImport:this.name,moduleSpecifier:`./${this.name}`}),s.addPropertyAssignment({name:`$${i.stringToCamelCase(this.name)}`,initializer:this.name}),await e.save(t)}))}async createServicesIndex(e){p.write("src/services/index.ts",D("\n export const services = {};\n\n export type AppServices = typeof services;\n\n declare module '@vue/runtime-core' {\n interface ComponentCustomProperties extends AppServices {}\n }\n ")),e.addSourceFile("src/services/index.ts");const t=e.requireSourceFile("src/main.ts"),i=this.getBootstrapOptions(t);if(!i)return m.fail("Could not find options object in bootstrap config, please add the services manually.");i.insertShorthandPropertyAssignment(0,{name:"services"}),t.addImportDeclaration({namedImports:["services"],moduleSpecifier:"./services"}),await e.save(t)}getBootstrapOptions(e){const t=A(e,{guard:l.Node.isCallExpression,validate:e=>"bootstrapApplication"===e.getExpression().getText(),skip:l.SyntaxKind.ImportDeclaration}),i=t?.getArguments()[1];return l.Node.isObjectLiteralExpression(i)?i:null}getServicesObject(e){const t=A(e,{guard:l.Node.isVariableDeclaration,validate:e=>"services"===e.getName()}),i=t?.getInitializer();return l.Node.isObjectLiteralExpression(i)?i:null}}u.default(P,"command","generate:service"),u.default(P,"description","Generate an AerogelJS Service"),u.default(P,"parameters",[["name","Service name"]]);class b{constructor(e){u.default(this,"name",void 0),this.name=e}async install(){this.assertNotInstalled(),await this.installDependencies();{const e=$().edit();await this.updateFiles(e),await e.format()}m.info(`Plugin ${this.name} installed!`)}assertNotInstalled(){p.contains("package.json",`"${this.getNpmPackageName()}"`)&&m.fail(`${this.name} is already installed!`)}async installDependencies(){await m.animate("Installing plugin dependencies",(async()=>{await this.installNpmDependencies()}))}async updateFiles(e){await this.updateBootstrapConfig(e)}async installNpmDependencies(){if(C())await w.run(`npm install file:${v(this.getLocalPackageName())}`);else if(p.contains("package.json","file")){const e=y(this.getLocalPackageName())??h(this.getLocalPackageName());await w.run(`npm install file:${e}`)}else await w.run(`npm install ${this.getNpmPackageName()}@next`)}async updateBootstrapConfig(e){await m.animate("Injecting plugin in bootstrap configuration",(async()=>{const t=e.requireSourceFile("src/main.ts"),i=this.getBootstrapPluginsDeclaration(t);if(!i)return m.fail(`\n Could not find plugins array in bootstrap config, please add the following manually:\n\n ${this.getBootstrapConfig()}\n `);t.addImportDeclaration(this.getBootstrapImport()),i.addElement(this.getBootstrapConfig()),await e.save(t)}))}getBootstrapPluginsDeclaration(e){const t=A(e,{guard:l.Node.isCallExpression,validate:e=>"bootstrapApplication"===e.getExpression().getText(),skip:l.SyntaxKind.ImportDeclaration}),i=t?.getArguments()[1],s=F(i,l.Node.isObjectLiteralExpression)?.getProperty("plugins"),n=F(s,l.Node.isPropertyAssignment)?.getInitializer();return l.Node.isArrayLiteralExpression(n)?n:null}getBootstrapImport(){return{defaultImport:this.name,moduleSpecifier:`@aerogel/plugin-${this.name}`}}getNpmPackageName(){return`@aerogel/${this.getLocalPackageName()}`}getLocalPackageName(){return`plugin-${this.name}`}getBootstrapConfig(){return`${this.name}()`}}const N=[new class extends b{constructor(){super("soukai")}async installNpmDependencies(){await w.run("npm install soukai@next"),await super.installNpmDependencies()}getBootstrapConfig(){return"soukai({ models: import.meta.glob('@/models/*', { eager: true }) })"}},new class extends b{constructor(){super("solid")}async updateFiles(e){await this.updateTailwindConfig(e),await super.updateFiles(e)}async installNpmDependencies(){await w.run("npm install soukai-solid@next"),await super.installNpmDependencies()}async updateTailwindConfig(e){await m.animate("Updating tailwind configuration",(async()=>{const t=e.requireSourceFile("tailwind.config.js"),i=this.getTailwindContentArray(t),s=C()?`'${v("plugin-solid")}/dist/**/*.js'`:"'./node_modules/@aerogel/plugin-solid/dist/**/*.js'";if(!i)return m.fail(`\n Could not find content array in tailwind config, please add the following manually:\n\n ${s}\n `);i.addElement(s),await e.save(t)}))}getTailwindContentArray(e){const t=A(e,{guard:l.Node.isPropertyAssignment,validate:e=>"content"===e.getName(),skip:l.SyntaxKind.JSDoc}),i=t?.getInitializer();return l.Node.isArrayLiteralExpression(i)?i:null}}].reduce(((e,t)=>Object.assign(e,{[t.name]:t})),{});class O extends S{constructor(e){super(),u.default(this,"plugin",void 0),this.plugin=N[e]??m.fail(`Plugin '${e}' doesn't exist. Available plugins: ${Object.keys(N).join(", ")}`)}async run(){await this.plugin.install()}}u.default(O,"command","install"),u.default(O,"description","Install an AerogelJS plugin"),u.default(O,"parameters",[["plugin","Plugin to install"]]);var E=i.facade(new class{run(t){const i=new e.Command;i.name("ag").description("AerogelJS CLI").version("0.0.0"),k.define(i),q.define(i),I.define(i),P.define(i),O.define(i),i.parse(t)}});exports.CLI=E;
2
2
  //# sourceMappingURL=aerogel-cli.cjs.js.map
@@ -1,2 +1,2 @@
1
- import{Command as e}from"commander";import t from"@babel/runtime/helpers/esm/defineProperty";import{facade as s,stringMatchAll as n,toString as i,stringToSlug as o,stringToStudlyCase as r}from"@noeldemartin/utils";import{existsSync as a,readFileSync as c,readdirSync as l,lstatSync as p,mkdirSync as d,writeFileSync as m}from"fs";import{resolve as h,dirname as u}from"path";import"core-js/modules/esnext.async-iterator.for-each.js";import"core-js/modules/esnext.iterator.constructor.js";import"core-js/modules/esnext.iterator.for-each.js";import"core-js/modules/esnext.async-iterator.find.js";import"core-js/modules/esnext.iterator.find.js";import"core-js/modules/esnext.async-iterator.map.js";import"core-js/modules/esnext.iterator.map.js";import{hex as f,bold as g}from"chalk";import{cursorTo as y,clearLine as w}from"readline";import"core-js/modules/esnext.async-iterator.reduce.js";import"core-js/modules/esnext.iterator.reduce.js";import{render as v}from"mustache";import{exec as $}from"child_process";var x=s(new class{contains(e,t){return!!this.read(e)?.includes(t)}exists(e){return a(e)}read(e){return this.isFile(e)?c(e).toString():null}getFiles(e){const t=l(e,{withFileTypes:!0}),s=[];for(const n of t){const t=h(e,n.name);n.isDirectory()?s.push(...this.getFiles(t)):s.push(t)}return s}isDirectory(e){return this.exists(e)&&p(e).isDirectory()}isFile(e){return this.exists(e)&&p(e).isFile()}isEmptyDirectory(e){return!!this.isDirectory(e)&&0===this.getFiles(e).length}makeDirectory(e){d(e,{recursive:!0})}write(e,t){a(u(e))||d(u(e),{recursive:!0}),m(e,t)}});var j=s(new class{constructor(){t(this,"renderInfo",f("#00ffff")),t(this,"renderSuccess",f("#00ff00")),t(this,"renderError",f("#ff0000"))}async animate(e,t){var s=this;const n=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";const n=s.renderInfo(s.renderMarkdown(e)+".".repeat(i%4))+t;s.stdout(n)};let i=0;n();const o=setInterval((()=>(i++,n())),1e3),r=await t();return clearInterval(o),n("\n"),r}info(e){this.log(this.renderMarkdown(e),this.renderInfo)}error(e){this.log(this.renderMarkdown(e),this.renderError)}fail(e){this.error(e),process.exit(1)}success(e){this.log(this.renderMarkdown(e),this.renderSuccess)}renderMarkdown(e){const t=n(e,/\*\*(.*)\*\*/g);for(const s of t)e=e.replace(s[0],g(s[1]));return e}log(e,t){this.formatMessage(e).forEach((e=>{this.logLine(t?t(e):e)}))}formatMessage(e){if("\n"===e[0]){const t=(e=e.slice(1).trimEnd()).split("\n"),s=e.trim()[0]??"",n=t.find((e=>e.trim().length>0))?.indexOf(s)??0;return t.map((e=>e.slice(n)))}return[e]}logLine(e){console.log(e)}stdout(e){y(process.stdout,0),w(process.stdout,0),process.stdout.write(e)}});class k{static instantiate(e,t,s){return new k(e).instantiate(t,s)}constructor(e){t(this,"path",void 0),this.path=e}instantiate(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=this.getFilenameReplacements(t),n=[];e=`${e}/`.replace(/\/\//,"/");for(const i of x.getFiles(this.path)){const o=Object.entries(s).reduce(((e,t)=>{let[s,n]=t;return e.replaceAll(s,n)}),i.substring(this.path.length+1)),r=c(i).toString(),a=e+(o.endsWith(".template")?o.slice(0,-9):o);x.write(a,v(r,t,void 0,["<%","%>"])),n.push(a)}return n}getFilenameReplacements(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return Object.entries(e).reduce(((e,s)=>{let[n,o]=s;return"object"==typeof o?Object.assign(e,this.getFilenameReplacements(o,`${n}.`)):e[`[${t}${n}]`]=i(o),e}),{})}}function A(){return h(__dirname,"../",arguments.length>0&&void 0!==arguments[0]?arguments[0]:"")}function D(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=e.split("\n"),n=t.indent??0;let i=0,o="";for(const e of s){const t=e.trim(),s=0===t.length;if(0===o.length){if(s)continue;i=e.indexOf(t[0]??""),o+=`${" ".repeat(n)}${t}\n`;continue}if(s){o+="\n";continue}const r=e.indexOf(t[0]??"");o+=`${" ".repeat(n+r-i)}${t}\n`}return o.trimEnd()}class F{constructor(e){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t(this,"name",void 0),t(this,"options",void 0),this.name=e,this.options=s}create(e){!x.exists(e)||x.isDirectory(e)&&x.isEmptyDirectory(e)||j.fail(`Folder at '${e}' already exists!`),k.instantiate(A("templates/app"),e,{app:{name:this.name,slug:o(this.name)},local:this.options.local&&{aerogelPath:A("../")}})}}class I{static define(e){var t=this;e=e.command(this.command).description(this.description);for(const[t,s]of this.parameters)e=e.argument(`<${t}>`,s);for(const[t,s]of Object.entries(this.options)){const n="string"==typeof s?s:s.description,i="string"==typeof s?"string":s.type??"string";e=e.option("boolean"===i?`--${t}`:`--${t} <${i}>`,n)}e=e.action((function(){for(var e=arguments.length,s=new Array(e),n=0;n<e;n++)s[n]=arguments[n];return t.run.call(t,...s)}))}static async run(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];const n=new this(...t);await n.run()}async run(){}assertAerogelOrDirectory(e){const t=x.read("package.json");if(t?.includes("@aerogel/core"))return;if(e&&x.isDirectory(e))return;const s=e?`${e} folder does not exist.`:"package.json does not contain @aerogel/core.";j.fail(`${s} Are you sure this is an Aerogel app?`)}}t(I,"command",""),t(I,"description",""),t(I,"parameters",[]),t(I,"options",{});var b=s(new class{constructor(){t(this,"cwd",null)}setWorkingDirectory(e){this.cwd=e}async run(e){await new Promise(((t,s)=>{$(e,{cwd:this.cwd??void 0},(e=>{e?s(e):t()}))}))}});class S extends I{constructor(e,s){super(),t(this,"path",void 0),t(this,"options",void 0),this.path=e,this.options=s}async run(){const e=this.path,t=this.options.name??"Aerogel App";b.setWorkingDirectory(e),await this.createApp(t,e),await this.installDependencies(),await this.initializeGit(),j.success(`\n\n That's it! You can start working on **${t}** doing the following:\n\n cd ${e}\n npm run dev\n\n Have fun!\n `)}async createApp(e,t){j.info(`Creating **${e}**...`),new F(e,{local:this.options.local}).create(t)}async installDependencies(){await j.animate("Installing dependencies",(async()=>{await b.run("npm install")}))}async initializeGit(){await j.animate("Initializing git",(async()=>{await b.run("git init"),await b.run("git add ."),await b.run('git commit -m "Start"')}))}}t(S,"command","create"),t(S,"description","Create AerogelJS app"),t(S,"parameters",[["path","Application path"]]),t(S,"options",{name:"Application name",local:{type:"boolean",description:"Whether to create an app linked to local Aerogel packages (used for core development)"}});class O extends I{constructor(e){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),t(this,"path",void 0),t(this,"options",void 0),this.path=e,this.options=s}async run(){this.assertAerogelOrDirectory("src/components"),this.options.story&&this.assertHistoireInstalled(),x.exists(`src/components/${this.path}.vue`)&&j.fail(`${this.path} component already exists!`);const[e,t]=this.parsePathComponents(),s=k.instantiate(A("templates/component"),`src/components/${e}`,{component:{name:t}});if(this.options.story){const e=k.instantiate(A("templates/component-story"),"src/components",{component:{name:t}});s.push(...e)}const n=s.map((e=>`- ${e}`)).join("\n");j.info(`${t} component created successfully! The following files were created:\n\n${n}`)}assertHistoireInstalled(){x.exists("src/main.histoire.ts")||j.fail("Histoire is not installed yet!")}parsePathComponents(){const e=this.path.lastIndexOf("/");return-1===e?["",this.path]:[this.path.substring(0,e),this.path.substring(e+1)]}}t(O,"command","generate:component"),t(O,"description","Generate an AerogelJS component"),t(O,"parameters",[["path","Component path (relative to components folder; extension not necessary)"]]),t(O,"options",{story:{description:"Create component story using Histoire",type:"boolean"}});class C extends I{constructor(e){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),t(this,"name",void 0),t(this,"options",void 0),this.name=e,this.options=s}async run(){this.assertAerogelOrDirectory("src/models"),x.exists(`src/models/${this.name}.ts`)&&j.fail(`${this.name} model already exists!`),this.assertSoukaiInstalled();const e=k.instantiate(A("templates/model"),"src/models",{model:{name:this.name,fieldsDefinition:this.getFieldsDefinition()},soukaiImports:this.options.fields?"FieldType, defineModelSchema":"defineModelSchema"}).map((e=>`- ${e}`)).join("\n");j.info(`${this.name} model created successfully! The following files were created:\n\n${e}`)}getFieldsDefinition(){if(!this.options.fields)return" //";const e=this.options.fields.split(",").map((e=>{const[t,s,n]=e.split(":");return{name:t,type:r(s??"string"),required:"required"===n}})).reduce(((e,t)=>e+`\n${t.required?D(`\n ${t.name}: {\n type: FieldType.${t.type},\n required: true,\n }\n `):`${t.name}: FieldType.${t.type}`},`),"");return D(e,{indent:8})}assertSoukaiInstalled(){x.contains("package.json",'"soukai"')||x.contains("package.json",'"@aerogel/plugin-soukai"')||j.fail("\n Soukai is not installed yet! You can install it doing the following:\n\n 1. Run the following command:\n npm install soukai @aerogel/plugin-soukai@next\n\n 2. Add this to your plugins array in src/main.ts:\n soukai({ models: import.meta.glob('@/models/*', { eager: true }) })\n ")}}t(C,"command","generate:model"),t(C,"description","Generate an AerogelJS model"),t(C,"parameters",[["name","Model name"]]),t(C,"options",{fields:"Create model with the given fields"});var M=s(new class{run(t){const s=new e;s.name("ag").description("AerogelJS CLI").version("0.0.0"),S.define(s),O.define(s),C.define(s),s.parse(t)}});export{M as CLI};
1
+ import{Command as e}from"commander";import t from"@babel/runtime/helpers/esm/defineProperty";import"core-js/modules/esnext.async-iterator.reduce.js";import"core-js/modules/esnext.iterator.constructor.js";import"core-js/modules/esnext.iterator.reduce.js";import{facade as i,stringMatchAll as s,toString as n,stringMatch as r,arrayFrom as a,stringToSlug as o,stringToStudlyCase as l,stringToCamelCase as c}from"@noeldemartin/utils";import{existsSync as p,lstatSync as d,readFileSync as m,readdirSync as u,mkdirSync as g,writeFileSync as h}from"fs";import{resolve as f,dirname as y}from"path";import"core-js/modules/esnext.async-iterator.for-each.js";import"core-js/modules/esnext.iterator.for-each.js";import"core-js/modules/esnext.async-iterator.find.js";import"core-js/modules/esnext.iterator.find.js";import"core-js/modules/esnext.async-iterator.map.js";import"core-js/modules/esnext.iterator.map.js";import{hex as w,bold as v}from"chalk";import{cursorTo as j,clearLine as x}from"readline";import{render as $}from"mustache";import"core-js/modules/esnext.set.add-all.js";import"core-js/modules/esnext.set.delete-all.js";import"core-js/modules/esnext.set.difference.js";import"core-js/modules/esnext.set.every.js";import"core-js/modules/esnext.set.filter.js";import"core-js/modules/esnext.set.find.js";import"core-js/modules/esnext.set.intersection.js";import"core-js/modules/esnext.set.is-disjoint-from.js";import"core-js/modules/esnext.set.is-subset-of.js";import"core-js/modules/esnext.set.is-superset-of.js";import"core-js/modules/esnext.set.join.js";import"core-js/modules/esnext.set.map.js";import"core-js/modules/esnext.set.reduce.js";import"core-js/modules/esnext.set.some.js";import"core-js/modules/esnext.set.symmetric-difference.js";import"core-js/modules/esnext.set.union.js";import{Project as k,SyntaxKind as S,Node as C}from"ts-morph";import{exec as A}from"child_process";import"core-js/modules/esnext.async-iterator.some.js";import"core-js/modules/esnext.iterator.some.js";var D=i(new class{contains(e,t){return!!this.read(e)?.includes(t)}exists(e){return p(e)}isSymlink(e){return d(e).isSymbolicLink()}read(e){return this.isFile(e)?m(e).toString():null}getFiles(e){const t=u(e,{withFileTypes:!0}),i=[];for(const s of t){const t=f(e,s.name);s.isDirectory()?i.push(...this.getFiles(t)):i.push(t)}return i}isDirectory(e){return this.exists(e)&&d(e).isDirectory()}isFile(e){return this.exists(e)&&d(e).isFile()}isEmptyDirectory(e){return!!this.isDirectory(e)&&0===this.getFiles(e).length}makeDirectory(e){g(e,{recursive:!0})}write(e,t){p(y(e))||g(y(e),{recursive:!0}),h(e,t)}});var F=i(new class{constructor(){t(this,"renderInfo",w("#00ffff")),t(this,"renderSuccess",w("#00ff00")),t(this,"renderError",w("#ff0000"))}async animate(e,t){var i=this;const s=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",s=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const r=i.renderInfo(i.renderMarkdown(e)+(s?"...":".".repeat(n%4)))+t;i.stdout(r)};let n=0;s();const r=setInterval((()=>(n++,s())),1e3),a=await t();return clearInterval(r),s("\n",!0),a}info(e){this.log(this.renderMarkdown(e),this.renderInfo)}error(e){this.log(this.renderMarkdown(e),this.renderError)}fail(e){this.error(e),process.exit(1)}success(e){this.log(this.renderMarkdown(e),this.renderSuccess)}renderMarkdown(e){const t=s(e,/\*\*(.*)\*\*/g);for(const i of t)e=e.replace(i[0],v(i[1]));return e}log(e,t){this.formatMessage(e).forEach((e=>{this.logLine(t?t(e):e)}))}formatMessage(e){if("\n"===e[0]){const t=(e=e.slice(1).trimEnd()).split("\n"),i=e.trim()[0]??"",s=t.find((e=>e.trim().length>0))?.indexOf(i)??0;return t.map((e=>e.slice(s)))}return[e]}logLine(e){console.log(e)}stdout(e){j(process.stdout,0),x(process.stdout,0),process.stdout.write(e)}});class I{static instantiate(e,t,i){return new I(e).instantiate(t,i)}constructor(e){t(this,"path",void 0),this.path=e}instantiate(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=this.getFilenameReplacements(t),s=[];e=`${e}/`.replace(/\/\//,"/");for(const n of D.getFiles(this.path)){const r=Object.entries(i).reduce(((e,t)=>{let[i,s]=t;return e.replaceAll(i,s)}),n.substring(this.path.length+1)),a=m(n).toString(),o=e+(r.endsWith(".template")?r.slice(0,-9):r);D.write(o,$(a,t,void 0,["<%","%>"])),s.push(o)}return s}getFilenameReplacements(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return Object.entries(e).reduce(((e,i)=>{let[s,r]=i;return"object"==typeof r?Object.assign(e,this.getFilenameReplacements(r,`${s}.`)):e[`[${t}${s}]`]=n(r),e}),{})}}function P(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";if(D.contains(f(__dirname,"../../../package.json"),'"name": "aerogel"'))return f(__dirname,"../",e);const t=D.read(f(__dirname,"../../../../package.json")),i=r(t??"",/"@aerogel\/cli": "file:(.*)\/aerogel-cli-[\d.]*\.tgz"/),s=i?.[1]??F.fail("Could not determine base path");return f(s,e)}function b(e){return F.fail(`Could not find ${e} pack file, did you run 'npm pack'?`)}function E(e){return D.getFiles(O(e)).find((e=>e.endsWith(".tgz")))??null}function O(e){return P(`../${e}`)}var N=i(new class{constructor(){t(this,"cwd",null)}setWorkingDirectory(e){this.cwd=e}async run(e){await new Promise(((t,i)=>{A(e,{cwd:this.cwd??void 0},(e=>{e?i(e):t()}))}))}});class L{constructor(){t(this,"project",void 0),t(this,"modifiedFiles",void 0),this.project=new k({tsConfigFilePath:"tsconfig.json"}),this.modifiedFiles=new Set,this.project.addSourceFilesAtPaths("src/**/*.ts"),this.project.addSourceFilesAtPaths("tailwind.config.js"),this.project.addSourceFilesAtPaths("vite.config.ts")}addSourceFile(e){this.project.addSourceFilesAtPaths(e)}requireSourceFile(e){return this.project.getSourceFileOrThrow(e)}async format(){await F.animate("Formatting modified files",(async()=>{const e=D.exists("prettier.config.js"),t=D.exists(".eslintrc.js");await Promise.all(a(this.modifiedFiles).map((async i=>{e&&await N.run(`npx prettier ${i} --write`),t&&await N.run(`npx eslint ${i} --fix`)})))}))}async save(e){await e.save(),this.modifiedFiles.add(e.getFilePath())}}class T{constructor(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t(this,"name",void 0),t(this,"options",void 0),this.name=e,this.options=i}create(e){!D.exists(e)||D.isDirectory(e)&&D.isEmptyDirectory(e)||F.fail(`Folder at '${e}' already exists!`),I.instantiate(P("templates/app"),e,{app:{name:this.name,slug:o(this.name)},dependencies:this.getDependencies(),contentPath:this.options.linkedLocal?`${O("core")}/dist/**/*.js`:"./node_modules/@aerogel/core/dist/**/*.js"})}edit(){return new L}getDependencies(){const e=e=>Object.entries(e).reduce(((e,t)=>{let[i,s]=t;return Object.assign(e,{[i]:`file:${s}`})}),{});return this.options.linkedLocal?e({aerogelCli:O("cli"),aerogelCore:O("core"),aerogelCypress:O("cypress"),aerogelPluginI18n:O("plugin-i18n"),aerogelPluginSoukai:O("plugin-soukai"),aerogelVite:O("vite")}):this.options.local?e({aerogelCli:E("cli")??b("cli"),aerogelCore:E("core")??b("core"),aerogelCypress:E("cypress")??b("cypress"),aerogelPluginI18n:E("plugin-i18n")??b("plugin-i18n"),aerogelPluginSoukai:E("plugin-soukai")??b("plugin-soukai"),aerogelVite:E("vite")??b("vite")}):{aerogelCli:"next",aerogelCore:"next",aerogelCypress:"next",aerogelPluginI18n:"next",aerogelPluginSoukai:"next",aerogelVite:"next"}}}class z{static define(e){var t=this;e=e.command(this.command).description(this.description);for(const[t,i]of this.parameters)e=e.argument(`<${t}>`,i);for(const[t,i]of Object.entries(this.options)){const s="string"==typeof i?i:i.description,n="string"==typeof i?"string":i.type??"string";e=e.option("boolean"===n?`--${t}`:`--${t} <${n}>`,s)}e=e.action((function(){for(var e=arguments.length,i=new Array(e),s=0;s<e;s++)i[s]=arguments[s];return t.run.call(t,...i)}))}static async run(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const s=new this(...t);await s.run()}async run(){}assertAerogelOrDirectory(e){const t=D.read("package.json");if(t?.includes("@aerogel/core"))return;if(e&&D.isDirectory(e))return;const i=e?`${e} folder does not exist.`:"package.json does not contain @aerogel/core.";F.fail(`${i} Are you sure this is an Aerogel app?`)}}t(z,"command",""),t(z,"description",""),t(z,"parameters",[]),t(z,"options",{});class B extends z{constructor(e,i){super(),t(this,"path",void 0),t(this,"options",void 0),this.path=e,this.options=i}async run(){const e=this.path,t=this.options.name??"Aerogel App";N.setWorkingDirectory(e),await this.createApp(t,e),await this.installDependencies(),await this.initializeGit(),F.success(`\n\n That's it! You can start working on **${t}** doing the following:\n\n cd ${e}\n npm run dev\n\n Have fun!\n `)}async createApp(e,t){F.info(`Creating **${e}**...`),new T(e,{local:this.options.local,linkedLocal:this.options.local&&!this.options.copy}).create(t)}async installDependencies(){await F.animate("Installing dependencies",(async()=>{await N.run("npm install")}))}async initializeGit(){await F.animate("Initializing git",(async()=>{await N.run("git init"),await N.run("git add ."),await N.run('git commit -m "Start"')}))}}function M(){return new T("")}function q(){return D.isSymlink("node_modules/@aerogel/core")}function _(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e)return;const i=t.guard??(()=>!0),s=t.validate??(()=>!0),n=a(t.skip??[]);return e.forEachDescendant(((e,t)=>{if(i(e)&&s(e))return e;const r=e.getKind();n.includes(r)&&t.skip()}))}function J(e,t){if(e&&t(e))return e}t(B,"command","create"),t(B,"description","Create AerogelJS app"),t(B,"parameters",[["path","Application path"]]),t(B,"options",{name:"Application name",local:{type:"boolean",description:"Whether to create an app using local Aerogel packages (used for core development)"},copy:{type:"boolean",description:"Whether to create an app linked to local Aerogel packages (used in CI)"}});class W extends z{constructor(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),t(this,"path",void 0),t(this,"options",void 0),this.path=e,this.options=i}async run(){this.assertAerogelOrDirectory("src/components"),this.assertHistoireInstalled();const e=new Set,[t,i]=this.parsePathComponents();await this.createComponent(t,i,e),await this.createStory(i,e),await this.declareComponents();const s=a(e).map((e=>`- ${e}`)).join("\n");F.info(`${i} component created successfully! The following files were created:\n\n${s}`)}assertHistoireInstalled(){this.options.story&&(D.exists("src/main.histoire.ts")||F.fail("Histoire is not installed yet!"))}async createComponent(e,t,i){await F.animate("Creating component",(async()=>{D.exists(`src/components/${this.path}.vue`)&&F.fail(`${this.path} component already exists!`);I.instantiate(P("templates/component"),`src/components/${e}`,{component:{name:t}}).forEach((e=>i.add(e)))}))}async createStory(e,t){this.options.story&&await F.animate("Creating story",(async()=>{I.instantiate(P("templates/component-story"),"src/components",{component:{name:e}}).forEach((e=>t.add(e)))}))}async declareComponents(){const e=M().edit(),t=e.requireSourceFile("vite.config.ts"),i=this.getComponentDirsArray(t);if(!i)return F.fail("Could not find component dirs declaration in vite config!");i.getDescendantsOfKind(S.StringLiteral).some((e=>"'src/components'"===e.getText()))||(await F.animate("Updating vite config",(async()=>{i.addElement("'src/components'"),await e.save(t)})),await e.format())}getComponentDirsArray(e){const t=_(e,{guard:C.isCallExpression,validate:e=>e.getText().startsWith("Components("),skip:S.ImportDeclaration});if(!t)return null;const i=_(t,{guard:C.isPropertyAssignment,validate:e=>"dirs"===e.getName()}),s=i?.getInitializer();return C.isArrayLiteralExpression(s)?s:this.declareComponentDirsArray(t)}declareComponentDirsArray(e){const t=_(e,{guard:C.isObjectLiteralExpression}),i=t?.addPropertyAssignment({name:"dirs",initializer:"[]"});return i?.getInitializer()??null}parsePathComponents(){const e=this.path.lastIndexOf("/");return-1===e?["",this.path]:[this.path.substring(0,e),this.path.substring(e+1)]}}function G(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=e.split("\n"),s=t.indent??0;let n=0,r="";for(const e of i){const t=e.trim(),i=0===t.length;if(0===r.length){if(i)continue;n=e.indexOf(t[0]??""),r+=`${" ".repeat(s)}${t}\n`;continue}if(i){r+="\n";continue}const a=e.indexOf(t[0]??"");r+=`${" ".repeat(s+a-n)}${t}\n`}return r.trimEnd()}t(W,"command","generate:component"),t(W,"description","Generate an AerogelJS Component"),t(W,"parameters",[["path","Component path (relative to components folder; extension not necessary)"]]),t(W,"options",{story:{description:"Create component story using Histoire",type:"boolean"}});class H extends z{constructor(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),t(this,"name",void 0),t(this,"options",void 0),this.name=e,this.options=i}async run(){this.assertAerogelOrDirectory("src/models"),D.exists(`src/models/${this.name}.ts`)&&F.fail(`${this.name} model already exists!`),this.assertSoukaiInstalled();const e=await F.animate("Creating model",(async()=>I.instantiate(P("templates/model"),"src/models",{model:{name:this.name,fieldsDefinition:this.getFieldsDefinition()},soukaiImports:this.options.fields?"FieldType, defineModelSchema":"defineModelSchema"}).map((e=>`- ${e}`)).join("\n")));F.info(`${this.name} model created successfully! The following files were created:\n\n${e}`)}getFieldsDefinition(){if(!this.options.fields)return" //";const e=this.options.fields.split(",").map((e=>{const[t,i,s]=e.split(":");return{name:t,type:l(i??"string"),required:"required"===s}})).reduce(((e,t)=>e+`\n${t.required?G(`\n ${t.name}: {\n type: FieldType.${t.type},\n required: true,\n }\n `):`${t.name}: FieldType.${t.type}`},`),"");return G(e,{indent:8})}assertSoukaiInstalled(){D.contains("package.json",'"soukai"')||D.contains("package.json",'"@aerogel/plugin-soukai"')||F.fail("\n Soukai is not installed yet! You can install it running:\n npx ag install soukai\n ")}}t(H,"command","generate:model"),t(H,"description","Generate an AerogelJS Model"),t(H,"parameters",[["name","Model name"]]),t(H,"options",{fields:"Create model with the given fields"});class R extends z{constructor(e){super(),t(this,"name",void 0),this.name=e}async run(){this.assertAerogelOrDirectory("src/services");const e=new Set,t=M().edit();await this.createService(e),await this.registerService(t),await t.format();const i=a(e).map((e=>`- ${e}`)).join("\n");F.info(`${this.name} service created successfully! The following files were created:\n\n${i}`)}async createService(e){await F.animate("Creating service",(async()=>{D.exists(`src/services/${this.name}.ts`)&&F.fail(`${this.name} service already exists!`);I.instantiate(P("templates/service"),"src/services",{service:{name:this.name}}).forEach((t=>e.add(t)))}))}async registerService(e){await F.animate("Registering service",(async()=>{D.exists("src/services/index.ts")||await this.createServicesIndex(e);const t=e.requireSourceFile("src/services/index.ts"),i=this.getServicesObject(t);if(!i)return F.fail("Could not find services object in services config, please add it manually.");t.addImportDeclaration({defaultImport:this.name,moduleSpecifier:`./${this.name}`}),i.addPropertyAssignment({name:`$${c(this.name)}`,initializer:this.name}),await e.save(t)}))}async createServicesIndex(e){D.write("src/services/index.ts",G("\n export const services = {};\n\n export type AppServices = typeof services;\n\n declare module '@vue/runtime-core' {\n interface ComponentCustomProperties extends AppServices {}\n }\n ")),e.addSourceFile("src/services/index.ts");const t=e.requireSourceFile("src/main.ts"),i=this.getBootstrapOptions(t);if(!i)return F.fail("Could not find options object in bootstrap config, please add the services manually.");i.insertShorthandPropertyAssignment(0,{name:"services"}),t.addImportDeclaration({namedImports:["services"],moduleSpecifier:"./services"}),await e.save(t)}getBootstrapOptions(e){const t=_(e,{guard:C.isCallExpression,validate:e=>"bootstrapApplication"===e.getExpression().getText(),skip:S.ImportDeclaration}),i=t?.getArguments()[1];return C.isObjectLiteralExpression(i)?i:null}getServicesObject(e){const t=_(e,{guard:C.isVariableDeclaration,validate:e=>"services"===e.getName()}),i=t?.getInitializer();return C.isObjectLiteralExpression(i)?i:null}}t(R,"command","generate:service"),t(R,"description","Generate an AerogelJS Service"),t(R,"parameters",[["name","Service name"]]);class V{constructor(e){t(this,"name",void 0),this.name=e}async install(){this.assertNotInstalled(),await this.installDependencies();{const e=M().edit();await this.updateFiles(e),await e.format()}F.info(`Plugin ${this.name} installed!`)}assertNotInstalled(){D.contains("package.json",`"${this.getNpmPackageName()}"`)&&F.fail(`${this.name} is already installed!`)}async installDependencies(){await F.animate("Installing plugin dependencies",(async()=>{await this.installNpmDependencies()}))}async updateFiles(e){await this.updateBootstrapConfig(e)}async installNpmDependencies(){if(q())await N.run(`npm install file:${O(this.getLocalPackageName())}`);else if(D.contains("package.json","file")){const e=E(this.getLocalPackageName())??b(this.getLocalPackageName());await N.run(`npm install file:${e}`)}else await N.run(`npm install ${this.getNpmPackageName()}@next`)}async updateBootstrapConfig(e){await F.animate("Injecting plugin in bootstrap configuration",(async()=>{const t=e.requireSourceFile("src/main.ts"),i=this.getBootstrapPluginsDeclaration(t);if(!i)return F.fail(`\n Could not find plugins array in bootstrap config, please add the following manually:\n\n ${this.getBootstrapConfig()}\n `);t.addImportDeclaration(this.getBootstrapImport()),i.addElement(this.getBootstrapConfig()),await e.save(t)}))}getBootstrapPluginsDeclaration(e){const t=_(e,{guard:C.isCallExpression,validate:e=>"bootstrapApplication"===e.getExpression().getText(),skip:S.ImportDeclaration}),i=t?.getArguments()[1],s=J(i,C.isObjectLiteralExpression)?.getProperty("plugins"),n=J(s,C.isPropertyAssignment)?.getInitializer();return C.isArrayLiteralExpression(n)?n:null}getBootstrapImport(){return{defaultImport:this.name,moduleSpecifier:`@aerogel/plugin-${this.name}`}}getNpmPackageName(){return`@aerogel/${this.getLocalPackageName()}`}getLocalPackageName(){return`plugin-${this.name}`}getBootstrapConfig(){return`${this.name}()`}}const K=[new class extends V{constructor(){super("soukai")}async installNpmDependencies(){await N.run("npm install soukai@next"),await super.installNpmDependencies()}getBootstrapConfig(){return"soukai({ models: import.meta.glob('@/models/*', { eager: true }) })"}},new class extends V{constructor(){super("solid")}async updateFiles(e){await this.updateTailwindConfig(e),await super.updateFiles(e)}async installNpmDependencies(){await N.run("npm install soukai-solid@next"),await super.installNpmDependencies()}async updateTailwindConfig(e){await F.animate("Updating tailwind configuration",(async()=>{const t=e.requireSourceFile("tailwind.config.js"),i=this.getTailwindContentArray(t),s=q()?`'${O("plugin-solid")}/dist/**/*.js'`:"'./node_modules/@aerogel/plugin-solid/dist/**/*.js'";if(!i)return F.fail(`\n Could not find content array in tailwind config, please add the following manually:\n\n ${s}\n `);i.addElement(s),await e.save(t)}))}getTailwindContentArray(e){const t=_(e,{guard:C.isPropertyAssignment,validate:e=>"content"===e.getName(),skip:S.JSDoc}),i=t?.getInitializer();return C.isArrayLiteralExpression(i)?i:null}}].reduce(((e,t)=>Object.assign(e,{[t.name]:t})),{});class U extends z{constructor(e){super(),t(this,"plugin",void 0),this.plugin=K[e]??F.fail(`Plugin '${e}' doesn't exist. Available plugins: ${Object.keys(K).join(", ")}`)}async run(){await this.plugin.install()}}t(U,"command","install"),t(U,"description","Install an AerogelJS plugin"),t(U,"parameters",[["plugin","Plugin to install"]]);var Y=i(new class{run(t){const i=new e;i.name("ag").description("AerogelJS CLI").version("0.0.0"),B.define(i),W.define(i),H.define(i),R.define(i),U.define(i),i.parse(t)}});export{Y as CLI};
2
2
  //# sourceMappingURL=aerogel-cli.esm.js.map
@@ -1,4 +1,14 @@
1
1
  /** @type {import('@noeldemartin/scripts').Config} */
2
2
  module.exports = {
3
- external: ['fs', '@noeldemartin/utils', 'chalk', 'child_process', 'commander', 'mustache', 'path', 'readline'],
3
+ external: [
4
+ '@noeldemartin/utils',
5
+ 'chalk',
6
+ 'child_process',
7
+ 'commander',
8
+ 'fs',
9
+ 'mustache',
10
+ 'path',
11
+ 'readline',
12
+ 'ts-morph',
13
+ ],
4
14
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aerogel/cli",
3
3
  "description": "Aerogel CLI",
4
- "version": "0.0.0-next.59bf5f7cc06e728d0cf6c00de28f1da48d7d6b8e",
4
+ "version": "0.0.0-next.b85327579d32f21c6a9fa21142f0165cdd320d7e",
5
5
  "main": "dist/aerogel-cli.cjs.js",
6
6
  "module": "dist/aerogel-cli.esm.js",
7
7
  "types": "dist/aerogel-cli.d.ts",
@@ -38,7 +38,8 @@
38
38
  "@noeldemartin/utils": "0.4.0-next.ac00beaecf32bb02ed8e335225d7948d946d73bd",
39
39
  "chalk": "^4.1.2",
40
40
  "commander": "^11.0.0",
41
- "mustache": "^4.2.0"
41
+ "mustache": "^4.2.0",
42
+ "ts-morph": "^20.0.0"
42
43
  },
43
44
  "devDependencies": {
44
45
  "@types/node": "^20.4.0"
package/src/cli.ts CHANGED
@@ -3,6 +3,8 @@ import { CreateCommand } from '@/commands/create';
3
3
  import { facade } from '@noeldemartin/utils';
4
4
  import { GenerateComponentCommand } from '@/commands/generate-component';
5
5
  import { GenerateModelCommand } from '@/commands/generate-model';
6
+ import { GenerateServiceCommand } from '@/commands/generate-service';
7
+ import { InstallCommand } from '@/commands/install';
6
8
 
7
9
  export class CLIService {
8
10
 
@@ -14,6 +16,8 @@ export class CLIService {
14
16
  CreateCommand.define(program);
15
17
  GenerateComponentCommand.define(program);
16
18
  GenerateModelCommand.define(program);
19
+ GenerateServiceCommand.define(program);
20
+ InstallCommand.define(program);
17
21
 
18
22
  program.parse(argv);
19
23
  }
@@ -16,9 +16,8 @@ describe('Create command', () => {
16
16
  FileMock.expectCreated('./app/package.json').toContain('"name": "my-app"');
17
17
  FileMock.expectCreated('./app/package.json').toContain('"@aerogel/core": "next"');
18
18
  FileMock.expectCreated('./app/index.html').toContain('My App');
19
- FileMock.expectCreated('./app/src/App.vue').toContain(
20
- '<h1 class="text-4xl font-semibold">{{ $t(\'home.title\') }}</h1>',
21
- );
19
+ FileMock.expectCreated('./app/src/App.vue').toContain('<h1 class="text-4xl font-semibold">');
20
+ FileMock.expectCreated('./app/src/App.vue').toContain('{{ $t(\'home.title\') }}');
22
21
 
23
22
  ShellMock.expectRan('npm install');
24
23
  ShellMock.expectRan('git init');
@@ -7,6 +7,7 @@ import type { CommandOptions } from '@/commands/Command';
7
7
  export interface Options {
8
8
  name?: string;
9
9
  local?: boolean;
10
+ copy?: boolean;
10
11
  }
11
12
 
12
13
  export class CreateCommand extends Command {
@@ -18,7 +19,11 @@ export class CreateCommand extends Command {
18
19
  name: 'Application name',
19
20
  local: {
20
21
  type: 'boolean',
21
- description: 'Whether to create an app linked to local Aerogel packages (used for core development)',
22
+ description: 'Whether to create an app using local Aerogel packages (used for core development)',
23
+ },
24
+ copy: {
25
+ type: 'boolean',
26
+ description: 'Whether to create an app linked to local Aerogel packages (used in CI)',
22
27
  },
23
28
  };
24
29
 
@@ -56,7 +61,10 @@ export class CreateCommand extends Command {
56
61
  protected async createApp(name: string, path: string): Promise<void> {
57
62
  Log.info(`Creating **${name}**...`);
58
63
 
59
- new App(name, { local: this.options.local }).create(path);
64
+ new App(name, {
65
+ local: this.options.local,
66
+ linkedLocal: this.options.local && !this.options.copy,
67
+ }).create(path);
60
68
  }
61
69
 
62
70
  protected async installDependencies(): Promise<void> {
@@ -4,7 +4,7 @@ import FileMock from '@/lib/File.mock';
4
4
 
5
5
  import { GenerateComponentCommand } from './generate-component';
6
6
 
7
- describe('Generate component command', () => {
7
+ describe('Generate Component command', () => {
8
8
 
9
9
  it('generates components', async () => {
10
10
  // Arrange
@@ -1,8 +1,14 @@
1
+ import { arrayFrom } from '@noeldemartin/utils';
2
+ import { Node, SyntaxKind } from 'ts-morph';
3
+ import type { ArrayLiteralExpression, CallExpression, SourceFile } from 'ts-morph';
4
+
1
5
  import Command from '@/commands/Command';
2
6
  import File from '@/lib/File';
3
7
  import Log from '@/lib/Log';
4
8
  import Template from '@/lib/Template';
5
- import { basePath } from '@/lib/utils';
9
+ import { app } from '@/lib/utils/app';
10
+ import { editFiles, findDescendant } from '@/lib/utils/edit';
11
+ import { basePath } from '@/lib/utils/paths';
6
12
  import type { CommandOptions } from '@/commands/Command';
7
13
 
8
14
  export interface Options {
@@ -12,7 +18,7 @@ export interface Options {
12
18
  export class GenerateComponentCommand extends Command {
13
19
 
14
20
  public static command: string = 'generate:component';
15
- public static description: string = 'Generate an AerogelJS component';
21
+ public static description: string = 'Generate an AerogelJS Component';
16
22
  public static parameters: [string, string][] = [
17
23
  ['path', 'Component path (relative to components folder; extension not necessary)'],
18
24
  ];
@@ -36,34 +42,125 @@ export class GenerateComponentCommand extends Command {
36
42
 
37
43
  public async run(): Promise<void> {
38
44
  this.assertAerogelOrDirectory('src/components');
39
- this.options.story && this.assertHistoireInstalled();
45
+ this.assertHistoireInstalled();
46
+
47
+ const files = new Set<string>();
48
+ const [directoryName, componentName] = this.parsePathComponents();
49
+
50
+ await this.createComponent(directoryName, componentName, files);
51
+ await this.createStory(componentName, files);
52
+ await this.declareComponents();
53
+
54
+ const filesList = arrayFrom(files)
55
+ .map((file) => `- ${file}`)
56
+ .join('\n');
57
+
58
+ Log.info(`${componentName} component created successfully! The following files were created:\n\n${filesList}`);
59
+ }
40
60
 
41
- if (File.exists(`src/components/${this.path}.vue`)) {
42
- Log.fail(`${this.path} component already exists!`);
61
+ protected assertHistoireInstalled(): void {
62
+ if (!this.options.story) {
63
+ return;
43
64
  }
44
65
 
45
- const [directoryName, componentName] = this.parsePathComponents();
46
- const files = Template.instantiate(basePath('templates/component'), `src/components/${directoryName}`, {
47
- component: { name: componentName },
66
+ if (!File.exists('src/main.histoire.ts')) {
67
+ Log.fail('Histoire is not installed yet!');
68
+ }
69
+ }
70
+
71
+ protected async createComponent(directoryName: string, componentName: string, files: Set<string>): Promise<void> {
72
+ await Log.animate('Creating component', async () => {
73
+ if (File.exists(`src/components/${this.path}.vue`)) {
74
+ Log.fail(`${this.path} component already exists!`);
75
+ }
76
+
77
+ const componentFiles = Template.instantiate(
78
+ basePath('templates/component'),
79
+ `src/components/${directoryName}`,
80
+ { component: { name: componentName } },
81
+ );
82
+
83
+ componentFiles.forEach((file) => files.add(file));
48
84
  });
85
+ }
49
86
 
50
- if (this.options.story) {
87
+ protected async createStory(componentName: string, files: Set<string>): Promise<void> {
88
+ if (!this.options.story) {
89
+ return;
90
+ }
91
+
92
+ await Log.animate('Creating story', async () => {
51
93
  const storyFiles = Template.instantiate(basePath('templates/component-story'), 'src/components', {
52
94
  component: { name: componentName },
53
95
  });
54
96
 
55
- files.push(...storyFiles);
97
+ storyFiles.forEach((file) => files.add(file));
98
+ });
99
+ }
100
+
101
+ protected async declareComponents(): Promise<void> {
102
+ if (!editFiles()) {
103
+ return;
56
104
  }
57
105
 
58
- const filesList = files.map((file) => `- ${file}`).join('\n');
106
+ const editor = app().edit();
107
+ const viteConfig = editor.requireSourceFile('vite.config.ts');
108
+ const componentDirsArray = this.getComponentDirsArray(viteConfig);
59
109
 
60
- Log.info(`${componentName} component created successfully! The following files were created:\n\n${filesList}`);
110
+ if (!componentDirsArray) {
111
+ return Log.fail('Could not find component dirs declaration in vite config!');
112
+ }
113
+
114
+ if (
115
+ componentDirsArray
116
+ .getDescendantsOfKind(SyntaxKind.StringLiteral)
117
+ .some((literal) => literal.getText() === '\'src/components\'')
118
+ ) {
119
+ return;
120
+ }
121
+
122
+ await Log.animate('Updating vite config', async () => {
123
+ componentDirsArray.addElement('\'src/components\'');
124
+
125
+ await editor.save(viteConfig);
126
+ });
127
+
128
+ await editor.format();
61
129
  }
62
130
 
63
- protected assertHistoireInstalled(): void {
64
- if (!File.exists('src/main.histoire.ts')) {
65
- Log.fail('Histoire is not installed yet!');
131
+ protected getComponentDirsArray(viteConfig: SourceFile): ArrayLiteralExpression | null {
132
+ const pluginCall = findDescendant(viteConfig, {
133
+ guard: Node.isCallExpression,
134
+ validate: (callExpression) => callExpression.getText().startsWith('Components('),
135
+ skip: SyntaxKind.ImportDeclaration,
136
+ });
137
+
138
+ if (!pluginCall) {
139
+ return null;
140
+ }
141
+
142
+ const dirsAssignment = findDescendant(pluginCall, {
143
+ guard: Node.isPropertyAssignment,
144
+ validate: (propertyAssignment) => propertyAssignment.getName() === 'dirs',
145
+ });
146
+
147
+ const dirsArray = dirsAssignment?.getInitializer();
148
+
149
+ if (!Node.isArrayLiteralExpression(dirsArray)) {
150
+ return this.declareComponentDirsArray(pluginCall);
66
151
  }
152
+
153
+ return dirsArray;
154
+ }
155
+
156
+ protected declareComponentDirsArray(pluginCall: CallExpression): ArrayLiteralExpression | null {
157
+ const pluginOptions = findDescendant(pluginCall, { guard: Node.isObjectLiteralExpression });
158
+ const dirsAssignment = pluginOptions?.addPropertyAssignment({
159
+ name: 'dirs',
160
+ initializer: '[]',
161
+ });
162
+
163
+ return (dirsAssignment?.getInitializer() as ArrayLiteralExpression) ?? null;
67
164
  }
68
165
 
69
166
  protected parsePathComponents(): [string, string] {
@@ -1,11 +1,11 @@
1
1
  import { describe, it } from 'vitest';
2
2
 
3
3
  import FileMock from '@/lib/File.mock';
4
- import { formatCodeBlock } from '@/lib/utils';
4
+ import { formatCodeBlock } from '@/lib/utils/format';
5
5
 
6
6
  import { GenerateModelCommand } from './generate-model';
7
7
 
8
- describe('Generate model command', () => {
8
+ describe('Generate Model command', () => {
9
9
 
10
10
  it('generates models', async () => {
11
11
  // Arrange
@@ -4,7 +4,8 @@ import Command from '@/commands/Command';
4
4
  import File from '@/lib/File';
5
5
  import Log from '@/lib/Log';
6
6
  import Template from '@/lib/Template';
7
- import { basePath, formatCodeBlock } from '@/lib/utils';
7
+ import { basePath } from '@/lib/utils/paths';
8
+ import { formatCodeBlock } from '@/lib/utils/format';
8
9
  import type { CommandOptions } from '@/commands/Command';
9
10
 
10
11
  interface Options {
@@ -14,7 +15,7 @@ interface Options {
14
15
  export class GenerateModelCommand extends Command {
15
16
 
16
17
  public static command: string = 'generate:model';
17
- public static description: string = 'Generate an AerogelJS model';
18
+ public static description: string = 'Generate an AerogelJS Model';
18
19
  public static parameters: [string, string][] = [['name', 'Model name']];
19
20
  public static options: CommandOptions = {
20
21
  fields: 'Create model with the given fields',
@@ -39,15 +40,17 @@ export class GenerateModelCommand extends Command {
39
40
 
40
41
  this.assertSoukaiInstalled();
41
42
 
42
- const files = Template.instantiate(basePath('templates/model'), 'src/models', {
43
- model: {
44
- name: this.name,
45
- fieldsDefinition: this.getFieldsDefinition(),
46
- },
47
- soukaiImports: this.options.fields ? 'FieldType, defineModelSchema' : 'defineModelSchema',
48
- });
43
+ const filesList = await Log.animate('Creating model', async () => {
44
+ const files = Template.instantiate(basePath('templates/model'), 'src/models', {
45
+ model: {
46
+ name: this.name,
47
+ fieldsDefinition: this.getFieldsDefinition(),
48
+ },
49
+ soukaiImports: this.options.fields ? 'FieldType, defineModelSchema' : 'defineModelSchema',
50
+ });
49
51
 
50
- const filesList = files.map((file) => `- ${file}`).join('\n');
52
+ return files.map((file) => `- ${file}`).join('\n');
53
+ });
51
54
 
52
55
  Log.info(`${this.name} model created successfully! The following files were created:\n\n${filesList}`);
53
56
  }
@@ -87,13 +90,8 @@ export class GenerateModelCommand extends Command {
87
90
  protected assertSoukaiInstalled(): void {
88
91
  if (!File.contains('package.json', '"soukai"') && !File.contains('package.json', '"@aerogel/plugin-soukai"')) {
89
92
  Log.fail(`
90
- Soukai is not installed yet! You can install it doing the following:
91
-
92
- 1. Run the following command:
93
- npm install soukai @aerogel/plugin-soukai@next
94
-
95
- 2. Add this to your plugins array in src/main.ts:
96
- soukai({ models: import.meta.glob('@/models/*', { eager: true }) })
93
+ Soukai is not installed yet! You can install it running:
94
+ npx ag install soukai
97
95
  `);
98
96
  }
99
97
  }
@@ -0,0 +1,21 @@
1
+ import { describe, it } from 'vitest';
2
+
3
+ import FileMock from '@/lib/File.mock';
4
+
5
+ import { GenerateServiceCommand } from './generate-service';
6
+
7
+ describe('Generate Service command', () => {
8
+
9
+ it('generates services', async () => {
10
+ // Arrange
11
+ FileMock.stub('package.json', '@aerogel/core');
12
+
13
+ // Act
14
+ await GenerateServiceCommand.run('FooBar');
15
+
16
+ // Assert
17
+ FileMock.expectCreated('src/services/FooBar.ts').toContain('class FooBarService extends Service');
18
+ FileMock.expectCreated('src/services/FooBar.ts').toContain('export default facade(new FooBarService());');
19
+ });
20
+
21
+ });