@aerogel/cli 0.0.0-next.0be1479064cfd43fb6eafa2552cb7f8775554d93

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 (74) hide show
  1. package/.eslintrc.js +7 -0
  2. package/bin/ag +4 -0
  3. package/dist/aerogel-cli.cjs.js +2 -0
  4. package/dist/aerogel-cli.cjs.js.map +1 -0
  5. package/dist/aerogel-cli.d.ts +10 -0
  6. package/dist/aerogel-cli.esm.js +2 -0
  7. package/dist/aerogel-cli.esm.js.map +1 -0
  8. package/noeldemartin.config.js +14 -0
  9. package/package.json +47 -0
  10. package/src/cli.ts +27 -0
  11. package/src/commands/Command.ts +59 -0
  12. package/src/commands/create.test.ts +34 -0
  13. package/src/commands/create.ts +84 -0
  14. package/src/commands/generate-component.test.ts +44 -0
  15. package/src/commands/generate-component.ts +174 -0
  16. package/src/commands/generate-model.test.ts +45 -0
  17. package/src/commands/generate-model.ts +99 -0
  18. package/src/commands/generate-service.test.ts +21 -0
  19. package/src/commands/generate-service.ts +152 -0
  20. package/src/commands/install.test.ts +18 -0
  21. package/src/commands/install.ts +32 -0
  22. package/src/lib/App.ts +87 -0
  23. package/src/lib/Editor.ts +51 -0
  24. package/src/lib/File.mock.ts +66 -0
  25. package/src/lib/File.ts +76 -0
  26. package/src/lib/Log.mock.ts +37 -0
  27. package/src/lib/Log.test.ts +37 -0
  28. package/src/lib/Log.ts +95 -0
  29. package/src/lib/Shell.mock.ts +20 -0
  30. package/src/lib/Shell.ts +28 -0
  31. package/src/lib/Template.ts +56 -0
  32. package/src/lib/utils/app.ts +15 -0
  33. package/src/lib/utils/edit.ts +44 -0
  34. package/src/lib/utils/format.test.ts +33 -0
  35. package/src/lib/utils/format.ts +38 -0
  36. package/src/lib/utils/paths.ts +34 -0
  37. package/src/main.ts +3 -0
  38. package/src/plugins/Plugin.ts +125 -0
  39. package/src/plugins/Solid.ts +65 -0
  40. package/src/plugins/Soukai.ts +19 -0
  41. package/src/testing/setup.ts +74 -0
  42. package/src/types/ts-reset.d.ts +1 -0
  43. package/templates/app/.eslintrc.js +3 -0
  44. package/templates/app/.github/workflows/ci.yml +17 -0
  45. package/templates/app/.gitignore.template +2 -0
  46. package/templates/app/.nvmrc +1 -0
  47. package/templates/app/.vscode/launch.json +16 -0
  48. package/templates/app/.vscode/settings.json +10 -0
  49. package/templates/app/cypress/e2e/app.cy.ts +9 -0
  50. package/templates/app/cypress/support/e2e.ts +3 -0
  51. package/templates/app/cypress/tsconfig.json +12 -0
  52. package/templates/app/cypress.config.ts +12 -0
  53. package/templates/app/index.html +12 -0
  54. package/templates/app/package.json +54 -0
  55. package/templates/app/postcss.config.js +6 -0
  56. package/templates/app/prettier.config.js +5 -0
  57. package/templates/app/src/App.vue +12 -0
  58. package/templates/app/src/assets/styles.css +3 -0
  59. package/templates/app/src/lang/en.yaml +3 -0
  60. package/templates/app/src/main.test.ts +9 -0
  61. package/templates/app/src/main.ts +13 -0
  62. package/templates/app/src/types/globals.d.ts +2 -0
  63. package/templates/app/src/types/shims.d.ts +7 -0
  64. package/templates/app/src/types/ts-reset.d.ts +1 -0
  65. package/templates/app/tailwind.config.js +5 -0
  66. package/templates/app/tsconfig.json +18 -0
  67. package/templates/app/vite.config.ts +23 -0
  68. package/templates/component/[component.name].vue +3 -0
  69. package/templates/component-story/[component.name].story.vue +7 -0
  70. package/templates/model/[model.name].schema.ts +7 -0
  71. package/templates/model/[model.name].ts +3 -0
  72. package/templates/service/[service.name].ts +8 -0
  73. package/tsconfig.json +11 -0
  74. package/vite.config.ts +14 -0
package/.eslintrc.js ADDED
@@ -0,0 +1,7 @@
1
+ module.exports = {
2
+ env: {
3
+ browser: true,
4
+ es2021: true,
5
+ },
6
+ extends: ['@noeldemartin/eslint-config-typescript'],
7
+ };
package/bin/ag ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ const { CLI } = require('../dist/aerogel-cli.cjs.js');
3
+
4
+ CLI.run();
@@ -0,0 +1,2 @@
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 h(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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return n.resolve(__dirname,"../",e)}function y(e){return m.fail(`Could not find ${e} pack file, did you run 'npm pack'?`)}function v(e){return p.getFiles(w(e)).find((e=>e.endsWith(".tgz")))??null}function w(e){return f(`../${e}`)}var x=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 j{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 x.run(`npx prettier ${i} --write`),t&&await x.run(`npx eslint ${i} --fix`)})))}))}async save(e){await e.save(),this.modifiedFiles.add(e.getFilePath())}}class S{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(h("templates/app"),e,{app:{name:this.name,slug:i.stringToSlug(this.name)},dependencies:this.getDependencies(),contentPath:this.options.linkedLocal?`${w("core")}/dist/**/*.js`:"./node_modules/@aerogel/core/dist/**/*.js"})}edit(){return new j}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:w("cli"),aerogelCore:w("core"),aerogelCypress:w("cypress"),aerogelPluginI18n:w("plugin-i18n"),aerogelPluginSoukai:w("plugin-soukai"),aerogelVite:w("vite")}):this.options.local?e({aerogelCli:v("cli")??y("cli"),aerogelCore:v("core")??y("core"),aerogelCypress:v("cypress")??y("cypress"),aerogelPluginI18n:v("plugin-i18n")??y("plugin-i18n"),aerogelPluginSoukai:v("plugin-soukai")??y("plugin-soukai"),aerogelVite:v("vite")??y("vite")}):{aerogelCli:"next",aerogelCore:"next",aerogelCypress:"next",aerogelPluginI18n:"next",aerogelPluginSoukai:"next",aerogelVite:"next"}}}class k{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(k,"command",""),u.default(k,"description",""),u.default(k,"parameters",[]),u.default(k,"options",{});class $ extends k{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";x.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 S(e,{local:this.options.local,linkedLocal:this.options.local&&!this.options.copy}).create(t)}async installDependencies(){await m.animate("Installing dependencies",(async()=>{await x.run("npm install")}))}async initializeGit(){await m.animate("Initializing git",(async()=>{await x.run("git init"),await x.run("git add ."),await x.run('git commit -m "Start"')}))}}function C(){return new S("")}function A(){return p.isSymlink("node_modules/@aerogel/core")}function F(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 q(e,t){if(e&&t(e))return e}u.default($,"command","create"),u.default($,"description","Create AerogelJS app"),u.default($,"parameters",[["path","Application path"]]),u.default($,"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 D extends k{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=C().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=F(e,{guard:l.Node.isCallExpression,validate:e=>e.getText().startsWith("Components("),skip:l.SyntaxKind.ImportDeclaration});if(!t)return null;const i=F(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=F(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 I(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(D,"command","generate:component"),u.default(D,"description","Generate an AerogelJS Component"),u.default(D,"parameters",[["path","Component path (relative to components folder; extension not necessary)"]]),u.default(D,"options",{story:{description:"Create component story using Histoire",type:"boolean"}});class P extends k{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?I(`\n ${t.name}: {\n type: FieldType.${t.type},\n required: true,\n }\n `):`${t.name}: FieldType.${t.type}`},`),"");return I(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(P,"command","generate:model"),u.default(P,"description","Generate an AerogelJS Model"),u.default(P,"parameters",[["name","Model name"]]),u.default(P,"options",{fields:"Create model with the given fields"});class b extends k{constructor(e){super(),u.default(this,"name",void 0),this.name=e}async run(){this.assertAerogelOrDirectory("src/services");const e=new Set,t=C().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",I("\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=F(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=F(e,{guard:l.Node.isVariableDeclaration,validate:e=>"services"===e.getName()}),i=t?.getInitializer();return l.Node.isObjectLiteralExpression(i)?i:null}}u.default(b,"command","generate:service"),u.default(b,"description","Generate an AerogelJS Service"),u.default(b,"parameters",[["name","Service name"]]);class N{constructor(e){u.default(this,"name",void 0),this.name=e}async install(){this.assertNotInstalled(),await this.installDependencies();{const e=C().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(A())await x.run(`npm install file:${w(this.getLocalPackageName())}`);else if(p.contains("package.json","file")){const e=v(this.getLocalPackageName())??y(this.getLocalPackageName());await x.run(`npm install file:${e}`)}else await x.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=F(e,{guard:l.Node.isCallExpression,validate:e=>"bootstrapApplication"===e.getExpression().getText(),skip:l.SyntaxKind.ImportDeclaration}),i=t?.getArguments()[1],s=q(i,l.Node.isObjectLiteralExpression)?.getProperty("plugins"),n=q(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 O=[new class extends N{constructor(){super("soukai")}async installNpmDependencies(){await x.run("npm install soukai@next"),await super.installNpmDependencies()}getBootstrapConfig(){return"soukai({ models: import.meta.glob('@/models/*', { eager: true }) })"}},new class extends N{constructor(){super("solid")}async updateFiles(e){await this.updateTailwindConfig(e),await super.updateFiles(e)}async installNpmDependencies(){await x.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=A()?`'${w("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=F(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 E extends k{constructor(e){super(),u.default(this,"plugin",void 0),this.plugin=O[e]??m.fail(`Plugin '${e}' doesn't exist. Available plugins: ${Object.keys(O).join(", ")}`)}async run(){await this.plugin.install()}}u.default(E,"command","install"),u.default(E,"description","Install an AerogelJS plugin"),u.default(E,"parameters",[["plugin","Plugin to install"]]);var L=i.facade(new class{run(t){const i=new e.Command;i.name("ag").description("AerogelJS CLI").version("0.0.0"),$.define(i),D.define(i),P.define(i),b.define(i),E.define(i),i.parse(t)}});exports.CLI=L;
2
+ //# sourceMappingURL=aerogel-cli.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aerogel-cli.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,10 @@
1
+ import { Constructor } from '@noeldemartin/utils';
2
+ import { Facade } from '@noeldemartin/utils';
3
+
4
+ export declare const CLI: Facade<CLIService, Constructor<CLIService>>;
5
+
6
+ declare class CLIService {
7
+ run(argv?: string[]): void;
8
+ }
9
+
10
+ export { }
@@ -0,0 +1,2 @@
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 b(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(){return f(__dirname,"../",arguments.length>0&&void 0!==arguments[0]?arguments[0]:"")}function E(e){return F.fail(`Could not find ${e} pack file, did you run 'npm pack'?`)}function O(e){return D.getFiles(N(e)).find((e=>e.endsWith(".tgz")))??null}function N(e){return P(`../${e}`)}var L=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 T{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 L.run(`npx prettier ${i} --write`),t&&await L.run(`npx eslint ${i} --fix`)})))}))}async save(e){await e.save(),this.modifiedFiles.add(e.getFilePath())}}class z{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(b("templates/app"),e,{app:{name:this.name,slug:o(this.name)},dependencies:this.getDependencies(),contentPath:this.options.linkedLocal?`${N("core")}/dist/**/*.js`:"./node_modules/@aerogel/core/dist/**/*.js"})}edit(){return new T}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:N("cli"),aerogelCore:N("core"),aerogelCypress:N("cypress"),aerogelPluginI18n:N("plugin-i18n"),aerogelPluginSoukai:N("plugin-soukai"),aerogelVite:N("vite")}):this.options.local?e({aerogelCli:O("cli")??E("cli"),aerogelCore:O("core")??E("core"),aerogelCypress:O("cypress")??E("cypress"),aerogelPluginI18n:O("plugin-i18n")??E("plugin-i18n"),aerogelPluginSoukai:O("plugin-soukai")??E("plugin-soukai"),aerogelVite:O("vite")??E("vite")}):{aerogelCli:"next",aerogelCore:"next",aerogelCypress:"next",aerogelPluginI18n:"next",aerogelPluginSoukai:"next",aerogelVite:"next"}}}class B{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(B,"command",""),t(B,"description",""),t(B,"parameters",[]),t(B,"options",{});class M extends B{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";L.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 z(e,{local:this.options.local,linkedLocal:this.options.local&&!this.options.copy}).create(t)}async installDependencies(){await F.animate("Installing dependencies",(async()=>{await L.run("npm install")}))}async initializeGit(){await F.animate("Initializing git",(async()=>{await L.run("git init"),await L.run("git add ."),await L.run('git commit -m "Start"')}))}}function q(){return new z("")}function _(){return D.isSymlink("node_modules/@aerogel/core")}function J(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 W(e,t){if(e&&t(e))return e}t(M,"command","create"),t(M,"description","Create AerogelJS app"),t(M,"parameters",[["path","Application path"]]),t(M,"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 G extends B{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=q().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=J(e,{guard:C.isCallExpression,validate:e=>e.getText().startsWith("Components("),skip:S.ImportDeclaration});if(!t)return null;const i=J(t,{guard:C.isPropertyAssignment,validate:e=>"dirs"===e.getName()}),s=i?.getInitializer();return C.isArrayLiteralExpression(s)?s:this.declareComponentDirsArray(t)}declareComponentDirsArray(e){const t=J(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 H(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(G,"command","generate:component"),t(G,"description","Generate an AerogelJS Component"),t(G,"parameters",[["path","Component path (relative to components folder; extension not necessary)"]]),t(G,"options",{story:{description:"Create component story using Histoire",type:"boolean"}});class R extends B{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?H(`\n ${t.name}: {\n type: FieldType.${t.type},\n required: true,\n }\n `):`${t.name}: FieldType.${t.type}`},`),"");return H(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(R,"command","generate:model"),t(R,"description","Generate an AerogelJS Model"),t(R,"parameters",[["name","Model name"]]),t(R,"options",{fields:"Create model with the given fields"});class V extends B{constructor(e){super(),t(this,"name",void 0),this.name=e}async run(){this.assertAerogelOrDirectory("src/services");const e=new Set,t=q().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",H("\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=J(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=J(e,{guard:C.isVariableDeclaration,validate:e=>"services"===e.getName()}),i=t?.getInitializer();return C.isObjectLiteralExpression(i)?i:null}}t(V,"command","generate:service"),t(V,"description","Generate an AerogelJS Service"),t(V,"parameters",[["name","Service name"]]);class K{constructor(e){t(this,"name",void 0),this.name=e}async install(){this.assertNotInstalled(),await this.installDependencies();{const e=q().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(_())await L.run(`npm install file:${N(this.getLocalPackageName())}`);else if(D.contains("package.json","file")){const e=O(this.getLocalPackageName())??E(this.getLocalPackageName());await L.run(`npm install file:${e}`)}else await L.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=J(e,{guard:C.isCallExpression,validate:e=>"bootstrapApplication"===e.getExpression().getText(),skip:S.ImportDeclaration}),i=t?.getArguments()[1],s=W(i,C.isObjectLiteralExpression)?.getProperty("plugins"),n=W(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 U=[new class extends K{constructor(){super("soukai")}async installNpmDependencies(){await L.run("npm install soukai@next"),await super.installNpmDependencies()}getBootstrapConfig(){return"soukai({ models: import.meta.glob('@/models/*', { eager: true }) })"}},new class extends K{constructor(){super("solid")}async updateFiles(e){await this.updateTailwindConfig(e),await super.updateFiles(e)}async installNpmDependencies(){await L.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=_()?`'${N("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=J(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 Y extends B{constructor(e){super(),t(this,"plugin",void 0),this.plugin=U[e]??F.fail(`Plugin '${e}' doesn't exist. Available plugins: ${Object.keys(U).join(", ")}`)}async run(){await this.plugin.install()}}t(Y,"command","install"),t(Y,"description","Install an AerogelJS plugin"),t(Y,"parameters",[["plugin","Plugin to install"]]);var Q=i(new class{run(t){const i=new e;i.name("ag").description("AerogelJS CLI").version("0.0.0"),M.define(i),G.define(i),R.define(i),V.define(i),Y.define(i),i.parse(t)}});export{Q as CLI};
2
+ //# sourceMappingURL=aerogel-cli.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aerogel-cli.esm.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,14 @@
1
+ /** @type {import('@noeldemartin/scripts').Config} */
2
+ module.exports = {
3
+ external: [
4
+ '@noeldemartin/utils',
5
+ 'chalk',
6
+ 'child_process',
7
+ 'commander',
8
+ 'fs',
9
+ 'mustache',
10
+ 'path',
11
+ 'readline',
12
+ 'ts-morph',
13
+ ],
14
+ };
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@aerogel/cli",
3
+ "description": "Aerogel CLI",
4
+ "version": "0.0.0-next.0be1479064cfd43fb6eafa2552cb7f8775554d93",
5
+ "main": "dist/aerogel-cli.cjs.js",
6
+ "module": "dist/aerogel-cli.esm.js",
7
+ "types": "dist/aerogel-cli.d.ts",
8
+ "sideEffects": false,
9
+ "bin": {
10
+ "ag": "bin/ag"
11
+ },
12
+ "scripts": {
13
+ "build": "rm dist -rf && npm run build:js && npm run build:types",
14
+ "build:js": "noeldemartin-build-javascript",
15
+ "build:types": "noeldemartin-build-types",
16
+ "lint": "noeldemartin-lint src",
17
+ "publish-next": "noeldemartin-publish-next",
18
+ "test": "vitest --run"
19
+ },
20
+ "engines": {
21
+ "node": ">=18.x"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/NoelDeMartin/aerogeljs.git"
26
+ },
27
+ "keywords": [
28
+ "javascript",
29
+ "aerogel",
30
+ "cli"
31
+ ],
32
+ "author": "Noel De Martin",
33
+ "license": "MIT",
34
+ "bugs": {
35
+ "url": "https://github.com/NoelDeMartin/aerogeljs/issues"
36
+ },
37
+ "dependencies": {
38
+ "@noeldemartin/utils": "0.4.0-next.ac00beaecf32bb02ed8e335225d7948d946d73bd",
39
+ "chalk": "^4.1.2",
40
+ "commander": "^11.0.0",
41
+ "mustache": "^4.2.0",
42
+ "ts-morph": "^20.0.0"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "^20.4.0"
46
+ }
47
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { Command } from 'commander';
2
+ import { CreateCommand } from '@/commands/create';
3
+ import { facade } from '@noeldemartin/utils';
4
+ import { GenerateComponentCommand } from '@/commands/generate-component';
5
+ import { GenerateModelCommand } from '@/commands/generate-model';
6
+ import { GenerateServiceCommand } from '@/commands/generate-service';
7
+ import { InstallCommand } from '@/commands/install';
8
+
9
+ export class CLIService {
10
+
11
+ public run(argv?: string[]): void {
12
+ const program = new Command();
13
+
14
+ program.name('ag').description('AerogelJS CLI').version('0.0.0');
15
+
16
+ CreateCommand.define(program);
17
+ GenerateComponentCommand.define(program);
18
+ GenerateModelCommand.define(program);
19
+ GenerateServiceCommand.define(program);
20
+ InstallCommand.define(program);
21
+
22
+ program.parse(argv);
23
+ }
24
+
25
+ }
26
+
27
+ export default facade(new CLIService());
@@ -0,0 +1,59 @@
1
+ import File from '@/lib/File';
2
+ import Log from '@/lib/Log';
3
+ import type { Constructor } from '@noeldemartin/utils';
4
+ import type { Command as CommanderCommand } from 'commander';
5
+
6
+ export type CommandConstructor<T extends Command = Command> = Constructor<T>;
7
+ export type CommandOptions = Record<string, string | { description: string; type?: string }>;
8
+
9
+ export default class Command {
10
+
11
+ public static command: string = '';
12
+ public static description: string = '';
13
+ public static parameters: [string, string][] = [];
14
+ public static options: CommandOptions = {};
15
+
16
+ public static define(program: CommanderCommand): void {
17
+ program = program.command(this.command).description(this.description);
18
+
19
+ for (const [name, description] of this.parameters) {
20
+ program = program.argument(`<${name}>`, description);
21
+ }
22
+
23
+ for (const [name, definition] of Object.entries(this.options)) {
24
+ const description = typeof definition === 'string' ? definition : definition.description;
25
+ const type = typeof definition === 'string' ? 'string' : definition.type ?? 'string';
26
+
27
+ program = program.option(type === 'boolean' ? `--${name}` : `--${name} <${type}>`, description);
28
+ }
29
+
30
+ program = program.action((...args) => this.run.call(this, ...args));
31
+ }
32
+
33
+ public static async run<T extends CommandConstructor>(this: T, ...args: ConstructorParameters<T>): Promise<void> {
34
+ const instance = new this(...args);
35
+
36
+ await instance.run();
37
+ }
38
+
39
+ public async run(): Promise<void> {
40
+ //
41
+ }
42
+
43
+ protected assertAerogelOrDirectory(path?: string): void {
44
+ const packageJson = File.read('package.json');
45
+
46
+ if (packageJson?.includes('@aerogel/core')) {
47
+ return;
48
+ }
49
+
50
+ if (path && File.isDirectory(path)) {
51
+ return;
52
+ }
53
+
54
+ const message = path ? `${path} folder does not exist.` : 'package.json does not contain @aerogel/core.';
55
+
56
+ Log.fail(`${message} Are you sure this is an Aerogel app?`);
57
+ }
58
+
59
+ }
@@ -0,0 +1,34 @@
1
+ import { describe, it } from 'vitest';
2
+
3
+ import FileMock from '@/lib/File.mock';
4
+ import ShellMock from '@/lib/Shell.mock';
5
+
6
+ import { CreateCommand } from './create';
7
+
8
+ describe('Create command', () => {
9
+
10
+ it('creates apps', async () => {
11
+ // Act
12
+ await CreateCommand.run('./app', { name: 'My App' });
13
+
14
+ // Assert
15
+ FileMock.expectCreated('./app/.gitignore').toContain('node_modules');
16
+ FileMock.expectCreated('./app/package.json').toContain('"name": "my-app"');
17
+ FileMock.expectCreated('./app/package.json').toContain('"@aerogel/core": "next"');
18
+ FileMock.expectCreated('./app/index.html').toContain('My App');
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\') }}');
21
+
22
+ ShellMock.expectRan('npm install');
23
+ ShellMock.expectRan('git init');
24
+ });
25
+
26
+ it('creates apps for local core development', async () => {
27
+ // Act
28
+ await CreateCommand.run('./app', { name: 'My App', local: true });
29
+
30
+ // Assert
31
+ FileMock.expectCreated('./app/package.json').toMatch(/"@aerogel\/core": "file:[^"]+\/packages\/core"/);
32
+ });
33
+
34
+ });
@@ -0,0 +1,84 @@
1
+ import App from '@/lib/App';
2
+ import Command from '@/commands/Command';
3
+ import Log from '@/lib/Log';
4
+ import Shell from '@/lib/Shell';
5
+ import type { CommandOptions } from '@/commands/Command';
6
+
7
+ export interface Options {
8
+ name?: string;
9
+ local?: boolean;
10
+ copy?: boolean;
11
+ }
12
+
13
+ export class CreateCommand extends Command {
14
+
15
+ public static command: string = 'create';
16
+ public static description: string = 'Create AerogelJS app';
17
+ public static parameters: [string, string][] = [['path', 'Application path']];
18
+ public static options: CommandOptions = {
19
+ name: 'Application name',
20
+ local: {
21
+ type: 'boolean',
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)',
27
+ },
28
+ };
29
+
30
+ private path: string;
31
+ private options: Options;
32
+
33
+ constructor(path: string, options: Options) {
34
+ super();
35
+
36
+ this.path = path;
37
+ this.options = options;
38
+ }
39
+
40
+ public async run(): Promise<void> {
41
+ const path = this.path;
42
+ const name = this.options.name ?? 'Aerogel App';
43
+
44
+ Shell.setWorkingDirectory(path);
45
+
46
+ await this.createApp(name, path);
47
+ await this.installDependencies();
48
+ await this.initializeGit();
49
+
50
+ Log.success(`
51
+
52
+ That's it! You can start working on **${name}** doing the following:
53
+
54
+ cd ${path}
55
+ npm run dev
56
+
57
+ Have fun!
58
+ `);
59
+ }
60
+
61
+ protected async createApp(name: string, path: string): Promise<void> {
62
+ Log.info(`Creating **${name}**...`);
63
+
64
+ new App(name, {
65
+ local: this.options.local,
66
+ linkedLocal: this.options.local && !this.options.copy,
67
+ }).create(path);
68
+ }
69
+
70
+ protected async installDependencies(): Promise<void> {
71
+ await Log.animate('Installing dependencies', async () => {
72
+ await Shell.run('npm install');
73
+ });
74
+ }
75
+
76
+ protected async initializeGit(): Promise<void> {
77
+ await Log.animate('Initializing git', async () => {
78
+ await Shell.run('git init');
79
+ await Shell.run('git add .');
80
+ await Shell.run('git commit -m "Start"');
81
+ });
82
+ }
83
+
84
+ }
@@ -0,0 +1,44 @@
1
+ import { describe, it } from 'vitest';
2
+
3
+ import FileMock from '@/lib/File.mock';
4
+
5
+ import { GenerateComponentCommand } from './generate-component';
6
+
7
+ describe('Generate Component command', () => {
8
+
9
+ it('generates components', async () => {
10
+ // Arrange
11
+ FileMock.stub('package.json', '@aerogel/core');
12
+
13
+ // Act
14
+ await GenerateComponentCommand.run('FooBar');
15
+
16
+ // Assert
17
+ FileMock.expectCreated('src/components/FooBar.vue').toContain('<div>FooBar</div>');
18
+ });
19
+
20
+ it('generates components in subfolders', async () => {
21
+ // Arrange
22
+ FileMock.stub('package.json', '@aerogel/core');
23
+
24
+ // Act
25
+ await GenerateComponentCommand.run('module/FooBar');
26
+
27
+ // Assert
28
+ FileMock.expectCreated('src/components/module/FooBar.vue').toContain('<div>FooBar</div>');
29
+ });
30
+
31
+ it('generates components with stories', async () => {
32
+ // Arrange
33
+ FileMock.stub('package.json', '@aerogel/core');
34
+ FileMock.stub('src/main.histoire.ts');
35
+
36
+ // Act
37
+ await GenerateComponentCommand.run('FooBar', { story: true });
38
+
39
+ // Assert
40
+ FileMock.expectCreated('src/components/FooBar.vue').toContain('<div>FooBar</div>');
41
+ FileMock.expectCreated('src/components/FooBar.story.vue').toContain('<FooBar />');
42
+ });
43
+
44
+ });
@@ -0,0 +1,174 @@
1
+ import { arrayFrom } from '@noeldemartin/utils';
2
+ import { Node, SyntaxKind } from 'ts-morph';
3
+ import type { ArrayLiteralExpression, CallExpression, SourceFile } from 'ts-morph';
4
+
5
+ import Command from '@/commands/Command';
6
+ import File from '@/lib/File';
7
+ import Log from '@/lib/Log';
8
+ import Template from '@/lib/Template';
9
+ import { app } from '@/lib/utils/app';
10
+ import { editFiles, findDescendant } from '@/lib/utils/edit';
11
+ import { basePath } from '@/lib/utils/paths';
12
+ import type { CommandOptions } from '@/commands/Command';
13
+
14
+ export interface Options {
15
+ story?: boolean;
16
+ }
17
+
18
+ export class GenerateComponentCommand extends Command {
19
+
20
+ public static command: string = 'generate:component';
21
+ public static description: string = 'Generate an AerogelJS Component';
22
+ public static parameters: [string, string][] = [
23
+ ['path', 'Component path (relative to components folder; extension not necessary)'],
24
+ ];
25
+
26
+ public static options: CommandOptions = {
27
+ story: {
28
+ description: 'Create component story using Histoire',
29
+ type: 'boolean',
30
+ },
31
+ };
32
+
33
+ private path: string;
34
+ private options: Options;
35
+
36
+ constructor(path: string, options: Options = {}) {
37
+ super();
38
+
39
+ this.path = path;
40
+ this.options = options;
41
+ }
42
+
43
+ public async run(): Promise<void> {
44
+ this.assertAerogelOrDirectory('src/components');
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
+ }
60
+
61
+ protected assertHistoireInstalled(): void {
62
+ if (!this.options.story) {
63
+ return;
64
+ }
65
+
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));
84
+ });
85
+ }
86
+
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 () => {
93
+ const storyFiles = Template.instantiate(basePath('templates/component-story'), 'src/components', {
94
+ component: { name: componentName },
95
+ });
96
+
97
+ storyFiles.forEach((file) => files.add(file));
98
+ });
99
+ }
100
+
101
+ protected async declareComponents(): Promise<void> {
102
+ if (!editFiles()) {
103
+ return;
104
+ }
105
+
106
+ const editor = app().edit();
107
+ const viteConfig = editor.requireSourceFile('vite.config.ts');
108
+ const componentDirsArray = this.getComponentDirsArray(viteConfig);
109
+
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();
129
+ }
130
+
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);
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;
164
+ }
165
+
166
+ protected parsePathComponents(): [string, string] {
167
+ const lastSlashIndex = this.path.lastIndexOf('/');
168
+
169
+ return lastSlashIndex === -1
170
+ ? ['', this.path]
171
+ : [this.path.substring(0, lastSlashIndex), this.path.substring(lastSlashIndex + 1)];
172
+ }
173
+
174
+ }