@aerogel/cli 0.0.0-next.47ed8ee3c048720794026e45140e9b700cb428b9 → 0.0.0-next.4b4da752b2ea1e9ee76a4d33a1e616bf87478f69

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 (84) hide show
  1. package/bin/gel +4 -0
  2. package/dist/aerogel-cli.d.ts +2 -2
  3. package/dist/aerogel-cli.js +833 -0
  4. package/dist/aerogel-cli.js.map +1 -0
  5. package/package.json +27 -33
  6. package/src/cli.ts +30 -6
  7. package/src/commands/Command.ts +14 -9
  8. package/src/commands/create.test.ts +24 -7
  9. package/src/commands/create.ts +38 -20
  10. package/src/commands/generate-component.test.ts +62 -4
  11. package/src/commands/generate-component.ts +181 -28
  12. package/src/commands/generate-model.test.ts +8 -5
  13. package/src/commands/generate-model.ts +41 -24
  14. package/src/commands/generate-overrides.ts +85 -0
  15. package/src/commands/generate-service.test.ts +21 -0
  16. package/src/commands/generate-service.ts +151 -0
  17. package/src/commands/info.ts +15 -0
  18. package/src/commands/install.test.ts +27 -0
  19. package/src/commands/install.ts +32 -0
  20. package/src/lib/App.ts +71 -6
  21. package/src/lib/Editor.ts +57 -0
  22. package/src/lib/File.mock.ts +7 -11
  23. package/src/lib/File.ts +9 -3
  24. package/src/lib/Log.mock.ts +11 -6
  25. package/src/lib/Log.test.ts +22 -6
  26. package/src/lib/Log.ts +43 -27
  27. package/src/lib/Shell.mock.ts +3 -3
  28. package/src/lib/Shell.ts +2 -2
  29. package/src/lib/Template.ts +24 -17
  30. package/src/lib/utils/app.ts +15 -0
  31. package/src/lib/utils/edit.ts +44 -0
  32. package/src/lib/utils/paths.ts +42 -0
  33. package/src/plugins/Plugin.ts +159 -0
  34. package/src/plugins/Solid.ts +71 -0
  35. package/src/plugins/Soukai.ts +19 -0
  36. package/src/testing/setup.ts +56 -25
  37. package/templates/app/.github/workflows/ci.yml +16 -4
  38. package/templates/app/.nvmrc +1 -1
  39. package/templates/app/.vscode/launch.json +17 -0
  40. package/templates/app/.vscode/settings.json +10 -0
  41. package/templates/app/README.md +3 -0
  42. package/templates/app/cypress/cypress.config.ts +14 -0
  43. package/templates/app/cypress/support/e2e.ts +1 -3
  44. package/templates/app/cypress/tsconfig.json +7 -8
  45. package/templates/app/index.html +5 -4
  46. package/templates/app/package.json +44 -21
  47. package/templates/app/src/App.vue +5 -3
  48. package/templates/app/src/assets/css/main.css +4 -0
  49. package/templates/app/src/assets/public/robots.txt +2 -0
  50. package/templates/app/src/main.ts +8 -4
  51. package/templates/app/src/types/globals.d.ts +0 -1
  52. package/templates/app/tsconfig.json +3 -9
  53. package/templates/app/vite.config.ts +18 -8
  54. package/templates/component-button/[component.name].vue +42 -0
  55. package/templates/component-button-story/[component.name].story.vue +77 -0
  56. package/templates/component-checkbox/[component.name].vue +34 -0
  57. package/templates/component-checkbox-story/[component.name].story.vue +63 -0
  58. package/templates/component-input/[component.name].vue +17 -0
  59. package/templates/component-input-story/[component.name].story.vue +63 -0
  60. package/templates/overrides/components/index.ts +15 -0
  61. package/templates/overrides/components/overrides/AlertModal.vue +11 -0
  62. package/templates/overrides/components/overrides/ConfirmModal.vue +20 -0
  63. package/templates/overrides/components/overrides/ErrorReportModal.vue +35 -0
  64. package/templates/overrides/components/overrides/LoadingModal.vue +12 -0
  65. package/templates/overrides/components/overrides/ModalWrapper.vue +22 -0
  66. package/templates/overrides/components/overrides/SnackbarNotification.vue +34 -0
  67. package/templates/overrides-story/Overrides.story.vue +86 -0
  68. package/templates/service/[service.name].ts +8 -0
  69. package/.eslintrc.js +0 -7
  70. package/bin/ag +0 -4
  71. package/dist/aerogel-cli.cjs.js +0 -2
  72. package/dist/aerogel-cli.cjs.js.map +0 -1
  73. package/dist/aerogel-cli.esm.js +0 -2
  74. package/dist/aerogel-cli.esm.js.map +0 -1
  75. package/noeldemartin.config.js +0 -4
  76. package/src/lib/utils.test.ts +0 -33
  77. package/src/lib/utils.ts +0 -44
  78. package/templates/app/cypress.config.ts +0 -8
  79. package/templates/app/postcss.config.js +0 -6
  80. package/templates/app/src/assets/styles.css +0 -3
  81. package/templates/app/tailwind.config.js +0 -5
  82. package/tsconfig.json +0 -11
  83. package/vite.config.ts +0 -14
  84. /package/src/{main.ts → index.ts} +0 -0
@@ -1,65 +1,218 @@
1
- import Command from '@/commands/Command';
2
- import File from '@/lib/File';
3
- import Log from '@/lib/Log';
4
- import Template from '@/lib/Template';
5
- import { basePath } from '@/lib/utils';
6
- import type { CommandOptions } from '@/commands/Command';
1
+ import { arrayFilter, arrayFrom, stringToSlug } from '@noeldemartin/utils';
2
+ import { Node, SyntaxKind } from 'ts-morph';
3
+ import type { ArrayLiteralExpression, CallExpression, SourceFile } from 'ts-morph';
4
+
5
+ import Command from '@aerogel/cli/commands/Command';
6
+ import File from '@aerogel/cli/lib/File';
7
+ import Log from '@aerogel/cli/lib/Log';
8
+ import Template from '@aerogel/cli/lib/Template';
9
+ import { app } from '@aerogel/cli/lib/utils/app';
10
+ import { editFiles, findDescendant } from '@aerogel/cli/lib/utils/edit';
11
+ import { templatePath } from '@aerogel/cli/lib/utils/paths';
12
+ import type { CommandOptions } from '@aerogel/cli/commands/Command';
7
13
 
8
14
  export interface Options {
15
+ button?: boolean;
16
+ checkbox?: boolean;
17
+ input?: boolean;
9
18
  story?: boolean;
10
19
  }
11
20
 
12
21
  export class GenerateComponentCommand extends Command {
13
22
 
14
- public static command: string = 'generate:component';
15
- public static description: string = 'Generate an AerogelJS component';
16
- public static parameters: [string, string][] = [['name', 'Component name']];
17
- public static options: CommandOptions = {
23
+ protected static override command: string = 'generate:component';
24
+ protected static override description: string = 'Generate an AerogelJS Component';
25
+ protected static override parameters: [string, string][] = [
26
+ ['path', 'Component path (relative to components folder; extension not necessary)'],
27
+ ];
28
+
29
+ protected static override options: CommandOptions = {
30
+ button: {
31
+ description: 'Create a custom button',
32
+ type: 'boolean',
33
+ },
34
+ checkbox: {
35
+ description: 'Create a custom checkbox',
36
+ type: 'boolean',
37
+ },
38
+ input: {
39
+ description: 'Create a custom input',
40
+ type: 'boolean',
41
+ },
18
42
  story: {
19
43
  description: 'Create component story using Histoire',
20
44
  type: 'boolean',
21
45
  },
22
46
  };
23
47
 
24
- private name: string;
48
+ private path: string;
25
49
  private options: Options;
26
50
 
27
- constructor(name: string, options: Options = {}) {
51
+ constructor(path: string, options: Options = {}) {
28
52
  super();
29
53
 
30
- this.name = name;
54
+ this.path = path;
31
55
  this.options = options;
32
56
  }
33
57
 
34
- public async run(): Promise<void> {
58
+ protected override async validate(): Promise<void> {
59
+ const components = arrayFilter([this.options.button, this.options.input, this.options.checkbox]).length;
60
+
61
+ if (components > 1) {
62
+ Log.fail('Can only use one of \'button\', \'input\', or \'checkbox\' flags!');
63
+ }
64
+ }
65
+
66
+ protected override async run(): Promise<void> {
35
67
  this.assertAerogelOrDirectory('src/components');
36
- this.options.story && this.assertHistoireInstalled();
68
+ this.assertHistoireInstalled();
69
+
70
+ const files = new Set<string>();
71
+ const [directoryName, componentName] = this.parsePathComponents();
72
+
73
+ await this.createComponent(directoryName, componentName, files);
74
+ await this.createStory(directoryName, componentName, files);
75
+ await this.declareComponents();
37
76
 
38
- if (File.exists(`src/components/${this.name}.vue`)) {
39
- Log.fail(`${this.name} component already exists!`);
77
+ const filesList = arrayFrom(files)
78
+ .map((file) => `- ${file}`)
79
+ .join('\n');
80
+
81
+ Log.info(`${componentName} component created successfully! The following files were created:\n\n${filesList}`);
82
+ }
83
+
84
+ protected assertHistoireInstalled(): void {
85
+ if (!this.options.story) {
86
+ return;
40
87
  }
41
88
 
42
- const files = Template.instantiate(basePath('templates/component'), 'src/components', {
43
- component: { name: this.name },
89
+ if (!File.contains('package.json', '"histoire"') && !File.contains('package.json', '"@aerogel/histoire"')) {
90
+ Log.fail(`
91
+ Histoire is not installed yet! You can install it running:
92
+ npx gel install histoire
93
+ `);
94
+ }
95
+ }
96
+
97
+ protected async createComponent(directoryName: string, componentName: string, files: Set<string>): Promise<void> {
98
+ await Log.animate('Creating component', async () => {
99
+ if (File.exists(`src/components/${this.path}.vue`)) {
100
+ Log.fail(`${this.path} component already exists!`);
101
+ }
102
+
103
+ const templateName = this.options.input
104
+ ? 'component-input'
105
+ : this.options.button
106
+ ? 'component-button'
107
+ : this.options.checkbox
108
+ ? 'component-checkbox'
109
+ : 'component';
110
+ const componentFiles = Template.instantiate(templatePath(templateName), `src/components/${directoryName}`, {
111
+ component: {
112
+ name: componentName,
113
+ slug: stringToSlug(componentName),
114
+ },
115
+ });
116
+
117
+ componentFiles.forEach((file) => files.add(file));
44
118
  });
119
+ }
120
+
121
+ protected async createStory(directoryName: string, componentName: string, files: Set<string>): Promise<void> {
122
+ if (!this.options.story) {
123
+ return;
124
+ }
45
125
 
46
- if (this.options.story) {
47
- const storyFiles = Template.instantiate(basePath('templates/component-story'), 'src/components', {
48
- component: { name: this.name },
126
+ await Log.animate('Creating story', async () => {
127
+ const templateName = this.options.input
128
+ ? 'component-input-story'
129
+ : this.options.button
130
+ ? 'component-button-story'
131
+ : this.options.checkbox
132
+ ? 'component-checkbox-story'
133
+ : 'component-story';
134
+ const storyFiles = Template.instantiate(templatePath(templateName), `src/components/${directoryName}`, {
135
+ component: {
136
+ name: componentName,
137
+ slug: stringToSlug(componentName),
138
+ },
49
139
  });
50
140
 
51
- files.push(...storyFiles);
141
+ storyFiles.forEach((file) => files.add(file));
142
+ });
143
+ }
144
+
145
+ protected async declareComponents(): Promise<void> {
146
+ if (!editFiles()) {
147
+ return;
52
148
  }
53
149
 
54
- const filesList = files.map((file) => `- ${file}`).join('\n');
150
+ const editor = app().edit();
151
+ const viteConfig = editor.requireSourceFile('vite.config.ts');
152
+ const componentDirsArray = this.getComponentDirsArray(viteConfig);
153
+
154
+ if (!componentDirsArray) {
155
+ return Log.fail('Could not find component dirs declaration in vite config!');
156
+ }
157
+
158
+ if (
159
+ componentDirsArray
160
+ .getDescendantsOfKind(SyntaxKind.StringLiteral)
161
+ .some((literal) => literal.getText() === '\'src/components\'')
162
+ ) {
163
+ return;
164
+ }
55
165
 
56
- Log.info(`${this.name} component created successfully! The following files were created:\n\n${filesList}`);
166
+ await Log.animate('Updating vite config', async () => {
167
+ componentDirsArray.addElement('\'src/components\'');
168
+
169
+ await editor.save(viteConfig);
170
+ });
171
+
172
+ await editor.format();
57
173
  }
58
174
 
59
- protected assertHistoireInstalled(): void {
60
- if (!File.exists('src/main.histoire.ts')) {
61
- Log.fail('Histoire is not installed yet!');
175
+ protected getComponentDirsArray(viteConfig: SourceFile): ArrayLiteralExpression | null {
176
+ const pluginCall = findDescendant(viteConfig, {
177
+ guard: Node.isCallExpression,
178
+ validate: (callExpression) => callExpression.getText().startsWith('Components('),
179
+ skip: SyntaxKind.ImportDeclaration,
180
+ });
181
+
182
+ if (!pluginCall) {
183
+ return null;
62
184
  }
185
+
186
+ const dirsAssignment = findDescendant(pluginCall, {
187
+ guard: Node.isPropertyAssignment,
188
+ validate: (propertyAssignment) => propertyAssignment.getName() === 'dirs',
189
+ });
190
+
191
+ const dirsArray = dirsAssignment?.getInitializer();
192
+
193
+ if (!Node.isArrayLiteralExpression(dirsArray)) {
194
+ return this.declareComponentDirsArray(pluginCall);
195
+ }
196
+
197
+ return dirsArray;
198
+ }
199
+
200
+ protected declareComponentDirsArray(pluginCall: CallExpression): ArrayLiteralExpression | null {
201
+ const pluginOptions = findDescendant(pluginCall, { guard: Node.isObjectLiteralExpression });
202
+ const dirsAssignment = pluginOptions?.addPropertyAssignment({
203
+ name: 'dirs',
204
+ initializer: '[]',
205
+ });
206
+
207
+ return (dirsAssignment?.getInitializer() as ArrayLiteralExpression) ?? null;
208
+ }
209
+
210
+ protected parsePathComponents(): [string, string] {
211
+ const lastSlashIndex = this.path.lastIndexOf('/');
212
+
213
+ return lastSlashIndex === -1
214
+ ? ['', this.path]
215
+ : [this.path.substring(0, lastSlashIndex), this.path.substring(lastSlashIndex + 1)];
63
216
  }
64
217
 
65
218
  }
@@ -1,11 +1,11 @@
1
1
  import { describe, it } from 'vitest';
2
+ import { formatCodeBlock } from '@noeldemartin/utils';
2
3
 
3
- import FileMock from '@/lib/File.mock';
4
- import { formatCodeBlock } from '@/lib/utils';
4
+ import FileMock from '@aerogel/cli/lib/File.mock';
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
@@ -21,7 +21,7 @@ describe('Generate model command', () => {
21
21
 
22
22
  // Act
23
23
  await GenerateModelCommand.run('FooBar', {
24
- fields: 'name:string,age:number,birth:Date',
24
+ fields: 'name:string:required,age:number,birth:Date',
25
25
  });
26
26
 
27
27
  // Assert
@@ -30,7 +30,10 @@ describe('Generate model command', () => {
30
30
  formatCodeBlock(`
31
31
  defineModelSchema({
32
32
  fields: {
33
- name: FieldType.String,
33
+ name: {
34
+ type: FieldType.String,
35
+ required: true,
36
+ },
34
37
  age: FieldType.Number,
35
38
  birth: FieldType.Date,
36
39
  },
@@ -1,11 +1,11 @@
1
- import { stringToStudlyCase } from '@noeldemartin/utils';
1
+ import { formatCodeBlock, stringToStudlyCase } from '@noeldemartin/utils';
2
2
 
3
- import Command from '@/commands/Command';
4
- import File from '@/lib/File';
5
- import Log from '@/lib/Log';
6
- import Template from '@/lib/Template';
7
- import { basePath, formatCodeBlock } from '@/lib/utils';
8
- import type { CommandOptions } from '@/commands/Command';
3
+ import Command from '@aerogel/cli/commands/Command';
4
+ import File from '@aerogel/cli/lib/File';
5
+ import Log from '@aerogel/cli/lib/Log';
6
+ import Template from '@aerogel/cli/lib/Template';
7
+ import { templatePath } from '@aerogel/cli/lib/utils/paths';
8
+ import type { CommandOptions } from '@aerogel/cli/commands/Command';
9
9
 
10
10
  interface Options {
11
11
  fields?: string;
@@ -13,10 +13,10 @@ interface Options {
13
13
 
14
14
  export class GenerateModelCommand extends Command {
15
15
 
16
- public static command: string = 'generate:model';
17
- public static description: string = 'Generate an AerogelJS model';
18
- public static parameters: [string, string][] = [['name', 'Model name']];
19
- public static options: CommandOptions = {
16
+ protected static override command: string = 'generate:model';
17
+ protected static override description: string = 'Generate an AerogelJS Model';
18
+ protected static override parameters: [string, string][] = [['name', 'Model name']];
19
+ protected static override options: CommandOptions = {
20
20
  fields: 'Create model with the given fields',
21
21
  };
22
22
 
@@ -30,7 +30,7 @@ export class GenerateModelCommand extends Command {
30
30
  this.options = options;
31
31
  }
32
32
 
33
- public async run(): Promise<void> {
33
+ protected override async run(): Promise<void> {
34
34
  this.assertAerogelOrDirectory('src/models');
35
35
 
36
36
  if (File.exists(`src/models/${this.name}.ts`)) {
@@ -39,15 +39,17 @@ export class GenerateModelCommand extends Command {
39
39
 
40
40
  this.assertSoukaiInstalled();
41
41
 
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
- });
42
+ const filesList = await Log.animate('Creating model', async () => {
43
+ const files = Template.instantiate(templatePath('model'), 'src/models', {
44
+ model: {
45
+ name: this.name,
46
+ fieldsDefinition: this.getFieldsDefinition(),
47
+ },
48
+ soukaiImports: this.options.fields ? 'FieldType, defineModelSchema' : 'defineModelSchema',
49
+ });
49
50
 
50
- const filesList = files.map((file) => `- ${file}`).join('\n');
51
+ return files.map((file) => `- ${file}`).join('\n');
52
+ });
51
53
 
52
54
  Log.info(`${this.name} model created successfully! The following files were created:\n\n${filesList}`);
53
55
  }
@@ -60,21 +62,36 @@ export class GenerateModelCommand extends Command {
60
62
  const code = this.options.fields
61
63
  .split(',')
62
64
  .map((field) => {
63
- const [name, type] = field.split(':');
65
+ const [name, type, rules] = field.split(':');
64
66
 
65
67
  return {
66
68
  name,
67
69
  type: stringToStudlyCase(type ?? 'string'),
70
+ required: rules === 'required',
68
71
  };
69
72
  })
70
- .reduce((definition, field) => definition + `\n${field.name}: FieldType.${field.type},`, '');
73
+ .reduce((definition, field) => {
74
+ const fieldDefinition = field.required
75
+ ? formatCodeBlock(`
76
+ ${field.name}: {
77
+ type: FieldType.${field.type},
78
+ required: true,
79
+ }
80
+ `)
81
+ : `${field.name}: FieldType.${field.type}`;
82
+
83
+ return definition + `\n${fieldDefinition},`;
84
+ }, '');
71
85
 
72
86
  return formatCodeBlock(code, { indent: 8 });
73
87
  }
74
88
 
75
89
  protected assertSoukaiInstalled(): void {
76
- if (!File.contains('package.json', '"soukai"')) {
77
- Log.fail('Soukai is not installed yet!');
90
+ if (!File.contains('package.json', '"soukai"') && !File.contains('package.json', '"@aerogel/plugin-soukai"')) {
91
+ Log.fail(`
92
+ Soukai is not installed yet! You can install it running:
93
+ npx gel install soukai
94
+ `);
78
95
  }
79
96
  }
80
97
 
@@ -0,0 +1,85 @@
1
+ import { arrayFrom } from '@noeldemartin/utils';
2
+
3
+ import Command from '@aerogel/cli/commands/Command';
4
+ import File from '@aerogel/cli/lib/File';
5
+ import Log from '@aerogel/cli/lib/Log';
6
+ import Template from '@aerogel/cli/lib/Template';
7
+ import { templatePath } from '@aerogel/cli/lib/utils/paths';
8
+ import type { CommandOptions } from '@aerogel/cli/commands/Command';
9
+
10
+ export interface Options {
11
+ story?: boolean;
12
+ }
13
+
14
+ export class GenerateOverridesCommand extends Command {
15
+
16
+ protected static override command: string = 'generate:overrides';
17
+ protected static override description: string = 'Generate AerogelJS component overrides';
18
+
19
+ protected static override options: CommandOptions = {
20
+ story: {
21
+ description: 'Create overrides story using Histoire',
22
+ type: 'boolean',
23
+ },
24
+ };
25
+
26
+ private options: Options;
27
+
28
+ constructor(options: Options = {}) {
29
+ super();
30
+
31
+ this.options = options;
32
+ }
33
+
34
+ protected override async run(): Promise<void> {
35
+ this.assertAerogelOrDirectory('src/components');
36
+ this.assertHistoireInstalled();
37
+
38
+ const files = new Set<string>();
39
+
40
+ await this.createComponents(files);
41
+ await this.createStory(files);
42
+
43
+ const filesList = arrayFrom(files)
44
+ .map((file) => `- ${file}`)
45
+ .join('\n');
46
+
47
+ Log.info(`Overrides created successfully! The following files were created:\n\n${filesList}`);
48
+ Log.info('\nRemember to declare your components in main.ts and main.histoire.ts!');
49
+ }
50
+
51
+ protected assertHistoireInstalled(): void {
52
+ if (!this.options.story) {
53
+ return;
54
+ }
55
+
56
+ if (!File.contains('package.json', '"histoire"') && !File.contains('package.json', '"@aerogel/histoire"')) {
57
+ Log.fail(`
58
+ Histoire is not installed yet! You can install it running:
59
+ npx gel install histoire
60
+ `);
61
+ }
62
+ }
63
+
64
+ protected async createComponents(files: Set<string>): Promise<void> {
65
+ await Log.animate('Creating components', async () => {
66
+ if (File.exists('src/components/ModalWrapper.vue')) {
67
+ Log.fail('ModalWrapper component already exists!');
68
+ }
69
+
70
+ Template.instantiate(templatePath('overrides'), 'src').forEach((file) => files.add(file));
71
+ });
72
+ }
73
+
74
+ protected async createStory(files: Set<string>): Promise<void> {
75
+ if (!this.options.story) {
76
+ return;
77
+ }
78
+
79
+ await Log.animate('Creating story', async () => {
80
+ Template.instantiate(templatePath('overrides-story'), 'src/components/overrides/').forEach((file) =>
81
+ files.add(file));
82
+ });
83
+ }
84
+
85
+ }
@@ -0,0 +1,21 @@
1
+ import { describe, it } from 'vitest';
2
+
3
+ import FileMock from '@aerogel/cli/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(FooBarService);');
19
+ });
20
+
21
+ });
@@ -0,0 +1,151 @@
1
+ import { arrayFrom, formatCodeBlock, stringToCamelCase } from '@noeldemartin/utils';
2
+ import { Node, SyntaxKind } from 'ts-morph';
3
+ import type { ObjectLiteralExpression, SourceFile } from 'ts-morph';
4
+
5
+ import Command from '@aerogel/cli/commands/Command';
6
+ import File from '@aerogel/cli/lib/File';
7
+ import Log from '@aerogel/cli/lib/Log';
8
+ import Template from '@aerogel/cli/lib/Template';
9
+ import { app } from '@aerogel/cli/lib/utils/app';
10
+ import { templatePath } from '@aerogel/cli/lib/utils/paths';
11
+ import { editFiles, findDescendant } from '@aerogel/cli/lib/utils/edit';
12
+ import type { Editor } from '@aerogel/cli/lib/Editor';
13
+
14
+ export class GenerateServiceCommand extends Command {
15
+
16
+ protected static override command: string = 'generate:service';
17
+ protected static override description: string = 'Generate an AerogelJS Service';
18
+ protected static override parameters: [string, string][] = [['name', 'Service name']];
19
+
20
+ private name: string;
21
+
22
+ constructor(name: string) {
23
+ super();
24
+
25
+ this.name = name;
26
+ }
27
+
28
+ protected override async run(): Promise<void> {
29
+ this.assertAerogelOrDirectory('src/services');
30
+
31
+ const files = new Set<string>();
32
+ const editor = app().edit();
33
+
34
+ await this.createService(files);
35
+
36
+ if (editFiles()) {
37
+ await this.registerService(editor);
38
+ await editor.format();
39
+ }
40
+
41
+ const filesList = arrayFrom(files)
42
+ .map((file) => `- ${file}`)
43
+ .join('\n');
44
+
45
+ Log.info(`${this.name} service created successfully! The following files were created:\n\n${filesList}`);
46
+ }
47
+
48
+ protected async createService(files: Set<string>): Promise<void> {
49
+ await Log.animate('Creating service', async () => {
50
+ if (File.exists(`src/services/${this.name}.ts`)) {
51
+ Log.fail(`${this.name} service already exists!`);
52
+ }
53
+
54
+ const serviceFiles = Template.instantiate(templatePath('service'), 'src/services', {
55
+ service: {
56
+ name: this.name,
57
+ },
58
+ });
59
+
60
+ serviceFiles.forEach((file) => files.add(file));
61
+ });
62
+ }
63
+
64
+ protected async registerService(editor: Editor): Promise<void> {
65
+ await Log.animate('Registering service', async () => {
66
+ if (!File.exists('src/services/index.ts')) {
67
+ await this.createServicesIndex(editor);
68
+ }
69
+
70
+ const servicesIndex = editor.requireSourceFile('src/services/index.ts');
71
+ const servicesObject = this.getServicesObject(servicesIndex);
72
+
73
+ if (!servicesObject) {
74
+ return Log.fail('Could not find services object in services config, please add it manually.');
75
+ }
76
+
77
+ servicesIndex.addImportDeclaration({
78
+ defaultImport: this.name,
79
+ moduleSpecifier: `./${this.name}`,
80
+ });
81
+ servicesObject.addPropertyAssignment({
82
+ name: `$${stringToCamelCase(this.name)}`,
83
+ initializer: this.name,
84
+ });
85
+
86
+ await editor.save(servicesIndex);
87
+ });
88
+ }
89
+
90
+ protected async createServicesIndex(editor: Editor): Promise<void> {
91
+ File.write(
92
+ 'src/services/index.ts',
93
+ formatCodeBlock(`
94
+ export const services = {};
95
+
96
+ export type AppServices = typeof services;
97
+
98
+ declare module '@aerogel/core' {
99
+ interface Services extends AppServices {}
100
+ }
101
+ `),
102
+ );
103
+
104
+ editor.addSourceFile('src/services/index.ts');
105
+
106
+ const mainConfig = editor.requireSourceFile('src/main.ts');
107
+ const bootstrapOptions = this.getBootstrapOptions(mainConfig);
108
+
109
+ if (!bootstrapOptions) {
110
+ return Log.fail('Could not find options object in bootstrap config, please add the services manually.');
111
+ }
112
+
113
+ bootstrapOptions.insertShorthandPropertyAssignment(0, { name: 'services' });
114
+ mainConfig.addImportDeclaration({
115
+ namedImports: ['services'],
116
+ moduleSpecifier: './services',
117
+ });
118
+
119
+ await editor.save(mainConfig);
120
+ }
121
+
122
+ protected getBootstrapOptions(mainConfig: SourceFile): ObjectLiteralExpression | null {
123
+ const bootstrapAppCall = findDescendant(mainConfig, {
124
+ guard: Node.isCallExpression,
125
+ validate: (callExpression) => callExpression.getExpression().getText() === 'bootstrap',
126
+ skip: SyntaxKind.ImportDeclaration,
127
+ });
128
+ const bootstrapOptions = bootstrapAppCall?.getArguments()[1];
129
+
130
+ if (!Node.isObjectLiteralExpression(bootstrapOptions)) {
131
+ return null;
132
+ }
133
+
134
+ return bootstrapOptions;
135
+ }
136
+
137
+ protected getServicesObject(servicesIndex: SourceFile): ObjectLiteralExpression | null {
138
+ const servicesDeclaration = findDescendant(servicesIndex, {
139
+ guard: Node.isVariableDeclaration,
140
+ validate: (variableDeclaration) => variableDeclaration.getName() === 'services',
141
+ });
142
+ const servicesObject = servicesDeclaration?.getInitializer();
143
+
144
+ if (!Node.isObjectLiteralExpression(servicesObject)) {
145
+ return null;
146
+ }
147
+
148
+ return servicesObject;
149
+ }
150
+
151
+ }
@@ -0,0 +1,15 @@
1
+ import { URL, fileURLToPath } from 'node:url';
2
+
3
+ import Command from '@aerogel/cli/commands/Command';
4
+ import Log from '@aerogel/cli/lib/Log';
5
+ export class InfoCommand extends Command {
6
+
7
+ protected static override command: string = 'info';
8
+ protected static override description: string = 'Show debugging information about the CLI';
9
+
10
+ protected override async run(): Promise<void> {
11
+ Log.info('[AerogelJS CLI info]');
12
+ Log.info('Installation directory: ' + fileURLToPath(new URL(/* @vite-ignore */ './', import.meta.url)));
13
+ }
14
+
15
+ }