ng-app-generator 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,404 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { execSync } = require("child_process");
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+ const readline = require("readline/promises");
7
+ const { stdin: input, stdout: output } = require("node:process");
8
+
9
+ const argWorkspace = process.argv[2];
10
+ const argApp = process.argv[3];
11
+
12
+ const layoutNames = ["general", "main", "narrow"];
13
+
14
+ function createAppFolders(workspacePath, appName) {
15
+ const appPath = path.join(workspacePath, "projects", appName, "src");
16
+ const folders = ["environments", "app/layouts", "app/pages", "app/shared"];
17
+
18
+ folders.forEach((folder) => {
19
+ fs.mkdirSync(path.join(appPath, folder), {
20
+ recursive: true,
21
+ });
22
+ });
23
+ }
24
+
25
+ function readProjectPrefix(workspacePath, appName) {
26
+ const angularJsonPath = path.join(workspacePath, "angular.json");
27
+ const angularJson = JSON.parse(fs.readFileSync(angularJsonPath, "utf8"));
28
+ return angularJson.projects?.[appName]?.prefix || "app";
29
+ }
30
+
31
+ const layoutRouteFiles = {
32
+ general: `import type {Routes} from '@angular/router';
33
+ import {General} from '../general';
34
+
35
+ export const GENERAL_LAYOUT_ROUTES: Routes = [
36
+ {
37
+ path: '',
38
+ component: General,
39
+ children: [
40
+ {
41
+ path: '',
42
+ loadChildren: async () =>
43
+ import('../../narrow/_/narrow-layout.routes').then(
44
+ r => r.NARROW_LAYOUT_ROUTES,
45
+ ),
46
+ }
47
+ ],
48
+ },
49
+ ];
50
+ `,
51
+ narrow: `import type {Routes} from '@angular/router';
52
+ import {Narrow} from '../narrow';
53
+
54
+ export const NARROW_LAYOUT_ROUTES: Routes = [
55
+ {
56
+ path: '',
57
+ component: Narrow,
58
+ children: [
59
+ {
60
+ path: '',
61
+ loadChildren: async () =>
62
+ import('../../main/_/main-layout.routes').then(
63
+ r => r.MAIN_LAYOUT_ROUTES,
64
+ ),
65
+ },
66
+ ],
67
+ },
68
+ ];
69
+ `,
70
+ main: `import type {Routes} from '@angular/router';
71
+ import {Main} from '../main';
72
+
73
+ export const MAIN_LAYOUT_ROUTES: Routes = [
74
+ {
75
+ path: '',
76
+ component: Main,
77
+ children: [],
78
+ },
79
+ ];
80
+ `,
81
+ };
82
+
83
+ function createLayoutFiles(workspacePath, appName) {
84
+ const layoutsPath = path.join(
85
+ workspacePath,
86
+ "projects",
87
+ appName,
88
+ "src",
89
+ "app",
90
+ "layouts",
91
+ );
92
+ const prefix = readProjectPrefix(workspacePath, appName);
93
+
94
+ for (const name of layoutNames) {
95
+ const layoutDir = path.join(layoutsPath, name);
96
+ const routesDir = path.join(layoutDir, "_");
97
+ const className = name.charAt(0).toUpperCase() + name.slice(1);
98
+
99
+ fs.mkdirSync(routesDir, { recursive: true });
100
+
101
+ const component = `import { Component } from '@angular/core';
102
+ import { RouterOutlet } from '@angular/router';
103
+
104
+ @Component({
105
+ selector: '${prefix}-${name}',
106
+ imports: [RouterOutlet],
107
+ templateUrl: './${name}.html',
108
+ styleUrl: './${name}.scss',
109
+ })
110
+ export class ${className} {}
111
+ `;
112
+
113
+ fs.writeFileSync(path.join(layoutDir, `${name}.ts`), component);
114
+ fs.writeFileSync(
115
+ path.join(layoutDir, `${name}.html`),
116
+ "<router-outlet />\n",
117
+ );
118
+ fs.writeFileSync(path.join(layoutDir, `${name}.scss`), "");
119
+ fs.writeFileSync(
120
+ path.join(routesDir, `${name}-layout.routes.ts`),
121
+ layoutRouteFiles[name],
122
+ );
123
+ }
124
+ }
125
+
126
+ function useInlineRouterOutlet(workspacePath, appName) {
127
+ const appDir = path.join(workspacePath, "projects", appName, "src", "app");
128
+ const componentPath = path.join(appDir, "app.ts");
129
+
130
+ for (const fileName of ["app.html", "app.scss"]) {
131
+ const filePath = path.join(appDir, fileName);
132
+ if (fs.existsSync(filePath)) {
133
+ fs.unlinkSync(filePath);
134
+ }
135
+ }
136
+
137
+ if (!fs.existsSync(componentPath)) {
138
+ console.error(`Could not find ${componentPath}.`);
139
+ process.exit(1);
140
+ }
141
+
142
+ const source = fs.readFileSync(componentPath, "utf8");
143
+ const newline = source.includes("\r\n") ? "\r\n" : "\n";
144
+ const templatePattern =
145
+ /^[ \t]*templateUrl:\s*['"]\.\/app\.html['"],?[ \t]*\r?\n[ \t]*styleUrl:\s*['"]\.\/app\.scss['"],?/m;
146
+
147
+ if (!templatePattern.test(source)) {
148
+ console.error(
149
+ `Could not find templateUrl and styleUrl in ${componentPath}.`,
150
+ );
151
+ process.exit(1);
152
+ }
153
+
154
+ const updated = removeAppTitleSignal(
155
+ source.replace(
156
+ templatePattern,
157
+ ` template: '<router-outlet />',${newline} styles: [],`,
158
+ ),
159
+ );
160
+
161
+ fs.writeFileSync(componentPath, updated);
162
+ }
163
+
164
+ function removeAppTitleSignal(source) {
165
+ const withoutTitle = source.replace(
166
+ /^[ \t]*protected readonly title = signal\([\s\S]*?\);[ \t]*\r?\n?/m,
167
+ "",
168
+ );
169
+
170
+ if (withoutTitle === source) {
171
+ console.error(
172
+ 'Could not find "protected readonly title = signal(...)" in app.ts.',
173
+ );
174
+ process.exit(1);
175
+ }
176
+
177
+ if (/\bsignal\s*\(/.test(withoutTitle)) {
178
+ return withoutTitle;
179
+ }
180
+
181
+ return withoutTitle.replace(
182
+ /import\s*\{([^}]+)\}\s*from\s*(['"]@angular\/core['"]);?/,
183
+ (_match, names, from) => {
184
+ const kept = names
185
+ .split(",")
186
+ .map((name) => name.trim())
187
+ .filter((name) => name && name !== "signal");
188
+
189
+ if (kept.length === 0) {
190
+ return "";
191
+ }
192
+
193
+ return `import { ${kept.join(", ")} } from ${from};`;
194
+ },
195
+ );
196
+ }
197
+
198
+ function writeAppRoutes(workspacePath, appName) {
199
+ const routesPath = path.join(
200
+ workspacePath,
201
+ "projects",
202
+ appName,
203
+ "src",
204
+ "app",
205
+ "app.routes.ts",
206
+ );
207
+
208
+ if (!fs.existsSync(routesPath)) {
209
+ console.error(`Could not find ${routesPath}.`);
210
+ process.exit(1);
211
+ }
212
+
213
+ const existing = fs.readFileSync(routesPath, "utf8");
214
+ const newline = existing.includes("\r\n") ? "\r\n" : "\n";
215
+ const contents = `import type {Routes} from '@angular/router';
216
+
217
+ export const routes: Routes = [
218
+ {
219
+ path: '',
220
+ loadChildren: async () =>
221
+ import('./layouts/general/_/general-layout.routes').then(
222
+ r => r.GENERAL_LAYOUT_ROUTES,
223
+ ),
224
+ },
225
+ ];
226
+ `.replace(/\n/g, newline);
227
+
228
+ fs.writeFileSync(routesPath, contents);
229
+ }
230
+
231
+ async function formatDocuments(workspacePath, appName) {
232
+ let prettier;
233
+
234
+ try {
235
+ prettier = require(require.resolve("prettier", { paths: [workspacePath] }));
236
+ } catch {
237
+ console.error(
238
+ "Prettier is not installed in the workspace, so the generated files could not be formatted.",
239
+ );
240
+ process.exit(1);
241
+ }
242
+ const appSrc = path.join(workspacePath, "projects", appName, "src");
243
+ const files = [];
244
+
245
+ function collect(dir) {
246
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
247
+ const fullPath = path.join(dir, entry.name);
248
+ if (entry.isDirectory()) {
249
+ collect(fullPath);
250
+ continue;
251
+ }
252
+
253
+ if (/\.(ts|html|scss|css)$/.test(entry.name)) {
254
+ files.push(fullPath);
255
+ }
256
+ }
257
+ }
258
+
259
+ collect(appSrc);
260
+
261
+ for (const file of files) {
262
+ const config =
263
+ (await prettier.resolveConfig(file, { editorconfig: true })) || {};
264
+ const source = fs.readFileSync(file, "utf8");
265
+ const formatted = await prettier.format(source, {
266
+ ...config,
267
+ filepath: file,
268
+ });
269
+
270
+ if (formatted !== source) {
271
+ fs.writeFileSync(file, formatted);
272
+ }
273
+ }
274
+ }
275
+
276
+ async function generateApplication(workspacePath, appName) {
277
+ execSync(`ng generate application ${appName} --skip-tests --style=scss`, {
278
+ cwd: workspacePath,
279
+ stdio: "inherit",
280
+ });
281
+
282
+ createAppFolders(workspacePath, appName);
283
+ createLayoutFiles(workspacePath, appName);
284
+ useInlineRouterOutlet(workspacePath, appName);
285
+ writeAppRoutes(workspacePath, appName);
286
+ await formatDocuments(workspacePath, appName);
287
+ }
288
+
289
+ function workspaceHasAngularJson(workspacePath) {
290
+ return fs.existsSync(path.join(workspacePath, "angular.json"));
291
+ }
292
+
293
+ async function ask(rl, question, fallback = "") {
294
+ const answer = (await rl.question(question)).trim();
295
+ return answer || fallback;
296
+ }
297
+
298
+ async function main() {
299
+ const rl = readline.createInterface({ input, output });
300
+
301
+ try {
302
+ console.log("\nWhat do you want to generate?");
303
+ console.log(" 1) Full workspace (new Angular workspace + application)");
304
+ console.log(" 2) Application only (inside an existing workspace)\n");
305
+
306
+ const choice = (await rl.question("Choose [1/2]: ")).trim().toLowerCase();
307
+ const fullWorkspace =
308
+ choice === "1" || choice === "full" || choice === "workspace";
309
+ const appOnly =
310
+ choice === "2" || choice === "app" || choice === "application";
311
+
312
+ if (!fullWorkspace && !appOnly) {
313
+ console.error(
314
+ "Invalid choice. Enter 1 for a full workspace or 2 for an application only.",
315
+ );
316
+ process.exit(1);
317
+ }
318
+
319
+ if (fullWorkspace) {
320
+ const workspaceName = await ask(
321
+ rl,
322
+ argWorkspace
323
+ ? `Workspace name [${argWorkspace}]: `
324
+ : "Workspace name: ",
325
+ argWorkspace,
326
+ );
327
+
328
+ if (!workspaceName) {
329
+ console.error("Please provide a workspace name.");
330
+ process.exit(1);
331
+ }
332
+
333
+ const defaultApp = argApp || "app";
334
+ const appName = await ask(
335
+ rl,
336
+ `Application name [${defaultApp}]: `,
337
+ defaultApp,
338
+ );
339
+
340
+ rl.close();
341
+
342
+ execSync(`ng new ${workspaceName} --no-create-application`, {
343
+ stdio: "inherit",
344
+ });
345
+
346
+ await generateApplication(workspaceName, appName);
347
+ console.log("Angular workspace created successfully!");
348
+ return;
349
+ }
350
+
351
+ const cwdIsWorkspace = workspaceHasAngularJson(process.cwd());
352
+ const argIsWorkspace =
353
+ argWorkspace && workspaceHasAngularJson(path.resolve(argWorkspace));
354
+ const defaultWorkspace = argIsWorkspace
355
+ ? path.resolve(argWorkspace)
356
+ : cwdIsWorkspace
357
+ ? process.cwd()
358
+ : "";
359
+
360
+ const workspacePathInput = await ask(
361
+ rl,
362
+ defaultWorkspace
363
+ ? `Workspace path [${defaultWorkspace}]: `
364
+ : "Workspace path: ",
365
+ defaultWorkspace,
366
+ );
367
+
368
+ if (!workspacePathInput) {
369
+ console.error("Please provide the existing workspace path.");
370
+ process.exit(1);
371
+ }
372
+
373
+ const workspacePath = path.resolve(workspacePathInput);
374
+
375
+ if (!workspaceHasAngularJson(workspacePath)) {
376
+ console.error(`No angular.json found in ${workspacePath}.`);
377
+ process.exit(1);
378
+ }
379
+
380
+ const defaultApp = argApp || (!argIsWorkspace ? argWorkspace : "") || "";
381
+ const appName = await ask(
382
+ rl,
383
+ defaultApp ? `Application name [${defaultApp}]: ` : "Application name: ",
384
+ defaultApp,
385
+ );
386
+
387
+ if (!appName) {
388
+ console.error("Please provide an application name.");
389
+ process.exit(1);
390
+ }
391
+
392
+ rl.close();
393
+
394
+ await generateApplication(workspacePath, appName);
395
+ console.log("Angular application created successfully!");
396
+ } finally {
397
+ rl.close();
398
+ }
399
+ }
400
+
401
+ main().catch((error) => {
402
+ console.error(error.message || error);
403
+ process.exit(1);
404
+ });
package/package.json CHANGED
@@ -1,6 +1,14 @@
1
1
  {
2
2
  "name": "ng-app-generator",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "",
5
+ "main": "index.js",
6
+ "bin": {
7
+ "app-generator": "bin/create-angular-app.js"
8
+ },
9
+ "scripts": {},
10
+ "keywords": [],
11
+ "author": "",
12
+ "license": "ISC",
13
+ "type": "commonjs"
14
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.